diff --git a/.github/actions/setup-worldline/action.yml b/.github/actions/setup-worldline/action.yml index 1e8f13e9..c08e409d 100644 --- a/.github/actions/setup-worldline/action.yml +++ b/.github/actions/setup-worldline/action.yml @@ -2,7 +2,7 @@ name: Setup native Bazel build tools description: Install Python and the pinned Bazelisk for source builds inputs: architecture: - description: Python architecture for native ABI verification + description: Python architecture for native build tools default: x64 runs: using: composite @@ -14,4 +14,4 @@ runs: - uses: bazel-contrib/setup-bazel@0.19.0 with: bazelisk-version: '1.29.0' - module-root: native/worldline + module-root: native diff --git a/.github/workflows/build-all-platforms.yml b/.github/workflows/build-all-platforms.yml index fbd809cf..77ac0729 100644 --- a/.github/workflows/build-all-platforms.yml +++ b/.github/workflows/build-all-platforms.yml @@ -43,6 +43,11 @@ permissions: env: AVALONIA_TELEMETRY_OPTOUT: "1" VersionLyrics: ${{ inputs.version_lyrics }} + Configuration: Release + Version: ${{ inputs.version }} + BuildNumber: ${{ inputs.build_number }} + SourceCommit: ${{ inputs.source_sha }} + ActionRunId: ${{ inputs.action_run_id }} jobs: # ============================================================ @@ -82,6 +87,8 @@ jobs: linux: name: Linux ${{ matrix.arch }} runs-on: ${{ matrix.runner }} + env: + RuntimeIdentifier: ${{ matrix.rid }} strategy: fail-fast: false @@ -109,15 +116,11 @@ jobs: with: architecture: ${{ matrix.arch }} - - name: Build and test Worldline - shell: bash - run: python native/worldline/build.py --rid ${{ matrix.rid }} --test - - name: Collect Build Metadata shell: bash run: | - echo "BUILD_TIMESTAMP=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> "$GITHUB_ENV" - echo "BUILD_MACHINE=${RUNNER_OS} / $(uname -srm)" >> "$GITHUB_ENV" + echo "BuildTimestamp=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> "$GITHUB_ENV" + echo "BuildMachine=${RUNNER_OS} / $(uname -srm)" >> "$GITHUB_ENV" - name: Publish Linux ${{ matrix.arch }} shell: bash @@ -126,20 +129,7 @@ jobs: dotnet publish \ OpenUtauMobile.Linux/OpenUtauMobile.Linux.csproj \ - -c Release \ - -r "${{ matrix.rid }}" \ - --self-contained true \ - -p:PublishDir="$PUBLISH_DIR/" \ - -p:Version="${{ inputs.version }}" \ - -p:BuildNumber=${{ inputs.build_number }} \ - -p:BuildTimestamp="$BUILD_TIMESTAMP" \ - -p:BuildMachine="$BUILD_MACHINE" \ - -p:SourceCommit=${{ inputs.source_sha }} \ - -p:ActionRunId=${{ inputs.action_run_id }} - - - name: Verify native runtime loading - shell: bash - run: python native/verify-runtime.py "artifacts/publish/${{ matrix.rid }}" + -o "$PUBLISH_DIR" - name: Package Linux ${{ matrix.arch }} shell: bash @@ -147,7 +137,7 @@ jobs: PUBLISH_DIR="${GITHUB_WORKSPACE}/artifacts/publish/${{ matrix.rid }}" PACKAGE="${GITHUB_WORKSPACE}/artifacts/OpenUtauMobile-build${{ inputs.build_number }}-linux-${{ matrix.arch }}.tar.gz" - chmod +x "$PUBLISH_DIR/OpenUtauMobile.Linux" || true + chmod +x "$PUBLISH_DIR/OpenUtauMobile.Linux" tar \ -C "$PUBLISH_DIR" \ @@ -171,6 +161,8 @@ jobs: windows: name: Windows ${{ matrix.arch }} runs-on: ${{ matrix.runner }} + env: + RuntimeIdentifier: ${{ matrix.rid }} strategy: fail-fast: false @@ -198,19 +190,15 @@ jobs: with: architecture: ${{ matrix.arch }} - - name: Build and test Worldline - shell: bash - run: python native/worldline/build.py --rid ${{ matrix.rid }} --test - - name: Collect Build Metadata shell: pwsh run: | $timestamp = [DateTime]::UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ") - "BUILD_TIMESTAMP=$timestamp" | + "BuildTimestamp=$timestamp" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append - "BUILD_MACHINE=$env:RUNNER_OS / $env:PROCESSOR_ARCHITECTURE" | + "BuildMachine=$env:RUNNER_OS / $env:PROCESSOR_ARCHITECTURE" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append - name: Publish Windows ${{ matrix.arch }} @@ -220,20 +208,7 @@ jobs: dotnet publish ` OpenUtauMobile.Windows/OpenUtauMobile.Windows.csproj ` - -c Release ` - -r "${{ matrix.rid }}" ` - --self-contained true ` - -p:PublishDir="$publishDir/" ` - -p:Version="${{ inputs.version }}" ` - -p:BuildNumber=${{ inputs.build_number }} ` - -p:BuildTimestamp="$env:BUILD_TIMESTAMP" ` - -p:BuildMachine="$env:BUILD_MACHINE" ` - -p:SourceCommit=${{ inputs.source_sha }} ` - -p:ActionRunId=${{ inputs.action_run_id }} - - - name: Verify native runtime loading - shell: bash - run: python native/verify-runtime.py "artifacts/publish/${{ matrix.rid }}" + -o "$publishDir" - name: Package Windows ${{ matrix.arch }} shell: pwsh @@ -265,6 +240,8 @@ jobs: macos: name: macOS ${{ matrix.arch }} runs-on: ${{ matrix.runner }} + env: + RuntimeIdentifier: ${{ matrix.rid }} strategy: fail-fast: false @@ -294,15 +271,11 @@ jobs: with: architecture: ${{ matrix.arch }} - - name: Build and test Worldline - shell: bash - run: python native/worldline/build.py --rid ${{ matrix.rid }} --test - - name: Collect Build Metadata shell: bash run: | - echo "BUILD_TIMESTAMP=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> "$GITHUB_ENV" - echo "BUILD_MACHINE=${RUNNER_OS} / $(uname -srm)" >> "$GITHUB_ENV" + echo "BuildTimestamp=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> "$GITHUB_ENV" + echo "BuildMachine=${RUNNER_OS} / $(uname -srm)" >> "$GITHUB_ENV" - name: Publish macOS ${{ matrix.arch }} shell: bash @@ -311,20 +284,7 @@ jobs: dotnet publish \ OpenUtauMobile.MacOS/OpenUtauMobile.MacOS.csproj \ - -c Release \ - -r "${{ matrix.rid }}" \ - --self-contained true \ - -p:PublishDir="$PUBLISH_DIR/" \ - -p:Version="${{ inputs.version }}" \ - -p:BuildNumber=${{ inputs.build_number }} \ - -p:BuildTimestamp="$BUILD_TIMESTAMP" \ - -p:BuildMachine="$BUILD_MACHINE" \ - -p:SourceCommit=${{ inputs.source_sha }} \ - -p:ActionRunId=${{ inputs.action_run_id }} - - - name: Verify native runtime loading - shell: bash - run: python native/verify-runtime.py "artifacts/publish/${{ matrix.rid }}" + -o "$PUBLISH_DIR" - name: Package macOS ${{ matrix.arch }} shell: bash @@ -332,7 +292,7 @@ jobs: PUBLISH_DIR="${GITHUB_WORKSPACE}/artifacts/publish/${{ matrix.rid }}" PACKAGE="${GITHUB_WORKSPACE}/artifacts/OpenUtauMobile-build${{ inputs.build_number }}-macos-${{ matrix.arch }}.tar.gz" - chmod +x "$PUBLISH_DIR/OpenUtauMobile.MacOS" || true + chmod +x "$PUBLISH_DIR/OpenUtauMobile.MacOS" tar \ -C "$PUBLISH_DIR" \ diff --git a/.github/workflows/build-android.yml b/.github/workflows/build-android.yml index 79ba8d02..ddc73b99 100644 --- a/.github/workflows/build-android.yml +++ b/.github/workflows/build-android.yml @@ -52,6 +52,12 @@ permissions: env: AVALONIA_TELEMETRY_OPTOUT: "1" VersionLyrics: ${{ inputs.version_lyrics }} + Configuration: Release + RuntimeIdentifier: ${{ inputs.rid }} + Version: ${{ inputs.version }} + BuildNumber: ${{ inputs.build_number }} + SourceCommit: ${{ inputs.source_sha }} + ActionRunId: ${{ inputs.action_run_id }} jobs: build: @@ -89,31 +95,22 @@ jobs: shell: bash run: | set -euo pipefail - command -v sdkmanager - NDK_VERSION="$(tr -d '\r\n' < native/game/android-ndk-version.txt)" - SDK_ROOT="${ANDROID_HOME:-${ANDROID_SDK_ROOT:?Android SDK is required}}" - sdkmanager --sdk_root="$SDK_ROOT" "ndk;$NDK_VERSION" - test -f "$SDK_ROOT/ndk/$NDK_VERSION/source.properties" - echo "OPUM_ANDROID_NDK=$SDK_ROOT/ndk/$NDK_VERSION" >> "$GITHUB_ENV" + sdkmanager "ndk;$(tr -d '\r\n' < native/android-ndk-version.txt)" - name: Create Swap Space shell: bash run: | SWAP_FILE=/runner-swapfile - if [ ! -f "$SWAP_FILE" ]; then - sudo fallocate -l 6G "$SWAP_FILE" - sudo chmod 600 "$SWAP_FILE" - sudo mkswap "$SWAP_FILE" - fi - sudo swapon "$SWAP_FILE" 2>/dev/null || true - free -h - swapon --show + sudo fallocate -l 6G "$SWAP_FILE" + sudo chmod 600 "$SWAP_FILE" + sudo mkswap "$SWAP_FILE" + sudo swapon "$SWAP_FILE" - name: Collect Build Metadata shell: bash run: | - echo "BUILD_TIMESTAMP=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> "$GITHUB_ENV" - echo "BUILD_MACHINE=${RUNNER_OS} / $(uname -srm)" >> "$GITHUB_ENV" + echo "BuildTimestamp=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> "$GITHUB_ENV" + echo "BuildMachine=${RUNNER_OS} / $(uname -srm)" >> "$GITHUB_ENV" - name: Decode Android Keystore if: inputs.release_signing @@ -122,16 +119,6 @@ jobs: ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }} run: printf '%s' "$ANDROID_KEYSTORE_BASE64" | base64 --decode > signing.keystore - # 必须按最终 RID 显式还原;发布阶段复用同一资产图,防止宿主平台原生资产混入 APK。 - # 全局指定 Mono,让引用的普通 .NET 类库也使用 Mono,避免 armhf 请求不存在的 CoreCLR linux-bionic-arm 包。 - - name: Restore Android ${{ inputs.arch }} - shell: bash - run: | - dotnet restore OpenUtauMobile.Android/OpenUtauMobile.Android.csproj \ - -r "${{ inputs.rid }}" \ - -p:UseMonoRuntime=true \ - -p:Configuration=Release - - name: Publish Android ${{ inputs.arch }} shell: bash env: @@ -143,8 +130,6 @@ jobs: set -euo pipefail signing_args=(-p:AndroidKeyStore=false) if [ "$RELEASE_SIGNING" = "true" ]; then - test -s signing.keystore - test -n "$KEYSTORE_PASSWORD" && test -n "$KEY_ALIAS" && test -n "$KEY_PASSWORD" signing_args=(-p:AndroidKeyStore=true "-p:AndroidSigningKeyStore=$GITHUB_WORKSPACE/signing.keystore" "-p:AndroidSigningStorePass=$KEYSTORE_PASSWORD" @@ -152,131 +137,20 @@ jobs: "-p:AndroidSigningKeyPass=$KEY_PASSWORD") fi dotnet publish OpenUtauMobile.Android/OpenUtauMobile.Android.csproj \ - --no-restore \ - -c Release \ - -f net10.0-android36.0 \ - -r "${{ inputs.rid }}" \ - -p:UseMonoRuntime=true \ - -p:Version="${{ inputs.version }}" \ - -p:BuildNumber=${{ inputs.build_number }} \ - -p:BuildTimestamp="$BUILD_TIMESTAMP" \ - -p:BuildMachine="$BUILD_MACHINE" \ - -p:SourceCommit=${{ inputs.source_sha }} \ - -p:ActionRunId=${{ inputs.action_run_id }} \ - -p:AndroidNdkDirectory="$OPUM_ANDROID_NDK" \ - -p:AndroidPackageFormat=apk \ "${signing_args[@]}" - - name: Verify and prepare Android artifact + - name: Prepare Android artifact shell: bash run: | set -euo pipefail PUBLISH_DIR="OpenUtauMobile.Android/bin/Release/net10.0-android36.0/${{ inputs.rid }}/publish" ARTIFACT_DIR="artifacts/android-${{ inputs.arch }}" - VERIFY_DIR="artifacts/verification-android-${{ inputs.arch }}" - - case "${{ inputs.rid }}" in - android-arm64) EXPECTED_ABI=arm64-v8a ;; - android-arm) EXPECTED_ABI=armeabi-v7a ;; - android-x64) EXPECTED_ABI=x86_64 ;; - android-x86) EXPECTED_ABI=x86 ;; - *) echo "::error::不支持的 Android RID:${{ inputs.rid }}"; exit 1 ;; - esac - - mkdir -p "$ARTIFACT_DIR" "$VERIFY_DIR/native" - echo "===== Publish files =====" - find "$PUBLISH_DIR" -maxdepth 1 -type f -printf '%f\n' - - mapfile -t SIGNED_APKS < <(find "$PUBLISH_DIR" -maxdepth 1 -type f -iname '*-signed.apk' -print) - if [ "${#SIGNED_APKS[@]}" -ne 1 ]; then - echo "::error::应当生成且仅生成一个已签名 APK,实际为 ${#SIGNED_APKS[@]} 个" - exit 1 - fi - SIGNED_APK="${SIGNED_APKS[0]}" - python native/verify-android-runtime.py "$SIGNED_APK" "${{ inputs.rid }}" - - ANDROID_SDK="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-}}" - if [ -z "$ANDROID_SDK" ] || [ ! -d "$ANDROID_SDK/build-tools" ]; then - echo "::error::找不到 Android SDK build-tools 目录,无法核对 APK 版本号" - exit 1 - fi - AAPT="$(find "$ANDROID_SDK/build-tools" -type f -name aapt -print | sort -V | tail -n 1)" - if [ -z "$AAPT" ]; then - echo "::error::找不到 Android Asset Packaging Tool,无法核对 APK 版本号" - exit 1 - fi - PACKAGE_BADGING="$("$AAPT" dump badging "$SIGNED_APK")" - APK_VERSION_CODE="$(sed -n "s/.*versionCode='\([^']*\)'.*/\1/p" <<< "$PACKAGE_BADGING")" - APK_VERSION_NAME="$(sed -n "s/.*versionName='\([^']*\)'.*/\1/p" <<< "$PACKAGE_BADGING")" - if [ "$APK_VERSION_CODE" != "${{ inputs.build_number }}" ]; then - echo "::error::APK versionCode 未继承调用方构建号。期望 ${{ inputs.build_number }},实际 $APK_VERSION_CODE" - exit 1 - fi - if [ "$APK_VERSION_NAME" != "${{ inputs.version }}" ]; then - echo "::error::APK versionName 未继承调用方版本。期望 ${{ inputs.version }},实际 $APK_VERSION_NAME" - exit 1 - fi - - mapfile -t PACKAGED_ABIS < <( - unzip -Z1 "$SIGNED_APK" | - sed -n 's#^lib/\([^/]*\)/.*\.so$#\1#p' | - sort -u - ) - if [ "${#PACKAGED_ABIS[@]}" -ne 1 ] || [ "${PACKAGED_ABIS[0]}" != "$EXPECTED_ABI" ]; then - printf '::error::APK 原生 ABI 与 RID 不一致。期望 %s,实际:%s\n' \ - "$EXPECTED_ABI" "${PACKAGED_ABIS[*]:-}" - exit 1 - fi - - for LIBRARY in libworldline.so libonnxruntime.so libonnxruntime4j_jni.so libopum_game.so; do - ENTRY="lib/$EXPECTED_ABI/$LIBRARY" - COUNT="$(unzip -Z1 "$SIGNED_APK" | grep -Fxc "$ENTRY" || true)" - if [ "$COUNT" -ne 1 ]; then - echo "::error::$ENTRY 应当在 APK 中恰好出现一次,实际为 $COUNT 次" - exit 1 - fi - unzip -p "$SIGNED_APK" "$ENTRY" > "$VERIFY_DIR/native/$LIBRARY" - done - - for LIBRARY in "$VERIFY_DIR/native/"*.so; do - DYNAMIC_INFO="$VERIFY_DIR/$(basename "$LIBRARY").dynamic.txt" - readelf -d "$LIBRARY" > "$DYNAMIC_INFO" - if grep -E 'libdl\.so\.2|libc\.so\.6|libm\.so\.6|libpthread\.so\.0|librt\.so\.1|ld-linux' "$DYNAMIC_INFO"; then - echo "::error::$(basename "$LIBRARY") 包含 Linux/glibc 依赖,不是 Android 原生库" - exit 1 - fi - done - - find "$VERIFY_DIR/native" -maxdepth 1 -type f -name '*.so' -print0 | - sort -z | - xargs -0 sha256sum | - sed "s#$VERIFY_DIR/native/##" > "$VERIFY_DIR/native-libraries.sha256" - - cat > "$VERIFY_DIR/build-contract.txt" < "$PACKAGE.sha256" - sha256sum --check "$PACKAGE.sha256" - name: Upload Android ${{ inputs.arch }} uses: actions/upload-artifact@v7 @@ -295,13 +168,3 @@ jobs: artifacts/android-${{ inputs.arch }}/OpenUtauMobile-build${{ inputs.build_number }}-android-${{ inputs.arch }}.apk.sha256 if-no-files-found: error compression-level: 0 - - - name: Upload Android ${{ inputs.arch }} verification - uses: actions/upload-artifact@v7 - with: - name: verification-android-${{ inputs.arch }} - path: | - artifacts/verification-android-${{ inputs.arch }}/build-contract.txt - artifacts/verification-android-${{ inputs.arch }}/native-libraries.sha256 - artifacts/verification-android-${{ inputs.arch }}/*.dynamic.txt - if-no-files-found: error diff --git a/.github/workflows/build-browser.yml b/.github/workflows/build-browser.yml index bd0b0a9d..8865b96c 100644 --- a/.github/workflows/build-browser.yml +++ b/.github/workflows/build-browser.yml @@ -28,6 +28,11 @@ jobs: env: AVALONIA_TELEMETRY_OPTOUT: "1" VersionLyrics: ${{ inputs.version_lyrics }} + Configuration: Release + Version: ${{ inputs.version }} + BuildNumber: ${{ inputs.build_number }} + SourceCommit: ${{ inputs.source_sha || github.sha }} + ActionRunId: ${{ inputs.action_run_id || github.run_id }} steps: - uses: actions/checkout@v4 with: @@ -39,23 +44,11 @@ jobs: - name: Install WebAssembly workload run: dotnet workload install wasm-tools - name: Publish Browser with Worldline - env: - PRODUCT_VERSION: ${{ inputs.version }} - BUILD_NUMBER: ${{ inputs.build_number }} - SOURCE_SHA: ${{ inputs.source_sha || github.sha }} - ACTION_RUN_ID: ${{ inputs.action_run_id || github.run_id }} run: | - args=() - if [ -n "$PRODUCT_VERSION" ]; then args+=("-p:Version=$PRODUCT_VERSION"); fi dotnet publish OpenUtauMobile.Browser/OpenUtauMobile.Browser.csproj \ - -c Release -o artifacts/publish/browser-wasm \ - -p:BuildNumber="$BUILD_NUMBER" -p:SourceCommit="$SOURCE_SHA" \ - -p:ActionRunId="$ACTION_RUN_ID" "${args[@]}" - - name: Verify Worldline WASM ABI - run: python native/worldline/verify_browser.py artifacts/worldline-native/browser-wasm + -o artifacts/publish/browser-wasm - name: Package Browser static files run: | - test -f artifacts/publish/browser-wasm/wwwroot/licenses/Worldline/worldline-build.json tar -C artifacts/publish/browser-wasm/wwwroot -czf artifacts/OpenUtauMobile-browser-wasm.tar.gz . cd artifacts sha256sum OpenUtauMobile-browser-wasm.tar.gz > OpenUtauMobile-browser-wasm.tar.gz.sha256 @@ -67,9 +60,3 @@ jobs: artifacts/OpenUtauMobile-browser-wasm.tar.gz artifacts/OpenUtauMobile-browser-wasm.tar.gz.sha256 if-no-files-found: error - - name: Upload native verification evidence - uses: actions/upload-artifact@v4 - with: - name: worldline-browser-wasm - path: artifacts/worldline-native/browser-wasm/ - if-no-files-found: error diff --git a/.github/workflows/build-ios.yml b/.github/workflows/build-ios.yml index 1f8e196f..9f1d0605 100644 --- a/.github/workflows/build-ios.yml +++ b/.github/workflows/build-ios.yml @@ -34,6 +34,12 @@ jobs: runs-on: xcode-27 timeout-minutes: 90 env: + Configuration: Release + RuntimeIdentifier: ios-arm64 + Version: ${{ inputs.version }} + BuildNumber: ${{ inputs.build_number }} + SourceCommit: ${{ inputs.source_sha }} + ActionRunId: ${{ inputs.action_run_id }} AVALONIA_TELEMETRY_OPTOUT: "1" DOTNET_CLI_TELEMETRY_OPTOUT: "1" DOTNET_NOLOGO: "1" @@ -57,39 +63,10 @@ jobs: run: | set -euo pipefail - echo "BUILD_TIMESTAMP=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> "$GITHUB_ENV" - echo "BUILD_MACHINE=${RUNNER_OS} / $(uname -srm)" >> "$GITHUB_ENV" + echo "BuildTimestamp=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> "$GITHUB_ENV" + echo "BuildMachine=${RUNNER_OS} / $(uname -srm)" >> "$GITHUB_ENV" mkdir -p "${GITHUB_WORKSPACE}/artifacts/ios-arm64-logs" - - name: Validate iOS Toolchain - shell: bash - run: | - set -euo pipefail - - echo "::group::.NET and installed workloads" - dotnet --info - dotnet workload list - echo "::endgroup::" - - echo "::group::Xcode and iPhoneOS SDK" - if [ ! -d "$DEVELOPER_DIR" ]; then - echo "::error::Required Xcode developer directory is missing: $DEVELOPER_DIR" - ls -1d /Applications/Xcode_*.app 2>/dev/null | sed -n '1,20p' || true - exit 1 - fi - - XCODE_VERSION="$(xcodebuild -version | awk '/^Xcode / { print $2 }')" - if [[ "$XCODE_VERSION" != "27.0" && "$XCODE_VERSION" != 27.0.* ]]; then - echo "::error::Expected Xcode 27.0, selected $XCODE_VERSION from $DEVELOPER_DIR" - exit 1 - fi - - echo "Developer directory: $DEVELOPER_DIR" - xcodebuild -version - echo "iPhoneOS SDK: $(xcrun --sdk iphoneos --show-sdk-version)" - echo "iPhoneOS SDK path: $(xcrun --sdk iphoneos --show-sdk-path)" - echo "::endgroup::" - - name: Restore iOS Workload shell: bash run: | @@ -119,24 +96,6 @@ jobs: dotnet publish \ OpenUtauMobile.iOS/OpenUtauMobile.iOS.csproj \ - --force \ - -c Release \ - -f net10.0-ios \ - -r ios-arm64 \ - -p:Version="${{ inputs.version }}" \ - -p:BuildNumber=${{ inputs.build_number }} \ - -p:BuildTimestamp="$BUILD_TIMESTAMP" \ - -p:BuildMachine="$BUILD_MACHINE" \ - -p:SourceCommit=${{ inputs.source_sha }} \ - -p:ActionRunId=${{ inputs.action_run_id }} \ - -p:PublishAot=false \ - -p:UseMonoRuntime=true \ - -p:MtouchUseLlvm=false \ - -p:UseInterpreter=false \ - -p:TrimMode=partial \ - -p:MtouchLink=SdkOnly \ - -p:EnableAssemblyILStripping=false \ - -p:_IsDedupEnabled=false \ -p:EnableCodeSigning=false \ -p:BuildIpa=true \ -p:IpaPackagePath="$IPA_PATH" \ @@ -145,78 +104,6 @@ jobs: ls -lh "$IPA_PATH" - - name: Validate iOS ARM64 Mono AOT Unsigned IPA - shell: bash - run: | - set -euo pipefail - - IPA_PATH="${GITHUB_WORKSPACE}/artifacts/ios-arm64/OpenUtauMobile-build${{ inputs.build_number }}-ios-arm64-mono-aot-unsigned.ipa" - VERIFY_DIR="${RUNNER_TEMP}/opum-ios-arm64-verify" - - unzip -tq "$IPA_PATH" - mkdir -p "$VERIFY_DIR" - unzip -q "$IPA_PATH" -d "$VERIFY_DIR" - - APP_COUNT="$(find "$VERIFY_DIR/Payload" -maxdepth 1 -type d -name '*.app' | wc -l | tr -d ' ')" - if [ "$APP_COUNT" != "1" ]; then - echo "::error::IPA must contain exactly one app bundle, found $APP_COUNT" - exit 1 - fi - - APP_DIR="$(find "$VERIFY_DIR/Payload" -maxdepth 1 -type d -name '*.app' -print -quit)" - INFO_PLIST="$APP_DIR/Info.plist" - EXECUTABLE="$(plutil -extract CFBundleExecutable raw "$INFO_PLIST")" - BUNDLE_ID="$(plutil -extract CFBundleIdentifier raw "$INFO_PLIST")" - DISPLAY_VERSION="$(plutil -extract CFBundleShortVersionString raw "$INFO_PLIST")" - BUILD_VERSION="$(plutil -extract CFBundleVersion raw "$INFO_PLIST")" - PLATFORM="$(plutil -extract CFBundleSupportedPlatforms.0 raw "$INFO_PLIST")" - ARCHS="$(lipo -archs "$APP_DIR/$EXECUTABLE")" - python native/worldline/verify_static.py \ - artifacts/worldline-native/ios-arm64/libworldline.a ios-arm64 \ - --nm "$(xcrun --find nm)" --app-bundle "$APP_DIR" - EXPECTED_BUNDLE_ID="$(dotnet msbuild \ - OpenUtauMobile.iOS/OpenUtauMobile.iOS.csproj \ - -nologo \ - -getProperty:ApplicationId \ - -p:Configuration=Release \ - -p:TargetFramework=net10.0-ios \ - -p:RuntimeIdentifier=ios-arm64)" - - if [ "$BUNDLE_ID" != "$EXPECTED_BUNDLE_ID" ]; then - echo "::error::Bundle ID is $BUNDLE_ID, expected $EXPECTED_BUNDLE_ID" - exit 1 - fi - if [ "$DISPLAY_VERSION" != "${{ inputs.version }}" ]; then - echo "::error::CFBundleShortVersionString is $DISPLAY_VERSION, expected ${{ inputs.version }}" - exit 1 - fi - if [ "$BUILD_VERSION" != "${{ inputs.build_number }}" ]; then - echo "::error::CFBundleVersion is $BUILD_VERSION, expected ${{ inputs.build_number }}" - exit 1 - fi - if [ "$PLATFORM" != "iPhoneOS" ]; then - echo "::error::IPA targets $PLATFORM instead of iPhoneOS" - exit 1 - fi - if [ "$ARCHS" != "arm64" ]; then - echo "::error::App executable architectures are $ARCHS instead of arm64" - exit 1 - fi - if [ -e "$APP_DIR/_CodeSignature" ] || [ -e "$APP_DIR/embedded.mobileprovision" ]; then - echo "::error::App bundle unexpectedly contains signing assets" - exit 1 - fi - if codesign --verify --deep --strict "$APP_DIR" 2>"$VERIFY_DIR/codesign.txt"; then - echo "::error::App bundle unexpectedly passed code-sign verification" - exit 1 - fi - - echo "Bundle ID: $BUNDLE_ID" - echo "Version: $DISPLAY_VERSION ($BUILD_VERSION)" - echo "Platform: $PLATFORM" - echo "Architectures: $ARCHS" - echo "Code signature: unsigned, verified" - - name: Upload iOS Failure Diagnostics if: failure() uses: actions/upload-artifact@v4 @@ -237,7 +124,6 @@ jobs: set -euo pipefail PACKAGE="OpenUtauMobile-build${{ inputs.build_number }}-ios-arm64-mono-aot-unsigned.ipa" shasum -a 256 "$PACKAGE" > "$PACKAGE.sha256" - shasum -a 256 --check "$PACKAGE.sha256" - name: Upload iOS ARM64 Mono AOT Unsigned IPA uses: actions/upload-artifact@v4 diff --git a/.github/workflows/pr-requirements.yml b/.github/workflows/pr-requirements.yml index 3e54f71c..81d696e1 100644 --- a/.github/workflows/pr-requirements.yml +++ b/.github/workflows/pr-requirements.yml @@ -13,6 +13,8 @@ jobs: name: PR build test for Android ARM64 env: AVALONIA_TELEMETRY_OPTOUT: "1" + Configuration: Release + RuntimeIdentifier: android-arm64 runs-on: ubuntu-latest steps: @@ -49,32 +51,8 @@ jobs: shell: bash run: | set -euo pipefail - command -v sdkmanager - NDK_VERSION="$(tr -d '\r\n' < native/game/android-ndk-version.txt)" - SDK_ROOT="${ANDROID_HOME:-${ANDROID_SDK_ROOT:?Android SDK is required}}" - sdkmanager --sdk_root="$SDK_ROOT" "ndk;$NDK_VERSION" - test -f "$SDK_ROOT/ndk/$NDK_VERSION/source.properties" - echo "OPUM_ANDROID_NDK=$SDK_ROOT/ndk/$NDK_VERSION" >> "$GITHUB_ENV" - - - name: Restore - run: dotnet restore OpenUtauMobile.Android/OpenUtauMobile.Android.csproj -r android-arm64 -p:Configuration=Release + sdkmanager "ndk;$(tr -d '\r\n' < native/android-ndk-version.txt)" - name: Build Android ARM64 run: | - dotnet build OpenUtauMobile.Android/OpenUtauMobile.Android.csproj \ - -c Release \ - -f net10.0-android36.0 \ - --no-restore \ - -p:RuntimeIdentifier=android-arm64 \ - -p:AndroidNdkDirectory="$OPUM_ANDROID_NDK" - - - name: Verify Android native packaging - shell: bash - run: | - set -euo pipefail - mapfile -t APKS < <(find OpenUtauMobile.Android/bin/Release/net10.0-android36.0/android-arm64 -maxdepth 1 -type f -iname '*-signed.apk') - if [ "${#APKS[@]}" -ne 1 ]; then - echo "::error::Expected exactly one signed APK; found ${#APKS[@]}" - exit 1 - fi - python native/verify-android-runtime.py "${APKS[0]}" android-arm64 + dotnet build OpenUtauMobile.Android/OpenUtauMobile.Android.csproj diff --git a/AGENTS.md b/AGENTS.md index aef7bb2e..4e4c20da 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,6 +11,7 @@ - Place plans documents in `/plans` where git can ignore them. Do not place plans in the source tree or in the `docs` directory. ## Boundaries and style +- Keep singer plugin infrastructure generic. Do not name or describe specific external plugins or add their dedicated behavior in host code, documentation, or UI. Keep README and UI text concise and actionable. - Forbid modifications to `OpenUtau.Core/Ustx`, which could break compatibility with universal USTX files. - Avoid unnecessary changes to upstream-derived `OpenUtau.Core`; keep application orchestration in the Mobile layer. Always ask for permission before modifying upstream-derived code. - `OpenUtau.Core/Util/Preferences.cs#OpenUtau Mobile特定选项` can be modified. @@ -18,8 +19,14 @@ - Follow `.editorconfig`. Write new code comments in Simplified Chinese; preserve upstream comments. - Newly added classes, public methods, hot private methods, and hot properties should use XML comments in Simplified Chinese whenever possible. - When newly added controls involve icons, you must use existing icons in the icon library and are prohibited from drawing icons yourself in forms such as PathGeometry. If necessary, stop and confirm. +- Add comments to critical containers to explain their purpose when adding new controls in `.axaml` files. +- Always use collection expressions instead of such as `ToList()` or `ToArray()` when constructing collections. ## Verification +- Do not introduce defensive validation layers in the build graph or CI. +- Do not add non-temporary verification scripts unless explicitly requested. + Keep temporary investigation scripts outside the source tree and do not hook + them into normal builds or CI. - Before `dotnet build`, set `$env:AVALONIA_TELEMETRY_OPTOUT='1';` (or the equivalent environment variable in another shell). - Do not add new unit tests unless explicitly requested or the task requires them. - Run existing relevant tests when available and appropriate. @@ -29,3 +36,12 @@ - Do not preload repository documentation or historical notes. Read source, docs, and repository-local skills only when relevant to the current task. - Current source is the primary source of truth; docs are references, not startup context. - Load repository-local skills when their scope matches the task. Historical migration notes are not active instructions. + +## Code editing rules + +- Prefer apply_patch for source code modifications. +- Do not use Python str.replace(), PowerShell -replace, or whole-file rewriting for ordinary C# edits. +- If apply_patch fails, report the exact error. Do not silently switch to string-based editing. +- Search with rg and read only relevant code sections. +- If an approach fails twice, reassess the root cause before retrying. +- IDE 报告的 InitializeComponent、命名控件等生成成员的解析错误若持续出现请忽略。 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0f7c4261..a57bf884 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -107,15 +107,15 @@ dotnet run --project OpenUtauMobile.Windows/OpenUtauMobile.Windows.csproj -c Deb 3. 启动前构建目标项目及其依赖;只调试 Windows 时,不要将构建整个解决方案作为启动前任务。 4. 在 C# 代码行旁设置断点,点击虫子图标 **Debug**。需要执行到断点所在操作才会暂停。 -普通 Windows 调试不必设置 `RuntimeIdentifier` 或 `EnableGameGgml`。 -桌面入口和 UI 探针的 Debug/Release 构建默认只复制当前系统架构所需的 NuGet 运行库, +普通 Windows 调试不必设置 `RuntimeIdentifier`。 +桌面入口的 Debug/Release 构建默认只复制当前系统架构所需的 NuGet 运行库, 不会再输出所有平台的 `runtimes`。Windows、Linux、macOS 入口会使用各自平台的 RID; 跨平台或跨架构构建请显式传入 `-r `。共享类库保持平台无关,Android、iOS 和浏览器仍由各自 SDK 选择 RID。 NuGet 原生库附带的 PDB 默认不复制;需要调试这些第三方原生库时,传入 `-p:CopyNuGetNativeSymbols=true`。应用自身的托管调试符号不受影响。 构建会自动生成 `opum_game.dll`,并将对应架构的 worldline 放到输出目录。 -默认 Debug 输出位于 `OpenUtauMobile.Windows/bin/Debug/net10.0-windows/`。 -如果显式使用 `-r win-x64`,输出会多一层 `win-x64/`;启动时应使用此次构建的目录。 +默认 Debug 输出位于 `OpenUtauMobile.Windows/bin/Debug/net10.0-windows//`。 +共同的原生构建参数与增量规则见[原生构建](native/README.md)。 ### 4. 准备 Android 环境 @@ -127,7 +127,7 @@ Windows 已能启动后,再安装以下 Android 专用工具。Android 的 C++ | JDK | 建议安装 [Microsoft OpenJDK 21](https://learn.microsoft.com/java/openjdk/download)。填写 JDK 根目录,不是 `bin`;Android Studio 自带 JBR 只有版本兼容时才可复用。 | | [Android Studio](https://developer.android.com/studio) | 用它的 SDK Manager 安装和管理 SDK,也可用 Device Manager 创建模拟器;C# 代码仍在 Rider 调试。 | | Android SDK | SDK Manager 中安装 Android API 36、Build-Tools 36.0.0、Platform-Tools、Command-line Tools (latest)。具体目标以 [Android 项目](OpenUtauMobile.Android/OpenUtauMobile.Android.csproj) 和安装的 .NET Android 工作负载为准。 | -| Android NDK | 在 SDK Tools 中勾选 Show Package Details,安装 [android-ndk-version.txt](native/game/android-ndk-version.txt) 指定的版本,当前为 r30 LTS `30.0.16248370`。 | +| Android NDK | 在 SDK Tools 中勾选 Show Package Details,安装 [android-ndk-version.txt](native/android-ndk-version.txt) 指定的版本。 | 安装方法也可参考微软的 [.NET Android 依赖说明](https://learn.microsoft.com/dotnet/android/getting-started/installation/dependencies)。 项目当前 CI 使用 JDK 17,本地 JDK 21 已通过构建;不要直接使用未经当前工作负载支持的更高版本。 @@ -136,7 +136,7 @@ Windows 已能启动后,再安装以下 Android 专用工具。Android 的 C++ ```powershell $androidSdk = Join-Path $env:LOCALAPPDATA 'Android/Sdk' -$androidNdkVersion = (Get-Content native/game/android-ndk-version.txt -Raw).Trim() +$androidNdkVersion = (Get-Content native/android-ndk-version.txt -Raw).Trim() $androidNdk = Join-Path $androidSdk "ndk/$androidNdkVersion" $javaSdk = 'C:/替换为你的JDK21目录' $env:JAVA_HOME = $javaSdk @@ -180,7 +180,7 @@ RID 是目标系统与 CPU 架构的标识;Android 应用按目标设备选择 ```powershell $env:AVALONIA_TELEMETRY_OPTOUT='1' $androidRid = 'android-arm64' -dotnet build OpenUtauMobile.Android/OpenUtauMobile.Android.csproj -c Debug -r $androidRid "-p:AndroidSdkDirectory=$androidSdk" "-p:AndroidNdkDirectory=$androidNdk" "-p:JavaSdkDirectory=$javaSdk" +dotnet build OpenUtauMobile.Android/OpenUtauMobile.Android.csproj -r $androidRid ``` 命令会自动恢复对应 RID 的依赖,签名 APK 位于 diff --git a/Directory.Build.props b/Directory.Build.props index 9d78d391..2586b20d 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,6 +1,6 @@ - 12.1.3 + 12.1.6 0.1.576.1-alpha-bc194b6fe489 @@ -30,9 +30,10 @@ preview - - <_OpumPreviousBeforeMicrosoftNETSdkTargets>$(BeforeMicrosoftNETSdkTargets) - $(MSBuildThisFileDirectory)build/DesktopRuntime.props + + + + true diff --git a/OpenUtau.Core/DocManager.cs b/OpenUtau.Core/DocManager.cs index b4d84344..3a8e4fb5 100644 --- a/OpenUtau.Core/DocManager.cs +++ b/OpenUtau.Core/DocManager.cs @@ -120,6 +120,9 @@ public void SearchAllLegacyPlugins() { } } + /// 宿主提供的外部插件文件筛选器;为空时保留默认加载行为。 + public Func? PluginFileFilter { get; set; } + public void SearchAllPlugins() { const string kBuiltin = "OpenUtau.Plugin.Builtin.dll"; var stopWatch = Stopwatch.StartNew(); @@ -141,6 +144,9 @@ public void SearchAllPlugins() { foreach (var file in files) { Assembly assembly; try { + if (PluginFileFilter != null && !PluginFileFilter(file)) { + continue; + } if (!LibraryLoader.IsManagedAssembly(file)) { Log.Debug("Skipping {File}", file); continue; @@ -195,8 +201,59 @@ private void SearchPluginInternal(string path, List result) { ValidateOptions? pendingValidate; UCommandGroup? savedPoint = null; UCommandGroup? autosavedPoint = null; + private object saveSession = new object(); public bool Recovered { get; set; } = false; // Flag to not overwrite backup file + /// 由宿主持有的保存检查点;不暴露或复制撤销队列。 + public sealed class SaveCheckpoint { + internal readonly UProject Project; + internal readonly object Session; + internal readonly UCommandGroup? Point; + + internal SaveCheckpoint(UProject project, object session, UCommandGroup? point) { + Project = project; + Session = session; + Point = point; + } + } + + /// 在 UI 线程捕获已结束编辑事务的保存检查点。 + public SaveCheckpoint CaptureSaveCheckpoint() { + ThreadGuard.AssertUi(); + return HasOpenUndoGroup ? throw new InvalidOperationException("Cannot capture a save checkpoint inside an undo group.") : new SaveCheckpoint(Project, saveSession, undoQueue.LastOrDefault()); + } + + /// 核查工程引用及装载会话,拒绝旧保存任务提交至新文档。 + public bool IsSaveCheckpointCurrent(SaveCheckpoint checkpoint) { + ThreadGuard.AssertUi(); + return ReferenceEquals(Project, checkpoint.Project) && ReferenceEquals(saveSession, checkpoint.Session); + } + + /// 仅按持久化编辑检查点判断是否需要自动保存,不受渲染通知影响。 + public bool NeedsAutoSave(SaveCheckpoint checkpoint) { + ThreadGuard.AssertUi(); + return IsSaveCheckpointCurrent(checkpoint) && !ReferenceEquals(checkpoint.Point, autosavedPoint); + } + + /// 宿主确认写盘及平台同步成功后提交捕获点;此方法不执行文件读写。 + public bool CompleteSave(SaveCheckpoint checkpoint, string path, bool autoSave) { + ThreadGuard.AssertUi(); + if (!IsSaveCheckpointCurrent(checkpoint)) { + return false; + } + if (autoSave) { + autosavedPoint = checkpoint.Point; + } else { + Project.FilePath = path; + Project.Saved = true; + savedPoint = checkpoint.Point; + autosavedPoint = checkpoint.Point; + Recovered = false; + Publish(new SaveProjectNotification(path)); + } + return true; + } + public bool ChangesSaved { get { return (Project.Saved || (Project.tracks.Count <= 1 && Project.parts.Count == 0)) && @@ -302,6 +359,7 @@ ProgressBarNotification or WaveformReadyNotification or Format.Ustx.Save(saveProjectNotif.Path, Project); } } else if (cmd is LoadProjectNotification notification) { + saveSession = new object(); undoQueue.Clear(); redoQueue.Clear(); undoGroup = null; diff --git a/OpenUtau.Core/OpenUtau.Core.csproj b/OpenUtau.Core/OpenUtau.Core.csproj index d0ac2b02..8429990b 100644 --- a/OpenUtau.Core/OpenUtau.Core.csproj +++ b/OpenUtau.Core/OpenUtau.Core.csproj @@ -1,7 +1,7 @@ - net10.0 + net10.0;net10.0-windows none true embedded @@ -41,7 +41,6 @@ Compile assets stay private: its root "Json" namespace would hide OpenUtau.Core.Json in referencing projects. --> - @@ -84,16 +83,16 @@ VogenRes.Designer.cs - - WINDOWS - - - - - - - + + + + + + + + + diff --git a/OpenUtau.Core/Pipeline/PhraseSource.cs b/OpenUtau.Core/Pipeline/PhraseSource.cs index 51d8a2bd..3454cf0a 100644 --- a/OpenUtau.Core/Pipeline/PhraseSource.cs +++ b/OpenUtau.Core/Pipeline/PhraseSource.cs @@ -403,6 +403,8 @@ public sealed class PhraseSource { public readonly PhonemeSource[] Phonemes; /// Half-open [start, end) index ranges into . public readonly (int Start, int End)[] PhraseGroups; + // 可选分组扩展:独占范围供表情图使用,共享上下文仅用于构造渲染输入。 + private readonly RenderPhraseGroup[]? rendererPhraseGroups; // Shared by graph contexts for this immutable snapshot; unused graphs pay no indexing cost. internal readonly Lazy PhraseNoteIndex; @@ -481,6 +483,25 @@ internal PhraseSource( Phonemes.Select(p => p.Position).ToArray(), numerical.ToDictionary(abbr => abbr, abbr => Phonemes.Select(p => p.Values![abbr]).ToArray())); } + + // 保留默认分句路径;只有显式提供分组的渲染器才接管连续音素的切分。 + // 延迟索引尚未求值,此时替换归属范围不会让表情图看到重叠的音符归属。 + rendererPhraseGroups = Renderer.GetPhraseGroups(this); + if (rendererPhraseGroups != null) + { + int previousEnd = 0; + foreach (RenderPhraseGroup group in rendererPhraseGroups) + { + if (group.Start < previousEnd || group.End <= group.Start + || group.ContextStart < 0 || group.ContextStart > group.Start + || group.ContextEnd < group.End || group.ContextEnd > Phonemes.Length) + { + throw new ArgumentException("渲染器返回了无效的乐句归属或上下文范围。"); + } + previousEnd = group.End; + } + PhraseGroups = [.. rendererPhraseGroups.Select(group => (group.Start, group.End))]; + } } /// @@ -546,7 +567,8 @@ public RenderPhrase[] BuildPhrases() { var phonemes = DrivenPhonemes(); var phrases = new RenderPhrase[PhraseGroups.Length]; for (int i = 0; i < PhraseGroups.Length; ++i) { - phrases[i] = new RenderPhrase(this, phonemes, PhraseGroups[i].Start, PhraseGroups[i].End); + phrases[i] = new RenderPhrase(this, phonemes, PhraseGroups[i].Start, PhraseGroups[i].End, + rendererPhraseGroups?[i]); } return phrases; } diff --git a/OpenUtau.Core/Render/IRenderer.cs b/OpenUtau.Core/Render/IRenderer.cs index 5bd36791..639efdad 100644 --- a/OpenUtau.Core/Render/IRenderer.cs +++ b/OpenUtau.Core/Render/IRenderer.cs @@ -91,6 +91,21 @@ public void ReportRealCurves(IReadOnlyList realCurves) { } } + /// 渲染器提供的只读乐句上下文;缓存键必须覆盖会影响音频的额外输入。 + public interface IRenderPhraseContext + { + /// 由渲染器提供的稳定缓存身份,不得包含账户凭据或可变对象标识。 + string CacheKey { get; } + } + + /// + /// 自定义乐句的音素索引范围,均为左闭右开。 + /// Start/End 表示表情图的独占归属,必须有序且不重叠;ContextStart/ContextEnd + /// 表示实际渲染所需的上下文,须包含归属范围,允许相邻乐句共享上下文。 + /// + public sealed record RenderPhraseGroup(int Start, int End, int ContextStart, int ContextEnd, + IRenderPhraseContext? Context = null); + /// /// Interface of phrase-based renderer. /// @@ -102,6 +117,12 @@ public interface IRenderer { bool SupportsExpression(UExpressionDescriptor descriptor); RenderResult Layout(RenderPhrase phrase); + /// + /// 在不可变快照建立后提供自定义分组,可切开连续音素;返回 null 沿用原有分句及合句上限。 + /// 这是可选扩展,默认实现不改变现有渲染器;实现方仅可读取快照,不得修改工程或发起网络请求。 + /// + RenderPhraseGroup[]? GetPhraseGroups(Pipeline.PhraseSource source) => null; + /// /// How much (ms) this renderer pads the rendered audio before the first /// phoneme (head) and after the last phoneme (tail) of a phrase. diff --git a/OpenUtau.Core/Render/RenderPhrase.cs b/OpenUtau.Core/Render/RenderPhrase.cs index 4ce0164a..d8f34eeb 100644 --- a/OpenUtau.Core/Render/RenderPhrase.cs +++ b/OpenUtau.Core/Render/RenderPhrase.cs @@ -217,19 +217,27 @@ public class RenderPhrase { /// public readonly PhraseLayout Layout; + /// 可选分组扩展的只读上下文;宿主不解释具体渲染器的数据。 + public IRenderPhraseContext? RendererContext { get; } + private List cacheFiles = new List(); /// /// The heavy phrase build over an immutable snapshot; pure over the /// snapshot, safe off the UI thread. /// - internal RenderPhrase(Pipeline.PhraseSource source, Pipeline.PhonemeSource[] phonemes, int phraseStart, int phraseEnd) { + internal RenderPhrase(Pipeline.PhraseSource source, Pipeline.PhonemeSource[] phonemes, int phraseStart, int phraseEnd, + RenderPhraseGroup? group = null) { + // 表情图仍以 phraseStart 定位独占归属,音素及音高输入可以包含相邻乐句共享的上下文。 + RendererContext = group?.Context; + int contextStart = group?.ContextStart ?? phraseStart; + int contextEnd = group?.ContextEnd ?? phraseEnd; var phrasePhonemes = phonemes - .Skip(phraseStart) - .Take(phraseEnd - phraseStart) + .Skip(contextStart) + .Take(contextEnd - contextStart) .ToList(); var notesOf = source.Notes; - var uNotes = source.PhraseNotes(phraseStart, phraseEnd); + var uNotes = source.PhraseNotes(contextStart, contextEnd); if (notesOf[uNotes.First()].Prev != -1 && notesOf[notesOf[uNotes.First()].Prev].End == notesOf[uNotes.First()].Position) { uNotes.Insert(0, notesOf[uNotes.First()].Prev); @@ -581,6 +589,11 @@ private ulong Hash(bool postEffect) { writer.Write(renderer?.ToString() ?? ""); writer.Write(wavtool ?? ""); writer.Write(timeAxis.Timestamp); + // 自定义分组的淡化、补白等额外输入也必须参与缓存;默认路径保持原哈希格式。 + if (RendererContext != null) + { + writer.Write(RendererContext.CacheKey); + } // R1.1 用乐句哈希作为噪声种子,输入须与桌面一致。 if (renderer?.ToString() != Renderers.WORLDLINE_R11) { diff --git a/OpenUtau.Core/Util/Preferences.cs b/OpenUtau.Core/Util/Preferences.cs index 3460b38b..98fbc334 100644 --- a/OpenUtau.Core/Util/Preferences.cs +++ b/OpenUtau.Core/Util/Preferences.cs @@ -14,12 +14,19 @@ namespace OpenUtau.Core.Util { public static class Preferences { public static SerializablePreferences Default { get; private set; } + /// 可选宿主保存入口;由宿主捕获独立数据、合并请求并安排后台持久化。 + public static Action? SaveOverride { get; set; } + static Preferences() { Load(); } public static void Save() { try { + if (SaveOverride != null) { + SaveOverride(); + return; + } File.WriteAllText(PathManager.Inst.PrefsFilePath, Json.Serialize(Default, Json.WriteIndentedOptions), Encoding.UTF8); @@ -362,13 +369,19 @@ public class SerializablePreferences { /// 待下次启动删除的插件文件,保存相对于插件目录的路径。 public List PendingPluginDeletions = []; + /// 启用插件的相对文件路径;仅加载名单内的外部插件。 + public List EnabledPlugins = []; + + /// 待下次启动清除数据的插件稳定 ID。 + public List PendingPluginDataClears = []; + /// 各平台的界面图形后端回退顺序;空列表使用 Avalonia 默认配置,重启后生效。 public Dictionary> GraphicsBackendFallbackOrders = new(); public double PlaybackRefreshRate = 20.0; /// 回放时钢琴卷帘纵向滚动:0 = 关闭,1 = 边界滚动,2 = 保持居中。 - public int PlaybackVerticalScroll = 0; + public int PlaybackVerticalScroll = 2; /// /// Android 全屏模式:0 = 始终,1 = 仅编辑页,2 = 关闭。 @@ -380,8 +393,8 @@ public class SerializablePreferences { /// public bool AndroidKeepScreenAwakeWhileEditing = true; -/// - /// Piano key behavior: 0=Silent, 1=SineWave, 2=SoundFont + /// + /// 钢琴键行为:0=静音,1=正弦波,2=SoundFont采样 /// public int PianoKeyBehavior = 1; @@ -395,6 +408,9 @@ public class SerializablePreferences { /// public bool ShowRenderWaveform = false; + /// 是否在钢琴卷帘背景显示其它轨道中与当前片段重叠的音符。 + public bool PianoRollShowGhostNotes = true; + /// /// Path to SoundFont (SF2) file for piano key playback. /// If empty or file not found, falls back to SineWave. @@ -402,14 +418,14 @@ public class SerializablePreferences { public string SoundFontPath = string.Empty; /// - /// Preferred audio backend. Empty string means auto-select based on platform. + /// 偏好的音频后端。空字符串表示根据平台自动选择。 /// Supported values: - /// - "" or "Auto": Auto-select (default) + /// - "" or "Auto": 自动 (default) /// - "MiniAudio": Use MiniAudio (Windows/Linux/macOS/Android) /// - "NAudio": Use NAudio (Windows only) /// - "AudioTrack": Use Android AudioTrack (Android only) /// - "Dummy": Use dummy audio output (all platforms, no sound) - /// Platform-specific availability: + /// 特定平台的可用性: /// - Windows: MiniAudio, NAudio, Dummy /// - Linux/macOS: MiniAudio, Dummy /// - Android: MiniAudio, AudioTrack, Dummy diff --git a/OpenUtau.Core/Vogen/VogenSingerLoader.cs b/OpenUtau.Core/Vogen/VogenSingerLoader.cs index 3ee136b0..c5a0ef36 100644 --- a/OpenUtau.Core/Vogen/VogenSingerLoader.cs +++ b/OpenUtau.Core/Vogen/VogenSingerLoader.cs @@ -24,7 +24,7 @@ class VogenMeta { public string misc; } - class VogenSingerLoader { + public class VogenSingerLoader { readonly string basePath; public static IEnumerable FindAllSingers() { diff --git a/OpenUtau.Plugin.Builtin/OpenUtau.Plugin.Builtin.csproj b/OpenUtau.Plugin.Builtin/OpenUtau.Plugin.Builtin.csproj index 8dd4d9ca..2596110b 100644 --- a/OpenUtau.Plugin.Builtin/OpenUtau.Plugin.Builtin.csproj +++ b/OpenUtau.Plugin.Builtin/OpenUtau.Plugin.Builtin.csproj @@ -1,7 +1,7 @@  - net10.0 + net10.0;net10.0-windows none embedded enable @@ -9,10 +9,6 @@ CS0168;CS0162;CS0219;CS0649;CS0414;CS8600;CS8601;CS8602;CS8603;CS8604;CS8612;CS8618;CS8619;CS8625;CS8629;CS8714;CS8767;CS8769;CS0108 - - - - diff --git a/OpenUtauMobile.Android/MainActivity.cs b/OpenUtauMobile.Android/MainActivity.cs index 1b592407..32a9a2a9 100644 --- a/OpenUtauMobile.Android/MainActivity.cs +++ b/OpenUtauMobile.Android/MainActivity.cs @@ -23,7 +23,6 @@ using OpenUtauMobile.Android.Services.Platform; using OpenUtauMobile.Android.Services.Performance; using OpenUtauMobile.Android.Services.Storage; -using Serilog; using Environment = System.Environment; using Log = Serilog.Log; using Path = System.IO.Path; @@ -84,6 +83,7 @@ internal static AppBuilder ConfigureAppBuilder(AppBuilder builder) ServiceHub.PlatformCrashLogService = crashLogService; _ = crashLogService.CollectPreviousExitAsync(); ServiceHub.InitAudioOutput = InitAudioOutput; // 设置初始化音频输出的委托 + ServiceHub.PlatformExitApplication = () => CurrentActivity?.FinishAffinity(); ServiceHub.ExternalUrlLauncher = new AndroidExternalUrlLauncher(() => CurrentActivity); ServiceHub.ExternalStorageService = new AndroidExternalStorageService(() => CurrentActivity); // 设置外部存储服务 @@ -124,6 +124,24 @@ protected override void OnDestroy() base.OnDestroy(); } + + /// 离开前请求刷新合并的偏好,避免以同步磁盘等待阻塞 Android 生命周期。 + protected override void OnPause() + { + base.OnPause(); + _ = FlushPreferencesAsync(); + } + + /// 异步刷新结束后记录异常,不在生命周期回调中等待磁盘。 + private static async Task FlushPreferencesAsync() + { + try + { + await Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(async () => + await OpenUtauMobile.Services.Projects.PreferencesWriter.Inst.FlushAsync()); + } + catch (Exception error) { Log.Error(error, "暂停时刷新偏好失败"); } + } /// /// 自动恢复沉浸模式 /// @@ -248,7 +266,7 @@ internal static void InitPathManager() /// private static void InitLogging() { - OpenUtauMobile.Services.AppLogging.Initialize(PathManager.Inst.LogFilePath); + AppLogging.Initialize(PathManager.Inst.LogFilePath); Log.Information("==========开始记录日志=========="); } diff --git a/OpenUtauMobile.Android/OpenUtauMobile.Android.csproj b/OpenUtauMobile.Android/OpenUtauMobile.Android.csproj index 2a3938f9..2178899a 100644 --- a/OpenUtauMobile.Android/OpenUtauMobile.Android.csproj +++ b/OpenUtauMobile.Android/OpenUtauMobile.Android.csproj @@ -4,28 +4,27 @@ net10.0-android36.0 24 enable - $(BaseApplicationId) OpenUtau Mobile 预览版 apk + + true false 2G true + true + + false - + $(BaseApplicationId).debug - True - - True + + true - - True + True - - - @@ -52,11 +51,15 @@ Bind="false"/> - - - - - - - + + + + + + + + + diff --git a/OpenUtauMobile.Android/Properties/AndroidManifest.xml b/OpenUtauMobile.Android/Properties/AndroidManifest.xml index 6dafecd0..1ded9638 100644 --- a/OpenUtauMobile.Android/Properties/AndroidManifest.xml +++ b/OpenUtauMobile.Android/Properties/AndroidManifest.xml @@ -10,6 +10,7 @@ diff --git a/OpenUtauMobile.Android/Resources/xml/network_security_config.xml b/OpenUtauMobile.Android/Resources/xml/network_security_config.xml new file mode 100644 index 00000000..7036ef61 --- /dev/null +++ b/OpenUtauMobile.Android/Resources/xml/network_security_config.xml @@ -0,0 +1,7 @@ + + + + localhost + 127.0.0.1 + + diff --git a/OpenUtauMobile.Browser/OpenUtauMobile.Browser.csproj b/OpenUtauMobile.Browser/OpenUtauMobile.Browser.csproj index c3e01ac1..43a0cf3c 100644 --- a/OpenUtauMobile.Browser/OpenUtauMobile.Browser.csproj +++ b/OpenUtauMobile.Browser/OpenUtauMobile.Browser.csproj @@ -4,7 +4,6 @@ Exe true enable - browser-wasm BROWSER true $(EmccExtraLDFlags) -lidbfs.js @@ -34,5 +33,5 @@ - + diff --git a/OpenUtauMobile.Browser/Program.cs b/OpenUtauMobile.Browser/Program.cs index a08598a9..8d305a96 100644 --- a/OpenUtauMobile.Browser/Program.cs +++ b/OpenUtauMobile.Browser/Program.cs @@ -17,6 +17,7 @@ using OpenUtauMobile.Browser.Services.Graphics; using OpenUtauMobile.Browser.Services.Platform; using OpenUtauMobile.Browser.Services; +using OpenUtauMobile.Browser.Services.Audio; using Serilog; internal sealed partial class Program @@ -31,6 +32,12 @@ private static async Task Main(string[] args) reactiveUIBuilder.WithExceptionHandler(Observer.Create(HandleReactiveException)); }); await BrowserExternalUrlLauncher.InitializeAsync(); + await BrowserAudioInterop.InitializeAsync(); + if (BrowserAudioInterop.CanSelectDevice) + { + ServiceHub.AudioDevicePickerFactory = onRouteChanged => new BrowserAudioDevicePicker(onRouteChanged); + ServiceHub.GetSystemAudioOutputDevices = BrowserAudioInterop.GetCurrentDevices; + } BrowserGraphicsBackendPreferenceStore graphicsStore = await BrowserGraphicsBackendPreferenceStore.CreateAsync(); BrowserGraphicsBackendProvider graphicsProvider = new(); GraphicsBackendService graphicsService = new(graphicsProvider, graphicsStore); @@ -133,7 +140,7 @@ private static void InitAudioOutput() Log.Warning("Preferred backend {Backend} failed to initialize; falling back.", pref); } - string[] fallbackOrder = ["Dummy"]; + string[] fallbackOrder = ["WebAudio", "Dummy"]; foreach (string backend in fallbackOrder) { @@ -152,6 +159,10 @@ private static bool TryInitAudioBackend(string backend) { switch (backend) { + case "WebAudio": + PlaybackManager.Inst.AudioOutput = new BrowserAudioOutput(); + Log.Information("Using Web Audio output."); + return true; case "Dummy": PlaybackManager.Inst.AudioOutput = new DummyAudioOutput(); Log.Information("Using Dummy audio backend (silent)."); diff --git a/OpenUtauMobile.Browser/README.md b/OpenUtauMobile.Browser/README.md index 1d74e93c..66286731 100644 --- a/OpenUtauMobile.Browser/README.md +++ b/OpenUtauMobile.Browser/README.md @@ -14,7 +14,7 @@ dotnet run --project OpenUtauMobile.Browser/OpenUtauMobile.Browser.csproj -c Deb - Worldline 在 Build / Publish 中通过 Bazel 源码构建为静态 WASM 归档,随后由 .NET 链入运行时。 除 `wasm-tools` 外需要 Python 3.10+、Git 和 Bazelisk;Emscripten 使用工作负载配套版本。 - 详见 [Worldline 构建说明](../native/worldline/README.md)。这不包含 ONNX 后端或浏览器音频播放接入。 + 详见 [Worldline 构建说明](../native/worldline/README.md)。这不包含 ONNX 后端。 - 启用 `WasmEnableThreads`,保留音素化与短语构建后台线程。SDK 开发服务器会自动附加跨源隔离响应头。 - 浏览器控制台默认记录 Information 及以上级别,不全局监听 FirstChanceException。已捕获异常和正常任务取消不应逐次创建后台日志任务;拖动命令的 Debug 日志也不应逐条跨线程输出到控制台。 - Debug 的原生编译使用 `-Oz`,原生链接使用 `-O2`。本机 .NET 10.0.12 的 `-O0` 多线程原生构建在运行时初始化时断言失败;这些设置保留 C# 的 Debug 配置和调试符号。相关上游记录:。 @@ -58,6 +58,8 @@ IDBFS 会把已保存的文件加载到内存,适合先接通现有同步文 当前 .NET 10 多线程 WASM 仍存在致命定时器锁异常风险:`System.Threading.Lock.Exit` → `TimerQueueTimer.Fire/Dispose` → `Task.Delay`,随后可能出现 GC 等待线程暂停失败并使页面失去响应。该堆栈已在 Chromium 内核浏览器中通过并发定时器、可取消延时复现;移除 FirstChanceException 日志任务、关闭 JITerpreter 均不能消除它。相关上游问题仍未关闭:[dotnet/runtime#129900](https://github.com/dotnet/runtime/issues/129900)。这些日志优化不代表多线程稳定性问题已经修复。当前后端会直接创建音素化和短语构建线程,单独关闭 `WasmEnableThreads` 会破坏初始化,不能作为现有架构的直接替代方案。 -启动、托管外部音素器扫描与后台音素化可以运行,但这不代表所有桌面插件和音频引擎都适用于浏览器。当前音频输出仍是既有的 Dummy 后端。ONNX 原生库在浏览器中不可用,重新读取偏好时的 ONNX 设备校验会记录异常;这不影响已验证的普通托管音素器。 +音频默认使用 Web Audio:后台读取采样源,AudioWorklet 消费有界缓冲。首次播放需要点击或按键授权;系统挂起后可再次操作恢复。设置中可选择 Web Audio 或 Dummy,后端切换重启后生效。支持设备授权及 `AudioContext.setSinkId` 的浏览器提供输出设备选择,否则使用系统默认设备。设备授权不请求麦克风权限。 + +启动、托管外部音素器扫描与后台音素化可以运行,但这不代表所有桌面插件和渲染器都适用于浏览器。ONNX 原生库在浏览器中不可用,重新读取偏好时的 ONNX 设备校验会记录异常;这不影响已验证的普通托管音素器。 持久化已验证工程保存后的页面刷新与浏览器关闭后重新打开,以及中文路径、覆盖、重命名、删除和写入失败后的重试。实际歌手导入与安装流程尚未验证。 diff --git a/OpenUtauMobile.Browser/Services/Audio/BrowserAudioBuffer.cs b/OpenUtauMobile.Browser/Services/Audio/BrowserAudioBuffer.cs new file mode 100644 index 00000000..aa9bce4f --- /dev/null +++ b/OpenUtauMobile.Browser/Services/Audio/BrowserAudioBuffer.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Concurrent; +using System.Runtime.InteropServices; +using System.Threading; + +namespace OpenUtauMobile.Browser.Services.Audio; + +/// 固定在 WASM 共享内存中的单生产者、单消费者音频队列。 +internal sealed class BrowserAudioBuffer +{ + // 与 audio-output-buffer.js 共用布局;计数均为立体声帧,允许无符号回绕。 + private const int Read = 0, Write = 1, Playing = 2, Ended = 3, Consumed = 4, Running = 5; + private const int HeaderLength = 8; + internal const int Capacity = 4096; + internal const int TargetFrames = 2048; + private static readonly ConcurrentDictionary retained = new(); + private readonly int[] storage = new int[HeaderLength + Capacity * 2]; + private readonly GCHandle pin; + private uint lastConsumed; + private long consumedFrames; + + /// 固定队列地址,内存增长和托管回收均不会移动音频数据。 + internal BrowserAudioBuffer() => pin = GCHandle.Alloc(storage, GCHandleType.Pinned); + + /// 浏览器放弃引用且后台生产结束之后,才允许解除固定。 + ~BrowserAudioBuffer() + { + if (pin.IsAllocated) pin.Free(); + } + + /// 发布给浏览器的队列必须保活,直到音频线程确认已切换。 + internal int Retain(int generation) + { + retained[generation] = this; + return pin.AddrOfPinnedObject().ToInt32(); + } + + /// 音频线程确认旧队列不再使用后,移除浏览器持有的引用。 + internal static void Release(int generation) => retained.TryRemove(generation, out _); + + /// 直接发布播放意图,不依赖主线程及时处理控制消息。 + internal bool IsPlaying + { + get => Volatile.Read(ref storage[Playing]) != 0; + set => Volatile.Write(ref storage[Playing], value ? 1 : 0); + } + + /// 浏览器主线程只在上下文状态变化时更新运行标记。 + internal bool IsRunning => Volatile.Read(ref storage[Running]) != 0; + + /// 设备尚未消费的帧数;写指针只能在样本复制完成后发布。 + internal int QueuedFrames => unchecked((int)((uint)Volatile.Read(ref storage[Write]) - + (uint)Volatile.Read(ref storage[Read]))); + + /// 读取消费时钟并展开回绕;调用者须串行访问。 + internal long ConsumedFrames + { + get + { + uint current = unchecked((uint)Volatile.Read(ref storage[Consumed])); + consumedFrames += unchecked(current - lastConsumed); + lastConsumed = current; + return consumedFrames; + } + } + + /// 生产结束只发布标记,音频线程自行排空剩余样本。 + internal void EndInput() => Volatile.Write(ref storage[Ended], 1); + + /// 向已预留的空位写入交错样本,跨越环尾时分两段复制。 + internal void WriteSamples(ReadOnlySpan samples) + { + uint write = unchecked((uint)Volatile.Read(ref storage[Write])); + int offset = (int)(write % Capacity) * 2; + Span destination = MemoryMarshal.Cast(storage.AsSpan(HeaderLength)); + int first = Math.Min(samples.Length, destination.Length - offset); + samples[..first].CopyTo(destination[offset..]); + samples[first..].CopyTo(destination); + Volatile.Write(ref storage[Write], unchecked((int)(write + (uint)(samples.Length / 2)))); + } +} diff --git a/OpenUtauMobile.Browser/Services/Audio/BrowserAudioDevicePicker.cs b/OpenUtauMobile.Browser/Services/Audio/BrowserAudioDevicePicker.cs new file mode 100644 index 00000000..1a6ea136 --- /dev/null +++ b/OpenUtauMobile.Browser/Services/Audio/BrowserAudioDevicePicker.cs @@ -0,0 +1,32 @@ +using System; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Interactivity; + +namespace OpenUtauMobile.Browser.Services.Audio; + +/// 通过用户点击请求浏览器设备授权,并展示切换成功后的实际路由。 +internal sealed class BrowserAudioDevicePicker : Button +{ + /// 复用设置页按钮样式,在控件存活期间监听系统设备变化。 + public BrowserAudioDevicePicker(Action onRouteChanged) + { + this.Bind(ContentProperty, this.GetResourceObservable("Settings.Render.OutputDevice")); + Classes.Add("filled"); + Click += SelectOutput; + Loaded += (_, _) => BrowserAudioInterop.DevicesChanged += onRouteChanged; + Unloaded += (_, _) => BrowserAudioInterop.DevicesChanged -= onRouteChanged; + } + + /// 直接从点击事件调用浏览器,保留系统选择器要求的用户激活。 + private async void SelectOutput(object? sender, RoutedEventArgs args) + { + try + { + IsEnabled = false; + await BrowserAudioInterop.SelectOutputAsync(); + } + catch (Exception exception) { BrowserAudioInterop.ReportError(0, exception.Message); } + finally { IsEnabled = true; } + } +} diff --git a/OpenUtauMobile.Browser/Services/Audio/BrowserAudioInterop.cs b/OpenUtauMobile.Browser/Services/Audio/BrowserAudioInterop.cs new file mode 100644 index 00000000..d2f27b9f --- /dev/null +++ b/OpenUtauMobile.Browser/Services/Audio/BrowserAudioInterop.cs @@ -0,0 +1,113 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices.JavaScript; +using System.Threading.Tasks; +using Avalonia.Threading; +using OpenUtau.Audio; +using OpenUtau.Core; +using OpenUtauMobile.Tools; +using Serilog; + +namespace OpenUtauMobile.Browser.Services.Audio; + +/// 在浏览器主线程连接 Web Audio,并为后台音频对象提供能力快照。 +internal static partial class BrowserAudioInterop +{ + private const string ModuleName = "OpenUtauMobileAudio"; + private static readonly object deviceLock = new(); + private static List currentDevices = []; + + /// 初始化成功后提供给浏览器宿主的输出采样率。 + internal static int SampleRate { get; private set; } + /// 是否可以通过浏览器的系统设备选择器切换输出。 + internal static bool CanSelectDevice { get; private set; } + internal static event Action? DevicesChanged; + + /// 预先加载音频线程,在用户首次操作之前准备好暂停的上下文。 + internal static async Task InitializeAsync() + { + try + { + await JSHost.ImportAsync(ModuleName, "/audio-output.js"); + SampleRate = await Initialize(JSHost.DotnetInstance); + CanSelectDevice = CanSelectOutput(); + } + catch (Exception exception) + { + SampleRate = 0; + Log.Error(exception, "浏览器音频初始化失败,将使用静音后端"); + } + } + + /// 返回当前已选路由的快照,不从后台线程调用浏览器 API。 + internal static List GetCurrentDevices() + { + lock (deviceLock) + { + return [.. currentDevices]; + } + } + + /// 浏览器已不再读取旧队列,允许回收其固定内存。 + [JSExport] + public static Task ReleaseBuffer(int generation) + { + BrowserAudioBuffer.Release(generation); + return Task.CompletedTask; + } + + /// 将消费时钟与上下文状态同步到托管快照。 + [JSExport] + public static async Task UpdateStatus(int generation, int state, double latency) + { + await Dispatcher.UIThread.InvokeAsync(() => BrowserAudioOutput.Active?.UpdateStatus(generation, state, latency)); + } + + /// 异步接收浏览器错误,避免从 JS 主线程同步进入托管运行时。 + [JSExport] + public static async Task ReceiveError(int generation, string message) + { + await Dispatcher.UIThread.InvokeAsync(() => ReportError(generation, message)); + } + + /// 将浏览器错误送入现有通知系统,保留用户重新授权的机会。 + internal static void ReportError(int generation, string message) + { + Log.Error("浏览器音频错误: {Message}", message); + DocManager.Inst.ExecuteCmd(new ErrorMessageNotification(new InvalidOperationException(message))); + } + + /// 设备切换成功后更新实际路由,设置页仅展示这个结果。 + [JSExport] + public static async Task UpdateDevice(string id, string name) + { + await Dispatcher.UIThread.InvokeAsync(() => + { + lock (deviceLock) + { + currentDevices = string.IsNullOrEmpty(id) || string.IsNullOrEmpty(name) + ? [] + : [new AudioOutputDevice + { + api = "WebAudio", + name = name, + deviceNumber = 0, + guid = GuidTools.CreateGuidFromStrings("WebAudio", id), + }]; + } + DevicesChanged?.Invoke(); + }); + } + + [JSImport("initialize", ModuleName)] + private static partial Task Initialize(JSObject runtime); + + [JSImport("canSelectOutput", ModuleName)] + private static partial bool CanSelectOutput(); + + [JSImport("setPlayback", ModuleName)] + internal static partial void SetPlayback(int generation, int state, int address); + + [JSImport("selectOutput", ModuleName)] + internal static partial Task SelectOutputAsync(); +} diff --git a/OpenUtauMobile.Browser/Services/Audio/BrowserAudioOutput.cs b/OpenUtauMobile.Browser/Services/Audio/BrowserAudioOutput.cs new file mode 100644 index 00000000..2de48ce2 --- /dev/null +++ b/OpenUtauMobile.Browser/Services/Audio/BrowserAudioOutput.cs @@ -0,0 +1,293 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using Avalonia.Threading; +using NAudio.Wave; +using NAudio.Wave.SampleProviders; +using OpenUtau.Audio; +using OpenUtauMobile.Services.Performance; +using Serilog; + +namespace OpenUtauMobile.Browser.Services.Audio; + +/// 后台直接向 WASM 共享队列生产采样,浏览器音频线程独立消费。 +internal sealed class BrowserAudioOutput : IAudioOutput, IAudioLatencySource, IDisposable +{ + private const int Channels = 2; + private const int BlockSamples = 1024 * Channels; + private static BrowserAudioOutput? active; + private static int nextGeneration; + private readonly object syncRoot = new(); + private BrowserAudioBuffer buffer = new(); + private ISampleProvider? sampleProvider; + private int generation = Interlocked.Increment(ref nextGeneration); + private int requestedState; + private double transportLatency; + private bool inputEnded; + private bool synchronizationPosted; + private bool disposed; + + /// 原生音频线程不会进入托管运行时,由这个后台线程读取采样源。 + public BrowserAudioOutput() + { + if (BrowserAudioInterop.SampleRate == 0) + { + throw new InvalidOperationException("Web Audio is unavailable."); + } + if (Interlocked.CompareExchange(ref active, this, null) != null) + { + throw new InvalidOperationException("A browser audio output is already active."); + } + Thread producer = new(ProduceSamples) { IsBackground = true, Name = "Browser audio producer" }; + try + { + producer.Start(); + } + catch + { + Interlocked.CompareExchange(ref active, null, this); + throw; + } + } + + /// 主线程回调访问的唯一输出实例。 + internal static BrowserAudioOutput? Active => Volatile.Read(ref active); + + /// 读取已同步的传输状态;等待用户激活时保持可继续的暂停状态。 + public PlaybackState PlaybackState + { + get + { + lock (syncRoot) + { + if (requestedState == 0 || (inputEnded && buffer.QueuedFrames == 0)) return PlaybackState.Stopped; + return requestedState == 1 && buffer.IsRunning && buffer.IsPlaying + ? PlaybackState.Playing : PlaybackState.Paused; + } + } + } + + /// 路由由浏览器选择器管理,不持久化枚举序号。 + public int DeviceNumber => 0; + + /// 直接读取共享队列水位,并加上浏览器报告的设备延迟。 + public double? OutputLatencyMilliseconds + { + get + { + lock (syncRoot) + { + return transportLatency + buffer.QueuedFrames * 1000.0 / BrowserAudioInterop.SampleRate; + } + } + } + + /// 设备列表仅反映已授权且实际选中的系统路由。 + public List GetOutputDevices() => BrowserAudioInterop.GetCurrentDevices(); + + /// 设备授权与切换必须通过设置页的用户操作完成。 + public void SelectDevice(Guid guid, int deviceNumber) + { + if (guid != Guid.Empty && !GetOutputDevices().Exists(device => device.guid == guid)) + { + throw new NotSupportedException("Select an audio output using the browser device picker."); + } + } + + /// 准备匹配上下文采样率的立体声源,并丢弃上一代缓冲。 + public void Init(ISampleProvider provider) + { + ISampleProvider prepared = provider; + if (provider.WaveFormat.SampleRate != BrowserAudioInterop.SampleRate) + { + prepared = new WdlResamplingSampleProvider(provider, BrowserAudioInterop.SampleRate); + } + prepared = prepared.ToStereo(); + lock (syncRoot) + { + ObjectDisposedException.ThrowIf(disposed, this); + ResetLocked(); + sampleProvider = prepared; + ScheduleSynchronizationLocked(); + } + } + + /// 请求播放,等待上下文解锁及首批数据后再报告实际播放状态。 + public void Play() + { + lock (syncRoot) + { + ObjectDisposedException.ThrowIf(disposed, this); + if (sampleProvider == null) return; + requestedState = 1; + buffer.IsPlaying = true; + ScheduleSynchronizationLocked(); + Monitor.PulseAll(syncRoot); + } + } + + /// 保留两侧缓冲和输入位置,暂停时不再读取采样源。 + public void Pause() + { + lock (syncRoot) + { + if (requestedState == 0 || disposed) return; + requestedState = 2; + buffer.IsPlaying = false; + ScheduleSynchronizationLocked(); + } + } + + /// 切换播放代次,使旧的回调和未播放样本全部失效。 + public void Stop() + { + lock (syncRoot) + { + if (disposed) return; + ResetLocked(); + ScheduleSynchronizationLocked(); + } + } + + /// 按播放管理器约定返回 44100 Hz 工程帧数乘四的字节位置。 + public long GetPosition() + { + lock (syncRoot) + { + return (long)(buffer.ConsumedFrames * 44100.0 / BrowserAudioInterop.SampleRate) * sizeof(float); + } + } + + /// 唤醒并结束生产线程,释放缓冲;不在浏览器主线程等待线程退出。 + public void Dispose() + { + lock (syncRoot) + { + if (disposed) return; + ResetLocked(); + sampleProvider = null; + ScheduleSynchronizationLocked(); + disposed = true; + Monitor.PulseAll(syncRoot); + } + } + + /// 停止旧队列并切换独立内存,避免重置正在消费的读写指针。 + private void ResetLocked() + { + buffer.IsPlaying = false; + buffer = new BrowserAudioBuffer(); + generation = Interlocked.Increment(ref nextGeneration); + requestedState = 0; + inputEnded = false; + transportLatency = 0; + } + + /// 合并控制请求,主线程始终应用最新的播放意图。 + private void ScheduleSynchronizationLocked() + { + if (synchronizationPosted) return; + synchronizationPosted = true; + Dispatcher.UIThread.Post(SynchronizeTransport); + } + + /// 不持有状态锁调用 JS,防止浏览器回调与后台生产相互等待。 + private void SynchronizeTransport() + { + int version, state, address; + lock (syncRoot) + { + synchronizationPosted = false; + version = generation; + state = requestedState; + address = disposed ? 0 : buffer.Retain(version); + } + try + { + BrowserAudioInterop.SetPlayback(version, state, address); + } + catch (Exception exception) { Fail(version, exception, synchronize: false); } + if (disposed) Interlocked.CompareExchange(ref active, null, this); + } + + /// 后台直接发布样本;满队列时短暂休眠,唤醒不依赖浏览器主线程。 + private void ProduceSamples() + { + float[] samples = new float[BlockSamples]; + while (true) + { + int version; + ISampleProvider provider; + BrowserAudioBuffer target; + lock (syncRoot) + { + while (!disposed && (requestedState != 1 || inputEnded)) + Monitor.Wait(syncRoot); + if (disposed) return; + if (buffer.QueuedFrames > BrowserAudioBuffer.TargetFrames - BlockSamples / Channels) + { + // Worklet 不进入托管运行时;有界休眠独立检查它发布的读指针。 + Monitor.Wait(syncRoot, 5); + continue; + } + version = generation; + provider = sampleProvider!; + target = buffer; + } + try + { + int count = provider.Read(samples, 0, BlockSamples); + lock (syncRoot) + { + if (!disposed && version == generation) + { + if (count > 0) + { + target.WriteSamples(samples.AsSpan(0, count)); + } + else + { + inputEnded = true; + target.EndInput(); + } + } + } + } + catch (Exception exception) { Fail(version, exception); } + } + } + + /// 只接受本代设备状态;采样水位和消费时钟直接读取共享内存。 + internal void UpdateStatus(int version, int state, double latency) + { + lock (syncRoot) + { + if (version != generation || disposed) return; + if (state == 3) + { + ResetLocked(); + sampleProvider = null; + return; + } + transportLatency = latency; + if (state == 0 && inputEnded && buffer.QueuedFrames == 0) + { + requestedState = 0; + } + } + } + + /// 采样或传输失败后停止本代播放,并回到主线程报告异常。 + private void Fail(int version, Exception exception, bool synchronize = true) + { + lock (syncRoot) + { + if (version != generation || disposed) return; + ResetLocked(); + sampleProvider = null; + if (synchronize) ScheduleSynchronizationLocked(); + } + Log.Error(exception, "浏览器音频输出失败"); + Dispatcher.UIThread.Post(() => BrowserAudioInterop.ReportError(version, exception.Message)); + } +} diff --git a/OpenUtauMobile.Browser/wwwroot/audio-output-buffer.js b/OpenUtauMobile.Browser/wwwroot/audio-output-buffer.js new file mode 100644 index 00000000..799ca6e6 --- /dev/null +++ b/OpenUtauMobile.Browser/wwwroot/audio-output-buffer.js @@ -0,0 +1,5 @@ +// 与 BrowserAudioBuffer.cs 共用布局;队列位于固定的 WASM 内存,计数单位为立体声帧。 +export const Read = 0, Write = 1, Playing = 2, Ended = 3, Consumed = 4, Running = 5; +export const headerLength = 8; +export const capacity = 4096; +export const targetFrames = 2048; diff --git a/OpenUtauMobile.Browser/wwwroot/audio-output-worklet.js b/OpenUtauMobile.Browser/wwwroot/audio-output-worklet.js new file mode 100644 index 00000000..a90d4e35 --- /dev/null +++ b/OpenUtauMobile.Browser/wwwroot/audio-output-worklet.js @@ -0,0 +1,55 @@ +// 后台生产者与音频线程直接共用 WASM 帧队列;主线程不参与持续供音。 +import { Read, Write, Playing, Ended, Consumed, headerLength, capacity } from './audio-output-buffer.js'; + +class OpenUtauAudioProcessor extends AudioWorkletProcessor { + constructor() { + super(); + this.generation = 0; + this.header = null; + this.framesSinceReport = 0; + this.port.onmessage = ({ data }) => { + if (data.type === "configure") { + const previousGeneration = this.generation; + const hadBuffer = this.header !== null; + this.generation = data.generation; + this.header = data.buffer ? new Int32Array(data.buffer, data.address, headerLength) : null; + this.samples = data.buffer ? new Float32Array(data.buffer, data.address + headerLength * 4, capacity * 2) : null; + this.framesSinceReport = 0; + // 消息和 process 在同一音频线程串行执行,确认之后不再访问旧地址。 + if (hadBuffer) this.port.postMessage({ type: "released", generation: previousGeneration }); + } + }; + } + + process(inputs, outputs) { + const output = outputs[0]; + if (!output?.length || !this.header || !Atomics.load(this.header, Playing)) return true; + const header = this.header; + const read = Atomics.load(header, Read) >>> 0; + const write = Atomics.load(header, Write) >>> 0; + const available = (write - read) >>> 0; + const count = Math.min(output[0].length, available); + for (let frame = 0; frame < count; frame++) { + const offset = ((read + frame) % capacity) * 2; + output[0][frame] = this.samples[offset]; + if (output[1]) output[1][frame] = this.samples[offset + 1]; + } + // 欠载补零不推进输入时钟;采样源返回的静音仍作为正常输入消费。 + Atomics.store(header, Read, (read + count) | 0); + Atomics.add(header, Consumed, count); + const remaining = available - count; + this.framesSinceReport += output[0].length; + // 结束标记可能在本次写指针快照之后发布,须再次确认末块已经消费完。 + if (remaining === 0 && Atomics.load(header, Ended) + && (Atomics.load(header, Write) >>> 0) === ((read + count) >>> 0)) { + Atomics.store(header, Playing, 0); + this.port.postMessage({ type: "ended", generation: this.generation }); + } else if (this.framesSinceReport >= sampleRate / 50) { + this.framesSinceReport = 0; + this.port.postMessage({ type: "position", generation: this.generation }); + } + return true; + } +} + +registerProcessor("openutau-audio-output", OpenUtauAudioProcessor); diff --git a/OpenUtauMobile.Browser/wwwroot/audio-output.js b/OpenUtauMobile.Browser/wwwroot/audio-output.js new file mode 100644 index 00000000..2f497ccb --- /dev/null +++ b/OpenUtauMobile.Browser/wwwroot/audio-output.js @@ -0,0 +1,221 @@ +// 此模块只在浏览器主线程访问 AudioContext,音频线程只消费共享帧队列。 +import { Read, Write, Playing, Consumed, Running, headerLength } from './audio-output-buffer.js'; +const deviceStorageKey = "OpenUtauMobile.AudioOutput.Device"; +let context, node, header, getHeap; +let generation = -1, intent = 0; +let onReleased, onStatus, onError, onDeviceChanged; +let selectedId = "", selectedName = "", selectionVersion = 0; +let resumePending = null; +let failed = false; + +export async function initialize(runtime) { + const exports = await runtime.getAssemblyExports("OpenUtauMobile.Browser"); + const bridge = exports.OpenUtauMobile.Browser.Services.Audio.BrowserAudioInterop; + return initializeTransport(bridge.ReleaseBuffer, bridge.UpdateStatus, bridge.ReceiveError, bridge.UpdateDevice, + () => runtime.localHeapViewU8()); +} + +export async function initializeTransport(released, status, error, deviceChanged, heap) { + onReleased = released; + getHeap = heap; + onStatus = status; + onError = error; + onDeviceChanged = deviceChanged; + if (!globalThis.crossOriginIsolated || typeof SharedArrayBuffer !== "function") { + throw new Error("Browser audio requires cross-origin isolation."); + } + try { + try { context = new AudioContext({ sampleRate: 44100, latencyHint: "interactive" }); } + catch (error) { + if (error.name !== "NotSupportedError") throw error; + context = new AudioContext({ latencyHint: "interactive" }); + } + await context.suspend(); + await context.audioWorklet.addModule(new URL("./audio-output-worklet.js", import.meta.url)); + node = new AudioWorkletNode(context, "openutau-audio-output", { + numberOfInputs: 0, numberOfOutputs: 1, outputChannelCount: [2] + }); + node.connect(context.destination); + node.port.onmessage = ({ data }) => { + if (data.type === "released") { notify(onReleased, data.generation); return; } + if (data.generation !== generation) return; + if (data.type === "ended") intent = 0; + report(); + }; + node.onprocessorerror = () => fail(new Error("The browser audio processor stopped.")); + context.onstatechange = report; + document.addEventListener("pointerdown", unlock, true); + document.addEventListener("keydown", unlock, true); + document.addEventListener("visibilitychange", visibilityChanged); + window.addEventListener("pagehide", pageHidden); + window.addEventListener("pageshow", visibilityChanged); + navigator.mediaDevices?.addEventListener("devicechange", devicesChanged); + await restoreDevice(); + return context.sampleRate; + } catch (error) { + await dispose(); + throw error; + } +} + +export function canSelectOutput() { + return typeof context?.setSinkId === "function" + && typeof navigator.mediaDevices?.selectAudioOutput === "function"; +} + +// 在用户原始事件中恢复上下文,允许之后的后台渲染完成时直接开始播放。 +function unlock(event) { + if (event.isTrusted) resume(true); +} + +function resume(force = false) { + if (!context || context.state === "closed" || context.state === "running" || document.hidden) return; + if (force || !resumePending) { + const attempt = context.resume().catch(error => { + if (intent === 1) notify(onError, generation, error.message ?? String(error)); + }).finally(() => { + if (resumePending === attempt) resumePending = null; + report(); + }); + resumePending = attempt; + } +} + +export function setPlayback(nextGeneration, nextIntent, address) { + if (failed) { + if (address && nextGeneration !== generation) notify(onReleased, nextGeneration); + throw new Error("Reload the page to restart the browser audio processor."); + } + if (nextGeneration !== generation) { + // 仅在控制操作时获取当前堆视图;已有固定范围在共享内存增长后仍指向原数据。 + let nextHeader; + try { + const buffer = address ? getHeap().buffer : null; + if (buffer && !(buffer instanceof SharedArrayBuffer)) throw new Error("Browser audio requires shared WASM memory."); + nextHeader = buffer ? new Int32Array(buffer, address >>> 0, headerLength) : null; + node.port.postMessage({ type: "configure", generation: nextGeneration, buffer, address: address >>> 0 }); + } catch (error) { + // 配置尚未送到音频线程,可以立即归还本次提交的固定缓冲。 + if (address) notify(onReleased, nextGeneration); + throw error; + } + generation = nextGeneration; + header = nextHeader; + } + intent = nextIntent; + if (intent === 1) resume(); + report(); +} + +function report() { + if (!header || !onStatus) return; + Atomics.store(header, Running, context.state === "running" && !failed ? 1 : 0); + const consumed = Atomics.load(header, Consumed) >>> 0; + const queued = ((Atomics.load(header, Write) >>> 0) - (Atomics.load(header, Read) >>> 0)) >>> 0; + const state = failed ? 3 : intent === 0 ? 0 + : intent === 1 && context.state === "running" && (queued > 0 || consumed > 0) ? 1 : 2; + notify(onStatus, generation, state, ((context.baseLatency || 0) + (context.outputLatency || 0)) * 1000); +} + +// .NET 多线程模式要求异步导出;通知不阻塞浏览器主线程,也不跨语言同步重入。 +function notify(callback, ...args) { + if (callback) Promise.resolve().then(() => callback(...args)).catch(error => console.error("Audio callback failed:", error)); +} + +export function latencyMilliseconds() { + if (!header) return 0; + const queued = ((Atomics.load(header, Write) >>> 0) - (Atomics.load(header, Read) >>> 0)) >>> 0; + return (queued / context.sampleRate + (context.baseLatency || 0) + (context.outputLatency || 0)) * 1000; +} + +function fail(error) { + failed = true; + intent = 0; + if (header) Atomics.store(header, Playing, 0); + notify(onError, generation, error.message ?? String(error)); + report(); +} + +function visibilityChanged() { + if (document.hidden) context?.suspend().catch(fail); + else if (intent === 1) { + resume(); + } +} + +function pageHidden() { + context?.suspend().catch(fail); +} + +async function restoreDevice() { + if (!canSelectOutput()) return; + let saved; + try { saved = localStorage.getItem(deviceStorageKey); } catch { return; } + if (!saved) return; + try { + const devices = await navigator.mediaDevices.enumerateDevices(); + const device = devices.find(item => item.kind === "audiooutput" && item.deviceId === saved); + if (!device) { + setDevice("", ""); + return; + } + await context.setSinkId(saved); + setDevice(saved, device.label); + } catch { + // 失效的设备或权限不妨碍默认播放,也不在启动时弹出授权窗口。 + setDevice("", ""); + } +} + +export async function selectOutput() { + if (!canSelectOutput()) return; + const version = ++selectionVersion; + // 必须在首次 await 之前请求系统选择器,以保留用户激活。 + try { + const device = await navigator.mediaDevices.selectAudioOutput(); + if (version !== selectionVersion) return; + await context.setSinkId(device.deviceId); + if (version === selectionVersion) setDevice(device.deviceId, device.label); + } catch (error) { + if (error.name !== "NotAllowedError" && error.name !== "AbortError") throw error; + } +} + +function setDevice(id, name) { + selectedId = id; + selectedName = name; + try { + if (id) localStorage.setItem(deviceStorageKey, id); + else localStorage.removeItem(deviceStorageKey); + } catch { /* 存储被禁用时,本次设备选择仍然有效。 */ } + notify(onDeviceChanged, selectedId, selectedName); +} + +async function devicesChanged() { + if (!selectedId) return; + try { + const devices = await navigator.mediaDevices.enumerateDevices(); + if (!devices.some(device => device.kind === "audiooutput" && device.deviceId === selectedId)) { + ++selectionVersion; + await context.setSinkId(""); + setDevice("", ""); + } + } catch (error) { notify(onError, generation, error.message ?? String(error)); } +} + +export async function dispose() { + intent = 0; + if (header) Atomics.store(header, Playing, 0); + document.removeEventListener("pointerdown", unlock, true); + document.removeEventListener("keydown", unlock, true); + document.removeEventListener("visibilitychange", visibilityChanged); + window.removeEventListener("pagehide", pageHidden); + window.removeEventListener("pageshow", visibilityChanged); + navigator.mediaDevices?.removeEventListener("devicechange", devicesChanged); + if (node) node.disconnect(); + if (context) { context.onstatechange = null; await context.close(); } + // 关闭上下文后音频线程已停止,随后才可解除最后一块共享缓冲的固定。 + if (header) notify(onReleased, generation); + if (node) { node.port.onmessage = null; node.port.close(); } + context = node = header = null; +} diff --git a/OpenUtauMobile.DesktopUI/OpenUtauMobile.DesktopUI.csproj b/OpenUtauMobile.DesktopUI/OpenUtauMobile.DesktopUI.csproj index 352ec67f..650a794d 100644 --- a/OpenUtauMobile.DesktopUI/OpenUtauMobile.DesktopUI.csproj +++ b/OpenUtauMobile.DesktopUI/OpenUtauMobile.DesktopUI.csproj @@ -1,6 +1,6 @@ - net10.0 + net10.0;net10.0-windows enable true diff --git a/OpenUtauMobile.DesktopUI/Views/DesktopPageLocator.cs b/OpenUtauMobile.DesktopUI/Views/DesktopPageLocator.cs index 0a4f9367..5e0316b8 100644 --- a/OpenUtauMobile.DesktopUI/Views/DesktopPageLocator.cs +++ b/OpenUtauMobile.DesktopUI/Views/DesktopPageLocator.cs @@ -130,14 +130,14 @@ private void ShowUtility(NavigateViewModelBase vm) window.KeyDown += (_, e) => { if (EditorInputController.IsComposing(window.FocusManager?.GetFocusedElement() as Visual ?? e.Source as Visual)) return; - if (!e.Handled && (e.Key == Key.Escape || e.Key == Key.W && e.KeyModifiers == (OperatingSystem.IsMacOS() ? KeyModifiers.Meta : KeyModifiers.Control)) && !IsUtilityModalOpen && vm is not ClassicSingerSetupViewModel { IsInstalling: true }) { e.Handled = true; vm.OnBackRequested(); } + if (!e.Handled && (e.Key == Key.Escape || e.Key == Key.W && e.KeyModifiers == (OperatingSystem.IsMacOS() ? KeyModifiers.Meta : KeyModifiers.Control)) && !IsUtilityModalOpen) { e.Handled = true; vm.OnBackRequested(); } }; window.Closing += (_, e) => { if (_closing) return; SaveGeometry(window, _utilityKey); e.Cancel = true; - if (!IsUtilityModalOpen && vm is not ClassicSingerSetupViewModel { IsInstalling: true }) vm.OnBackRequested(); + if (!IsUtilityModalOpen) vm.OnBackRequested(); }; window.Activated += (_, _) => RegisterWindowProviders(); window.Show(parent); diff --git a/OpenUtauMobile.DesktopUI/Views/DesktopPresentationCatalog.cs b/OpenUtauMobile.DesktopUI/Views/DesktopPresentationCatalog.cs index 24eecc49..a32d3e90 100644 --- a/OpenUtauMobile.DesktopUI/Views/DesktopPresentationCatalog.cs +++ b/OpenUtauMobile.DesktopUI/Views/DesktopPresentationCatalog.cs @@ -46,7 +46,17 @@ private static PageRoute Route(string titleKey, DesktopWindowProfile window, (about, _, _) => Utility("About.Title", new DesktopAboutPage(about))), [typeof(ExportLogsViewModel)] = Route("ExportLogs.Title", DesktopWindowProfile.Logs, (logs, _, _) => Utility("ExportLogs.Title", new DesktopExportLogsPage(logs))), - [typeof(ClassicSingerSetupViewModel)] = Route("SingerSetup.Title", DesktopWindowProfile.SingerSetup, + [typeof(UtauSingerSetupViewModel)] = Route("SingerSetup.Title", DesktopWindowProfile.SingerSetup, + (setup, _, _) => Utility("SingerSetup.Title", new DesktopSingerSetupPage(setup))), + [typeof(DiffSingerSetupViewModel)] = Route("SingerSetup.Title", DesktopWindowProfile.SingerSetup, + (setup, _, _) => Utility("SingerSetup.Title", new DesktopSingerSetupPage(setup))), + [typeof(EnunuSingerSetupViewModel)] = Route("SingerSetup.Title", DesktopWindowProfile.SingerSetup, + (setup, _, _) => Utility("SingerSetup.Title", new DesktopSingerSetupPage(setup))), + [typeof(NeutrinoSingerSetupViewModel)] = Route("SingerSetup.Title", DesktopWindowProfile.SingerSetup, + (setup, _, _) => Utility("SingerSetup.Title", new DesktopSingerSetupPage(setup))), + [typeof(SingleFileSingerSetupViewModel)] = Route("SingerSetup.Title", DesktopWindowProfile.SingerSetup, + (setup, _, _) => Utility("SingerSetup.Title", new DesktopSingerSetupPage(setup))), + [typeof(PluginSingerSetupViewModel)] = Route("SingerSetup.Title", DesktopWindowProfile.SingerSetup, (setup, _, _) => Utility("SingerSetup.Title", new DesktopSingerSetupPage(setup))), [typeof(SingerDetailViewModel)] = Route("SingerDetail.Title", DesktopWindowProfile.Standard, (singer, _, _) => Utility("SingerDetail.Title", new DesktopSingerDetailPage(singer))), diff --git a/OpenUtauMobile.DesktopUI/Views/DesktopShell.cs b/OpenUtauMobile.DesktopUI/Views/DesktopShell.cs index 0703e36c..bcc92b4e 100644 --- a/OpenUtauMobile.DesktopUI/Views/DesktopShell.cs +++ b/OpenUtauMobile.DesktopUI/Views/DesktopShell.cs @@ -113,7 +113,7 @@ void UpdateChrome() AddHandler(DragDrop.DropEvent, OnDrop); UpdateNavigation(); } - private bool Ready => !_fileAction && !PianoRollViewModel.IsBatchEditRunning && _main.CurrentViewModel is not (SplashScreenViewModel or ClassicSingerSetupViewModel { IsInstalling: true }) && !_pages.IsUtilityModalOpen && !_dialogHost.IsOpen && _main.ActiveEditor is not { IsLoadingProject: true }; + private bool Ready => !_fileAction && !PianoRollViewModel.IsBatchEditRunning && _main.CurrentViewModel is not (SplashScreenViewModel or ISingerInstallationPage { IsBusy: true }) && !_pages.IsUtilityModalOpen && !_dialogHost.IsOpen && _main.ActiveEditor is not { IsLoadingProject: true }; public void CancelInput() => _pages.Workspace?.CancelInput(); private void OnWindowActivated(object? sender, EventArgs e) => _pages.InitializeWindowProviders(); public bool PrepareFileAction() => _pages.Workspace?.PrepareFileAction() != false; @@ -266,7 +266,7 @@ private async void OnShellKeyDown(object? sender, KeyEventArgs e) await RunAsync(action); } private static bool Supported(string path) => TrackImportService.FilePatterns.Any(p => Path.GetExtension(path).Equals(p[1..], StringComparison.OrdinalIgnoreCase)) || IsAudio(path) || IsArchive(path) || IsTool(path); - private static bool IsArchive(string path) => new[] { ".zip", ".rar", ".uar" }.Contains(Path.GetExtension(path).ToLowerInvariant()); + private static bool IsArchive(string path) => SingerManagementViewModel.IsInstallPackagePath(path); private static bool IsTool(string path) => new[] { ".exe", ".bat", ".sh" }.Contains(Path.GetExtension(path).ToLowerInvariant()) || !OperatingSystem.IsWindows() && Path.GetExtension(path).Length == 0 && DesktopToolsService.IsExecutable(path); private static bool IsAudio(string path) => new[] { ".wav", ".mp3", ".flac", ".ogg", ".aac", ".aiff", ".aif", ".aifc" }.Contains(Path.GetExtension(path).ToLowerInvariant()); private void OnDragOver(object? sender, DragEventArgs e) @@ -295,7 +295,8 @@ await RunFileAsync(async () => string? archive = paths.FirstOrDefault(IsArchive); if (archive != null) { - Show(new ClassicSingerSetupViewModel(_main) { ArchiveFilePath = archive }); + using SingerManagementViewModel installers = new(_main); + await installers.ChooseInstallerAsync(archive); return; } string? tool = paths.FirstOrDefault(IsTool); diff --git a/OpenUtauMobile.DesktopUI/Views/DesktopSingerDetailPage.axaml b/OpenUtauMobile.DesktopUI/Views/DesktopSingerDetailPage.axaml index 6719e0e5..11a1e126 100644 --- a/OpenUtauMobile.DesktopUI/Views/DesktopSingerDetailPage.axaml +++ b/OpenUtauMobile.DesktopUI/Views/DesktopSingerDetailPage.axaml @@ -126,11 +126,7 @@ FontSize="{x:Static semantic:TypographyTokens.BodyMSize}" FontWeight="SemiBold" Foreground="{DynamicResource Sem.Color.Error}" /> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + VerticalAlignment="Stretch"> + + + + + + + + + + + + + + - + - + - - + + - - - - - - - - - - + + + + + + + + + + + + + + + diff --git a/OpenUtauMobile/Controls/ArrangementSurface.axaml.cs b/OpenUtauMobile/Controls/ArrangementSurface.axaml.cs index 5ac33555..f179c1f1 100644 --- a/OpenUtauMobile/Controls/ArrangementSurface.axaml.cs +++ b/OpenUtauMobile/Controls/ArrangementSurface.axaml.cs @@ -9,7 +9,7 @@ public partial class ArrangementSurface : UserControl public PartsCanvas PartsCanvas => PartsInputCanvas; public void SetHeaderExpanded(bool expanded) => TrackAreaGrid.ColumnDefinitions[0].Width = new Avalonia.Controls.GridLength(expanded ? ViewConstants.TrackHeaderWidthExpanded : ViewConstants.TrackHeaderWidthCollapsed); - public void SetDesktopChrome() { Ruler.IsVisible = true; FloatingActions.IsVisible = false; ArrangementToolbar.IsVisible = false; } + public void SetDesktopChrome() { Ruler.IsVisible = true; FloatingActions.IsVisible = false; } public ArrangementSurface() { InitializeComponent(); diff --git a/OpenUtauMobile/Controls/AsyncAvatarImage.cs b/OpenUtauMobile/Controls/AsyncAvatarImage.cs new file mode 100644 index 00000000..058c0ebc --- /dev/null +++ b/OpenUtauMobile/Controls/AsyncAvatarImage.cs @@ -0,0 +1,88 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Media.Imaging; +using OpenUtauMobile.Services; + +namespace OpenUtauMobile.Controls; + +/// 后台解码歌手头像,控件只在 UI 线程接收和释放当前图片。 +public sealed class AsyncAvatarImage : Image +{ + public static readonly StyledProperty DataProperty = + AvaloniaProperty.Register(nameof(Data)); + + private CancellationTokenSource? _loading; + private Bitmap? _bitmap; + private bool _attached; + + /// 已经预读到内存的只读头像数据,不触发歌手实例的文件加载。 + public byte[]? Data + { + get => GetValue(DataProperty); + set => SetValue(DataProperty, value); + } + + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) + { + base.OnPropertyChanged(change); + if (change.Property == DataProperty && _attached) RefreshImage(); + } + + protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) + { + base.OnAttachedToVisualTree(e); + _attached = true; + RefreshImage(); + } + + protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e) + { + _attached = false; + ClearImage(); + base.OnDetachedFromVisualTree(e); + } + + /// 替换头像或卸载时取消旧请求,图片解绑后再释放。 + private void ClearImage() + { + _loading?.Cancel(); + _loading = null; + Source = null; + _bitmap?.Dispose(); + _bitmap = null; + } + + /// 只有已挂载的控件才请求解码,等待期间保留宿主的文字头像。 + private void RefreshImage() + { + ClearImage(); + if (Data is { Length: > 0 } data) _ = LoadAsync(data); + } + + /// 完成后检查请求身份,切换和卸载后返回的图片立即释放。 + private async Task LoadAsync(byte[] data) + { + using CancellationTokenSource loading = new(); + _loading = loading; + try + { + Bitmap bitmap = await BitmapLoader.DecodeAsync(data, loading.Token); + if (!_attached || loading.IsCancellationRequested || !ReferenceEquals(_loading, loading)) + { + bitmap.Dispose(); + return; + } + _bitmap = bitmap; + Source = bitmap; + } + catch (OperationCanceledException) when (loading.IsCancellationRequested) { } + catch (Exception) { /* 无效图片继续使用宿主的文字头像。 */ } + finally + { + if (ReferenceEquals(_loading, loading)) _loading = null; + } + } +} diff --git a/OpenUtauMobile/Controls/DialogKeyboard.cs b/OpenUtauMobile/Controls/DialogKeyboard.cs index c4af3a75..d7f3b6f7 100644 --- a/OpenUtauMobile/Controls/DialogKeyboard.cs +++ b/OpenUtauMobile/Controls/DialogKeyboard.cs @@ -113,8 +113,14 @@ private void Preview(object? sender, KeyEventArgs e) { if (e.Key != Key.Enter || e.KeyModifiers != KeyModifiers.None) return; _keyShell = Shells.LastOrDefault(s => s.IsEffectivelyVisible); - if (_keyShell == null && !_enterDown) return; Visual? source = e.Source as Visual; + // 浮于弹窗上方的提示拥有自己的按键处理,不触发下层弹窗默认动作。 + if (_keyShell != null && !Within(source, _keyShell)) + { + _keyShell = null; + return; + } + if (_keyShell == null && !_enterDown) return; // 多行输入的重复 Enter 仍由文本框处理。 if (source?.GetSelfAndVisualAncestors().OfType().Any(t => t.AcceptsReturn) == true) return; if (_enterDown) { e.Handled = true; return; } @@ -128,7 +134,7 @@ private void Complete(object? sender, KeyEventArgs e) if (e.Key == Key.Escape && e.KeyModifiers == KeyModifiers.None && !IsComposing(e.Source as Visual)) { DialogShell? active = Shells.LastOrDefault(s => s.IsEffectivelyVisible); - if (active?.CloseCommand is { } cancel && cancel.CanExecute(null)) + if (active?.CloseCommand is { } cancel && Within(e.Source as Visual, active) && cancel.CanExecute(null)) { e.Handled = true; cancel.Execute(null); diff --git a/OpenUtauMobile/Controls/EditorContextActions.axaml b/OpenUtauMobile/Controls/EditorContextActions.axaml index 508371d9..17777309 100644 --- a/OpenUtauMobile/Controls/EditorContextActions.axaml +++ b/OpenUtauMobile/Controls/EditorContextActions.axaml @@ -1,11 +1,7 @@ - - - - - - + + diff --git a/OpenUtauMobile/Controls/EditorContextActions.axaml.cs b/OpenUtauMobile/Controls/EditorContextActions.axaml.cs index 96f64d72..9b9443da 100644 --- a/OpenUtauMobile/Controls/EditorContextActions.axaml.cs +++ b/OpenUtauMobile/Controls/EditorContextActions.axaml.cs @@ -1,26 +1,22 @@ using System.Collections.Generic; +using System.Linq; using Avalonia; -using Avalonia.Automation; using Avalonia.Controls; -using Avalonia.Controls.Primitives; -using Avalonia.Layout; -using Avalonia.Media; -using IconPacks.Avalonia.PhosphorIcons; -using OpenUtauMobile.Themes.OpenUtauMobile.Tokens.Semantic; +using OpenUtauMobile.Themes.OpenUtauMobile.Controls; using OpenUtauMobile.ViewModels; namespace OpenUtauMobile.Controls; -/// 沿编辑区边缘排列、始终显示的可滚动上下文操作栏。 +/// 各编辑区内可拖拽贴边的纵向浮动工具栏,复用公共工具栏的溢出和键盘行为。 public partial class EditorContextActions : UserControl { /// 现有视图模型生成的上下文操作。 public static readonly StyledProperty?> ActionsProperty = AvaloniaProperty.Register?>(nameof(Actions)); - /// 沿所在编辑区边缘的排列方向。 - public static readonly StyledProperty OrientationProperty = - AvaloniaProperty.Register(nameof(Orientation), Orientation.Vertical); + /// 保留原有交互的编辑模式入口。 + public static readonly StyledProperty ModeSwitchProperty = + AvaloniaProperty.Register(nameof(ModeSwitch)); /// 现有视图模型生成的上下文操作。 public IReadOnlyList? Actions @@ -29,64 +25,39 @@ public IReadOnlyList? Actions set => SetValue(ActionsProperty, value); } - /// 横向用于走带底栏,纵向用于钢琴卷帘侧栏。 - public Orientation Orientation + /// 独立于操作列表的编辑模式入口。 + public Control? ModeSwitch { - get => GetValue(OrientationProperty); - set => SetValue(OrientationProperty, value); + get => GetValue(ModeSwitchProperty); + set => SetValue(ModeSwitchProperty, value); } - /// 初始化有限滚动视口。 + /// 初始化限制在当前编辑区内的浮动层。 public EditorContextActions() { InitializeComponent(); - UpdateOrientation(); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); - if (ActionsList == null) return; + if (Toolbar == null) return; if (change.Property == ActionsProperty) UpdateActionsList(); - if (change.Property == OrientationProperty) UpdateOrientation(); + if (change.Property == ModeSwitchProperty) Toolbar.LeadingContent = ModeSwitch; } - /// 将滚动方向同步到所在边缘。 - private void UpdateOrientation() - { - bool horizontal = Orientation == Orientation.Horizontal; - ActionsList.Orientation = Orientation; - ActionsScrollViewer.HorizontalScrollBarVisibility = horizontal ? ScrollBarVisibility.Hidden : ScrollBarVisibility.Disabled; - ActionsScrollViewer.VerticalScrollBarVisibility = horizontal ? ScrollBarVisibility.Disabled : ScrollBarVisibility.Hidden; - } - - /// 保留操作命令及状态文字,以紧凑图标和文字显示普通操作。 + /// 将现有操作适配到公共工具栏,命令与无障碍名称保持一致。 private void UpdateActionsList() { - ActionsList.Children.Clear(); - if (Actions == null) return; - foreach (ContextActionItem action in Actions) + IReadOnlyList actions = Actions == null ? [] : [.. Actions.Select(action => new FloatingToolbarAction { - Control symbol = action.Label != null - ? new TextBlock { Text = action.Label, FontSize = TypographyTokens.LabelSSize, FontWeight = FontWeight.SemiBold, HorizontalAlignment = HorizontalAlignment.Center } - : new PackIconPhosphorIcons { Kind = action.Icon, Width = IconTokens.Small, Height = IconTokens.Small, HorizontalAlignment = HorizontalAlignment.Center }; - Button button = new() - { - Classes = { "ContextActionBtn" }, - Command = action.Command, - Content = new StackPanel - { - Spacing = 2, - Children = - { - symbol, - new TextBlock { Classes = { "ContextActionCaption" }, Text = action.Tip, FontSize = TypographyTokens.LabelSSize, LineHeight = 14, MaxHeight = 28, TextWrapping = TextWrapping.Wrap, TextTrimming = TextTrimming.CharacterEllipsis, TextAlignment = TextAlignment.Center }, - }, - }, - }; - ToolTip.SetTip(button, action.Tip); - AutomationProperties.SetName(button, action.Tip); - ActionsList.Children.Add(button); - } + Text = action.Tip, + Icon = action.Icon, + Label = action.Label, + Command = action.Command, + HoldCommand = action.HoldCommand, + IsDanger = action.IsDanger + })]; + Toolbar.Actions = actions; } } diff --git a/OpenUtauMobile/Controls/EditorModePicker.axaml.cs b/OpenUtauMobile/Controls/EditorModePicker.axaml.cs index 4609532f..f61be6be 100644 --- a/OpenUtauMobile/Controls/EditorModePicker.axaml.cs +++ b/OpenUtauMobile/Controls/EditorModePicker.axaml.cs @@ -155,7 +155,7 @@ private void UpdateSelection() foreach (EditorModeOption option in _options) { if (option.Value == SelectedValue) - SwitchButton.Content = new PackIconPhosphorIcons { Kind = option.Icon, Width = IconTokens.Small, Height = IconTokens.Small }; + SwitchButton.Content = new PackIconPhosphorIcons { Classes = { "EditModeIcon" }, Kind = option.Icon }; } foreach (Control item in _layer.Items.Children) item.Classes.Set("Selected", Equals(item.Tag, SelectedValue)); diff --git a/OpenUtauMobile/Controls/EditorMorePopup.axaml b/OpenUtauMobile/Controls/EditorMorePopup.axaml index ab7c018d..3c2d82dc 100644 --- a/OpenUtauMobile/Controls/EditorMorePopup.axaml +++ b/OpenUtauMobile/Controls/EditorMorePopup.axaml @@ -41,6 +41,12 @@ Content="{DynamicResource ExpressionGraph.Title}" Command="{Binding ConfirmCommand}"> ExpressionGraphs + 为编辑器固定侧栏提供统一的 MD3 Level 3 双层阴影。 + public class EditorRailSurface : Border + { + /// 随主题变化的语义阴影色。 + public static readonly StyledProperty ShadowColorProperty = + AvaloniaProperty.Register(nameof(ShadowColor)); + + /// 获取或设置侧栏的语义阴影色。 + public Color ShadowColor + { + get => GetValue(ShadowColorProperty); + set => SetValue(ShadowColorProperty, value); + } + + /// 在主题阴影色变化时同步更新主阴影与环境阴影。 + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) + { + base.OnPropertyChanged(change); + if (change.Property == ShadowColorProperty) + { + Color color = ShadowColor; + // MD3 Level 3:主阴影 (0,1,3,0),环境阴影 (0,4,8,3)。 + BoxShadow = new BoxShadows( + new BoxShadow + { + OffsetY = 1, + Blur = 3, + Color = Color.FromArgb((byte)(color.A * 0.30), color.R, color.G, color.B) + }, + [new BoxShadow + { + OffsetY = 4, + Blur = 8, + Spread = 3, + Color = Color.FromArgb((byte)(color.A * 0.15), color.R, color.G, color.B) + }]); + } + } + } +} \ No newline at end of file diff --git a/OpenUtauMobile/Controls/ErrorDialogPopup.axaml b/OpenUtauMobile/Controls/ErrorDialogPopup.axaml index 3142e927..b99f71e4 100644 --- a/OpenUtauMobile/Controls/ErrorDialogPopup.axaml +++ b/OpenUtauMobile/Controls/ErrorDialogPopup.axaml @@ -18,7 +18,10 @@ - + + + + @@ -47,42 +50,42 @@ - - - - - - - - - + + + + + + + + + + + + + diff --git a/OpenUtauMobile/Controls/ErrorDialogPopup.axaml.cs b/OpenUtauMobile/Controls/ErrorDialogPopup.axaml.cs index 899852b3..7a12665e 100644 --- a/OpenUtauMobile/Controls/ErrorDialogPopup.axaml.cs +++ b/OpenUtauMobile/Controls/ErrorDialogPopup.axaml.cs @@ -7,7 +7,7 @@ public partial class ErrorDialogPopup : PopupDialogControl { private bool _detailExpanded; - protected override PopupDialogWidthPreset WidthPreset => PopupDialogWidthPreset.Regular; + protected override PopupDialogWidthPreset WidthPreset => PopupDialogWidthPreset.Wide; public ErrorDialogPopup() { @@ -18,6 +18,7 @@ private void OnDetailToggleClicked(object? sender, RoutedEventArgs e) { _detailExpanded = !_detailExpanded; DetailPanel.IsVisible = _detailExpanded; + MessagePanel.IsVisible = !_detailExpanded; DetailChevron.Kind = _detailExpanded ? PackIconPhosphorIconsKind.CaretUp : PackIconPhosphorIconsKind.CaretDown; diff --git a/OpenUtauMobile/Controls/FilePickerPopup.axaml b/OpenUtauMobile/Controls/FilePickerPopup.axaml index 427782c1..9b259494 100644 --- a/OpenUtauMobile/Controls/FilePickerPopup.axaml +++ b/OpenUtauMobile/Controls/FilePickerPopup.axaml @@ -214,7 +214,7 @@ FontSize="14" TextTrimming="CharacterEllipsis" /> diff --git a/OpenUtauMobile/Controls/GhostNotesVisibilityChangedEvent.cs b/OpenUtauMobile/Controls/GhostNotesVisibilityChangedEvent.cs new file mode 100644 index 00000000..de11c8ed --- /dev/null +++ b/OpenUtauMobile/Controls/GhostNotesVisibilityChangedEvent.cs @@ -0,0 +1,4 @@ +namespace OpenUtauMobile.Controls; + +/// 通知钢琴卷帘更新背景音符的显示状态。 +public sealed record GhostNotesVisibilityChangedEvent; diff --git a/OpenUtauMobile/Controls/GraphItemPickerPopup.axaml b/OpenUtauMobile/Controls/GraphItemPickerPopup.axaml index d84facdb..9aba0225 100644 --- a/OpenUtauMobile/Controls/GraphItemPickerPopup.axaml +++ b/OpenUtauMobile/Controls/GraphItemPickerPopup.axaml @@ -15,8 +15,8 @@ - + diff --git a/OpenUtauMobile/Controls/MagnifierControl.cs b/OpenUtauMobile/Controls/MagnifierControl.cs index 285e109a..e076dd57 100644 --- a/OpenUtauMobile/Controls/MagnifierControl.cs +++ b/OpenUtauMobile/Controls/MagnifierControl.cs @@ -49,6 +49,7 @@ public class MagnifierControl : Control private Visual? _source; private readonly VisualBrush _visualBrush = new(); private bool _hasSample; + private Rect _sampleDestinationRect; private Point _focusPointInSource; @@ -144,28 +145,26 @@ public void UpdateView(Point focusPointInSource) double factor = MagnificationFactor; Size size = Bounds.Size; - double width = Math.Min(size.Width / factor, _source.Bounds.Width); - double height = Math.Min(size.Height / factor, _source.Bounds.Height); - _hasSample = width > 0 && height > 0; + double width = size.Width / factor; + double height = size.Height / factor; + // 完整采样框始终以目标点为中心,不因触及源控件边界而停住。 + SourceRect = new Rect(_focusPointInSource.X - width / 2, + _focusPointInSource.Y - height / 2, width, height); + Rect sampleRect = SourceRect.Intersect(new Rect(_source.Bounds.Size)); + _hasSample = sampleRect.Width > 0 && sampleRect.Height > 0; if (!_hasSample) { InvalidateVisual(); return; } - double x = Math.Clamp(_focusPointInSource.X - width / 2, 0, _source.Bounds.Width - width); - double y = Math.Clamp(_focusPointInSource.Y - height / 2, 0, _source.Bounds.Height - height); - SourceRect = new Rect(x, y, width, height); - - // 用 VisualBrush.SourceRect 指定“源控件中被采样”的绝对区域。 - // 目标区域按实际倍率计算,避免源区域不足时改变缩放比例。 - _visualBrush.SourceRect = new RelativeRect(SourceRect, RelativeUnit.Absolute); - - // 源区域小于镜片时居中留出主题背景,不把不足的内容拉伸到另一倍率。 - _visualBrush.DestinationRect = new RelativeRect(new Rect( - (size.Width - width * factor) / 2, - (size.Height - height * factor) / 2, - width * factor, height * factor), RelativeUnit.Absolute); + // 只采样有效交集,并保留其相对完整采样框的偏移与倍率。 + _visualBrush.SourceRect = new RelativeRect(sampleRect, RelativeUnit.Absolute); + _sampleDestinationRect = new Rect( + (sampleRect.X - SourceRect.X) * factor, + (sampleRect.Y - SourceRect.Y) * factor, + sampleRect.Width * factor, sampleRect.Height * factor); + _visualBrush.DestinationRect = new RelativeRect(_sampleDestinationRect, RelativeUnit.Absolute); // 设置笔刷源 _visualBrush.Visual = _source; @@ -192,13 +191,18 @@ public override void Render(DrawingContext context) Color = Color.FromArgb((byte)(ShadowColor.A * 0.18), ShadowColor.R, ShadowColor.G, ShadowColor.B) }); - // 阴影在裁切外绘制,镜片内容和背景共同使用圆角裁切。 - context.DrawRectangle(Background, null, roundedRect, shadows); + // 阴影在裁切外绘制,透明底保留镜片中超出源控件边界的空白。 + context.DrawRectangle(Brushes.Transparent, null, roundedRect, shadows); using (context.PushClip(roundedRect)) { if (_source != null && _hasSample) { - context.FillRectangle(_visualBrush, rect); + // 背景与内容仅绘制到有效区域,边界外保持透明。 + using (context.PushClip(_sampleDestinationRect)) + { + context.DrawRectangle(Background, null, _sampleDestinationRect); + context.FillRectangle(_visualBrush, rect); + } } } diff --git a/OpenUtauMobile/Controls/NotesCanvas.cs b/OpenUtauMobile/Controls/NotesCanvas.cs index fd7734f3..70d69d8e 100644 --- a/OpenUtauMobile/Controls/NotesCanvas.cs +++ b/OpenUtauMobile/Controls/NotesCanvas.cs @@ -87,7 +87,7 @@ public double KeyOffset private const int RenderPitchSampleInterval = 5; // 音高采样间隔(tick) private const double PitchHandleRadius = 5.0; private const double PitchHandleDiameter = PitchHandleRadius * 2; - private const double NoteBodyCornerRadius = 4; + private const double NoteBodyCornerRadius = 8; private readonly Geometry _pointGeometry = new EllipseGeometry( new Rect(-PitchHandleRadius, -PitchHandleRadius, PitchHandleDiameter, PitchHandleDiameter)); @@ -148,7 +148,8 @@ protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) _renderViewSubscription?.Dispose(); _renderViewSubscription = RenderView.Inst.Observe(projection => { - if (ReferenceEquals(projection.Part, Part)) InvalidateVisual(); + if (ReferenceEquals(projection.Part, Part) || Preferences.Default.PianoRollShowGhostNotes) + InvalidateVisual(); }); ViewModel = DataContext as PianoRollViewModel; if (ViewModel != null) @@ -184,6 +185,7 @@ public override void Render(DrawingContext context) int rightTick = (int)(leftTick + Bounds.Width / TickWidth); SolidColorBrush brush = TrackPalette.GetTrackColor(DocManager.Inst.Project.tracks[Part.trackNo].TrackColor) .AccentColor; + RenderGhostNotes(context, leftTick, rightTick); RenderPitchPenHitArea(context); // ———— 绘制主体 ———— foreach (UNote note in Part.notes) @@ -216,17 +218,17 @@ public override void Render(DrawingContext context) bool isSelected = ViewModel.IsNoteSelected(note); // 定位 - Point leftTop = ViewModel.TickPitchToPoint(note.position + Part.position, note.AdjustedTone); + Point leftTop = ViewModel.TickPitchToPoint(note.position + Part.position, note.AdjustedTone) + new Avalonia.Vector(1, 0); Size size = ViewModel.TickToneToSize(note.duration, 1); Point rightBottom = new(leftTop.X + size.Width, leftTop.Y + size.Height); // 圆角矩形 - Rect rect = new(leftTop, rightBottom); + Rect rect = new Rect(leftTop, rightBottom).Deflate(new Thickness(0, 4)); RoundedRect roundedRect = new(rect, new CornerRadius(NoteBodyCornerRadius)); // 边框:表示选中状态 - IPen borderPen = isSelected - ? ThemeResources.GetPen("Sem.Color.Primary", 1.5) - : ThemeResources.GetPen("Sem.Color.OutlineVariant", 0.5); - context.DrawRectangle(null, borderPen, roundedRect); + if (isSelected) + { + context.DrawRectangle(null, ThemeResources.GetPen("Sem.Color.Primary", 1.5), roundedRect); + } if ((ViewModel.EditMode != PianoRollEditMode.MultiSelect && ViewModel.EditMode != PianoRollEditMode.Note) || @@ -364,6 +366,43 @@ private void RenderPitchPenHitArea(DrawingContext context) } } + /// 绘制其它轨道中与当前片段重叠的背景音符,不参与编辑命中。 + private void RenderGhostNotes(DrawingContext context, int leftTick, int rightTick) + { + if (!Preferences.Default.PianoRollShowGhostNotes || Part == null || ViewModel == null) return; + + UProject project = DocManager.Inst.Project; + // 背景音符沿用上游的半行高度与内缩,保持在音高行中央。 + double height = Math.Floor(KeyHeight * 0.2 - 2); + if (height <= 0) return; + using (context.PushClip(new Rect(Bounds.Size))) + using (context.PushOpacity(0.2)) + { + foreach (UPart otherPart in project.parts) + { + if (otherPart is not UVoicePart voicePart || otherPart.trackNo == Part.trackNo || + otherPart.position >= Part.End || otherPart.End <= Part.position || + otherPart.position > rightTick || otherPart.End < leftTick) + continue; + + IBrush brush = TrackPalette.GetTrackColor(project.tracks[otherPart.trackNo].TrackColor).AccentColor; + foreach (UNote note in voicePart.notes) + { + int position = voicePart.position + note.position; + if (position > rightTick) break; + if (voicePart.position + note.End < leftTick) continue; + + Point topLeft = ViewModel.TickPitchToPoint(position, note.AdjustedTone); + double width = ViewModel.TickToneToSize(note.duration, 1).Width - 1; + if (width <= 0) continue; + Rect rect = new(topLeft.X + 1, Math.Round(topLeft.Y + 1 + Math.Floor(KeyHeight * 0.4)), width, height); + if (rect.Bottom < 0 || rect.Top > Bounds.Height) continue; + context.DrawRectangle(brush, null, rect, 2, 2); + } + } + } + } + /// /// 绘制音符主体(矩形 + 歌词) /// @@ -374,12 +413,12 @@ private void RenderNoteBody(UNote note, DrawingContext context, SolidColorBrush { if (ViewModel == null || Part == null) return; - Point leftTop = ViewModel.TickPitchToPoint(note.position + Part.position, note.AdjustedTone); + Point leftTop = ViewModel.TickPitchToPoint(note.position + Part.position, note.AdjustedTone) + new Avalonia.Vector(1, 0); Size size = ViewModel.TickToneToSize(note.duration, 1); Point rightBottom = new(leftTop.X + size.Width, leftTop.Y + size.Height); // 圆角矩形 - Rect rect = new(leftTop, rightBottom); + Rect rect = new Rect(leftTop, rightBottom).Deflate(new Thickness(0, 4)); RoundedRect roundedRect = new(rect, new CornerRadius(NoteBodyCornerRadius)); // 根据错误状态选择颜色 @@ -1122,6 +1161,8 @@ public void OnNext(UCommand cmd, bool isUndo) { case NoteCommand: case PartCommand: + case TrackCommand: + case LoadProjectNotification: case SetCurveCommand: case MaskedCurveCommand: case PhonemizedNotification: diff --git a/OpenUtauMobile/Controls/PartsCanvas.DesktopInput.cs b/OpenUtauMobile/Controls/PartsCanvas.DesktopInput.cs index afe4c275..13b5bf75 100644 --- a/OpenUtauMobile/Controls/PartsCanvas.DesktopInput.cs +++ b/OpenUtauMobile/Controls/PartsCanvas.DesktopInput.cs @@ -16,6 +16,8 @@ private enum DesktopPartOperation { None, Pan, Box, Edit } private DesktopPartOperation _desktopOperation; private Point _desktopPress, _desktopLast; private bool _desktopDragging; + private bool _desktopMultiSelectTap; + private bool _desktopTogglePartToolbar; private bool _lastDesktopPressWasLeft; private Rect? _desktopBox; private UPart[] _desktopSelection = []; @@ -33,13 +35,22 @@ private bool HandleDesktopPressed(PointerPressedEventArgs e) _desktopOwner = vm; _desktopPress = _desktopLast = e.GetPosition(this); _desktopDragging = false; - vm.TrackEditMode = TrackEditMode.Normal; + _desktopMultiSelectTap = false; bool toggle = e.KeyModifiers.HasFlag(KeyModifiers.Control) || e.KeyModifiers.HasFlag(KeyModifiers.Meta); bool additive = toggle || e.KeyModifiers.HasFlag(KeyModifiers.Shift); _desktopSelection = vm.SelectedParts.ToArray(); // 先识别扩展到分片外的移动区域,避免误清选区或选中相邻分片。 UPart? hit = vm.HitTestMoveHandle(_desktopPress) ?? vm.HitTestPart(_desktopPress); + // 在按下前记录是否已经选中,避免首次选中或拖动结束后误展开工具栏。 + _desktopTogglePartToolbar = left && unmodified && vm.TrackEditMode == TrackEditMode.Normal && + hit != null && vm.SelectedParts.Contains(hit); if (!left) { _desktopOperation = DesktopPartOperation.Pan; vm.BeginViewportInput(); } + else if (vm.TrackEditMode == TrackEditMode.MultiSelect && !additive) + { + // 单击在松手后反选;拖动交给共用逻辑,空白和主体平移,手柄仍可编辑选区。 + _desktopMultiSelectTap = true; + _desktopOperation = DesktopPartOperation.Edit; + } else if (hit == null) { if (!additive) vm.SelectedParts.Clear(); @@ -50,7 +61,7 @@ private bool HandleDesktopPressed(PointerPressedEventArgs e) else { if (!vm.SelectedParts.Contains(hit)) { if (!additive) vm.SelectedParts.Clear(); vm.SelectedParts.Add(hit); } - _desktopOperation = doubleClick ? DesktopPartOperation.None : DesktopPartOperation.Edit; + _desktopOperation = DesktopPartOperation.Edit; } _desktopPointer = e.Pointer; e.Pointer.Capture(this); @@ -108,13 +119,17 @@ internal void EndDesktopPointer(bool cancel, Point point = default, ulong timest vm.SelectedParts.Clear(); foreach (UPart part in _desktopSelection) vm.SelectedParts.Add(part); } + if (!cancel && !_desktopDragging && _desktopMultiSelectTap) vm.OnGestureTap(point); + if (!cancel && !_desktopDragging && _desktopTogglePartToolbar) vm.TogglePartToolbar(); } _desktopBox = null; _desktopSelection = []; _desktopOperation = DesktopPartOperation.None; + _desktopMultiSelectTap = false; + _desktopTogglePartToolbar = false; if (cancel) _lastDesktopPressWasLeft = false; pointer?.Capture(null); InvalidateVisual(); } } -} \ No newline at end of file +} diff --git a/OpenUtauMobile/Controls/PhonemeSimpleCanvas.cs b/OpenUtauMobile/Controls/PhonemeSimpleCanvas.cs index 91ccae2a..f2858b65 100644 --- a/OpenUtauMobile/Controls/PhonemeSimpleCanvas.cs +++ b/OpenUtauMobile/Controls/PhonemeSimpleCanvas.cs @@ -17,7 +17,7 @@ namespace OpenUtauMobile.Controls; /// -/// 简易音素画布,SynthV 风格:独立的圆角音素卡片,卡片之间有清晰间距与显著的垂直边界手柄。 +/// 显示音素卡片与可拖动的边界手柄。 /// 双击音素卡片直接唤起音素别名编辑弹窗。 /// public class PhonemeSimpleCanvas : Control, ICmdSubscriber @@ -257,7 +257,7 @@ public override void Render(DrawingContext context) IBrush currentTextBrush = hasError ? errorText : isSelected ? selectedTextBrush : textBrush; IPen borderPen = hasError ? isSelected ? selectedErrorBorder : errorBorder : chipBorderPen; - // 1. 绘制音素卡片(SynthV 风格独立圆角药丸框) + // 1. 绘制音素卡片 Rect blockRect = new Rect(chipLeft, topMargin, chipWidth, blockHeight); context.DrawRectangle(fillBrush, borderPen, blockRect, 4, 4); diff --git a/OpenUtauMobile/Controls/PianoRollEditModeSwitcher.axaml b/OpenUtauMobile/Controls/PianoRollEditModeSwitcher.axaml index f9037667..e7285f78 100644 --- a/OpenUtauMobile/Controls/PianoRollEditModeSwitcher.axaml +++ b/OpenUtauMobile/Controls/PianoRollEditModeSwitcher.axaml @@ -2,5 +2,5 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:c="clr-namespace:OpenUtauMobile.Controls" x:Class="OpenUtauMobile.Controls.PianoRollEditModeSwitcher"> - + \ No newline at end of file diff --git a/OpenUtauMobile/Controls/PianoRollEditModeSwitcher.axaml.cs b/OpenUtauMobile/Controls/PianoRollEditModeSwitcher.axaml.cs index df3be363..f2385e0d 100644 --- a/OpenUtauMobile/Controls/PianoRollEditModeSwitcher.axaml.cs +++ b/OpenUtauMobile/Controls/PianoRollEditModeSwitcher.axaml.cs @@ -11,8 +11,7 @@ public partial class PianoRollEditModeSwitcher : UserControl { /// 当前编辑模式。 public static readonly StyledProperty CurrentModeProperty = - AvaloniaProperty.Register(nameof(CurrentMode), - PianoRollEditMode.Hand, defaultBindingMode: BindingMode.TwoWay); + AvaloniaProperty.Register(nameof(CurrentMode), defaultBindingMode: BindingMode.TwoWay); /// 当前编辑区使用的模式。 public PianoRollEditMode CurrentMode @@ -41,12 +40,12 @@ protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs chang private void UpdateOptions() { Picker.SetOptions([ - new((int)PianoRollEditMode.Hand, PackIconPhosphorIconsKind.Hand, "PianoRoll.DragSelect"), - new((int)PianoRollEditMode.MultiSelect, PackIconPhosphorIconsKind.Selection, "PianoRoll.MultiSelect"), - new((int)PianoRollEditMode.Note, PackIconPhosphorIconsKind.MusicNoteSimple, "PianoRoll.NotePen"), - new((int)PianoRollEditMode.PitchPen, PackIconPhosphorIconsKind.Pencil, "PianoRoll.PitchPen"), - new((int)PianoRollEditMode.Anchor, PackIconPhosphorIconsKind.Cursor, "PianoRoll.Anchor"), - new((int)PianoRollEditMode.Vibrato, PackIconPhosphorIconsKind.WaveSine, "PianoRoll.Vibrato"), + new EditorModeOption((int)PianoRollEditMode.Hand, PackIconPhosphorIconsKind.Hand, "PianoRoll.DragSelect"), + new EditorModeOption((int)PianoRollEditMode.MultiSelect, PackIconPhosphorIconsKind.Selection, "PianoRoll.MultiSelect"), + new EditorModeOption((int)PianoRollEditMode.Note, PackIconPhosphorIconsKind.MusicNoteSimple, "PianoRoll.NotePen"), + new EditorModeOption((int)PianoRollEditMode.PitchPen, PackIconPhosphorIconsKind.Pencil, "PianoRoll.PitchPen"), + new EditorModeOption((int)PianoRollEditMode.Anchor, PackIconPhosphorIconsKind.Cursor, "PianoRoll.Anchor"), + new EditorModeOption((int)PianoRollEditMode.Vibrato, PackIconPhosphorIconsKind.WaveSine, "PianoRoll.Vibrato"), ]); } } \ No newline at end of file diff --git a/OpenUtauMobile/Controls/PianoRollSurface.axaml b/OpenUtauMobile/Controls/PianoRollSurface.axaml index 3c00796c..da0d613b 100644 --- a/OpenUtauMobile/Controls/PianoRollSurface.axaml +++ b/OpenUtauMobile/Controls/PianoRollSurface.axaml @@ -1,6 +1,5 @@ - - - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - + KeyOffset="{Binding KeyOffset}" + ProjectKey="{Binding ProjectKey}" + LabelMode="{Binding PianoKeyLabelMode}" /> + + + + + + + + + + - - - - - - - - - + + + + + + + - - - - - - - - - + Fill="{DynamicResource Sem.Color.Surface}" + Stroke="{DynamicResource Sem.Color.Outline}" + StrokeThickness="1" + Stretch="Fill" /> + + + + - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + - - - - - - + Actions="{Binding PianoRollContextActions}"> + + + + + diff --git a/OpenUtauMobile/Controls/PianoRollSurface.axaml.cs b/OpenUtauMobile/Controls/PianoRollSurface.axaml.cs index 5f7ecfd7..8b7cb290 100644 --- a/OpenUtauMobile/Controls/PianoRollSurface.axaml.cs +++ b/OpenUtauMobile/Controls/PianoRollSurface.axaml.cs @@ -11,6 +11,8 @@ public partial class PianoRollSurface : UserControl { public Grid LayoutGrid => PART_PianoRollGrid; public NotesCanvas NotesCanvas => NotesInputCanvas; + /// 待确认音符的入口,供页级输入绑定识别占位框内部点击。 + public Button NoteCreationPreview => NoteCreationPreviewButton; public Border Ruler => PianoInputRuler; public PhonemeParamPanel ParameterPanel => PhonemeParamPanel; private bool _desktopResizeGrip; diff --git a/OpenUtauMobile/Controls/PluginFieldsPanel.cs b/OpenUtauMobile/Controls/PluginFieldsPanel.cs new file mode 100644 index 00000000..55f14d4d --- /dev/null +++ b/OpenUtauMobile/Controls/PluginFieldsPanel.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.Templates; +using Avalonia.Data; +using Avalonia.Data.Converters; +using Avalonia.Layout; +using OpenUtauMobile.Plugin.Abstractions; +using OpenUtauMobile.ViewModels; + +namespace OpenUtauMobile.Controls +{ + /// 使用宿主标准控件呈现声明式字段,不加载插件视图。 + public sealed class PluginFieldsPanel : StackPanel + { + public static readonly StyledProperty?> FieldsProperty = + AvaloniaProperty.Register?>(nameof(Fields)); + public IReadOnlyList? Fields { get => GetValue(FieldsProperty); set => SetValue(FieldsProperty, value); } + + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) + { + base.OnPropertyChanged(change); + if (change.Property != FieldsProperty) return; + Children.Clear(); + Spacing = Themes.OpenUtauMobile.Tokens.Foundation.LayoutTokens.SpaceM; + foreach (PluginFieldViewModel field in Fields ?? []) + { + PluginFieldDescriptor descriptor = field.Descriptor; + if (!descriptor.IsVisible) continue; + StackPanel row = new() { DataContext = field, Spacing = 8, IsEnabled = descriptor.IsEnabled }; + if (descriptor.Kind != PluginFieldKind.Boolean) + row.Children.Add(new TextBlock { Text = descriptor.Label, TextWrapping = Avalonia.Media.TextWrapping.Wrap }); + if (!string.IsNullOrEmpty(descriptor.Description)) + row.Children.Add(new TextBlock { Text = descriptor.Description, TextWrapping = Avalonia.Media.TextWrapping.Wrap }); + switch (descriptor.Kind) + { + case PluginFieldKind.Boolean: + CheckBox check = new() { Content = descriptor.Label }; + check.Bind(CheckBox.IsCheckedProperty, new Binding(nameof(field.Checked)) { Mode = BindingMode.TwoWay }); + row.Children.Add(check); + break; + case PluginFieldKind.Number: + NumericUpDown number = new() { Minimum = descriptor.Minimum ?? decimal.MinValue, Maximum = descriptor.Maximum ?? decimal.MaxValue }; + number.Bind(NumericUpDown.ValueProperty, new Binding(nameof(field.Number)) { Mode = BindingMode.TwoWay }); + row.Children.Add(number); + break; + case PluginFieldKind.Selection: + ComboBox combo = new() + { + ItemsSource = descriptor.Options.IsDefault ? [] : descriptor.Options, + HorizontalAlignment = HorizontalAlignment.Stretch, + ItemTemplate = new FuncDataTemplate((option, _) => new TextBlock { Text = option?.Label }) + }; + combo.Bind(ComboBox.SelectedItemProperty, new Binding(nameof(field.Selected)) { Mode = BindingMode.TwoWay }); + row.Children.Add(combo); + break; + case PluginFieldKind.MultipleSelection: + foreach (PluginFieldOption option in descriptor.Options.IsDefault ? [] : descriptor.Options) + { + CheckBox choice = new() { Content = option.Label }; + choice.Bind(CheckBox.IsCheckedProperty, new Binding(nameof(field.SelectedIds)) + { + Source = field, + Mode = BindingMode.OneWay, + Converter = new FuncValueConverter, bool>( + ids => !ids.IsDefault && ids.Contains(option.Id)) + }); + choice.IsCheckedChanged += (_, _) => + { + bool selected = field.SelectedIds.Contains(option.Id); + if (choice.IsChecked == true && !selected) field.SelectedIds = field.SelectedIds.Add(option.Id); + else if (choice.IsChecked != true && selected) field.SelectedIds = field.SelectedIds.Remove(option.Id); + }; + row.Children.Add(choice); + } + break; + default: + TextBox text = new() { IsReadOnly = descriptor.Kind is PluginFieldKind.File or PluginFieldKind.Directory }; + text.Bind(TextBox.TextProperty, new Binding(nameof(field.Text)) { Mode = BindingMode.TwoWay }); + row.Children.Add(text); + if (text.IsReadOnly) + { + Button browse = new() { Command = field.BrowseCommand }; + browse.Bind(ContentControl.ContentProperty, browse.GetResourceObservable("Common.Browse")); + row.Children.Add(browse); + } + break; + } + TextBlock error = new() { TextWrapping = Avalonia.Media.TextWrapping.Wrap }; + error.Bind(TextBlock.TextProperty, new Binding(nameof(field.Error))); + error.Bind(TextBlock.ForegroundProperty, error.GetResourceObservable("Sem.Color.Error")); + row.Children.Add(error); + Children.Add(row); + } + } + } +} diff --git a/OpenUtauMobile/Controls/ProjectInfoEditPopup.axaml b/OpenUtauMobile/Controls/ProjectInfoEditPopup.axaml index 1379fde5..56d20bad 100644 --- a/OpenUtauMobile/Controls/ProjectInfoEditPopup.axaml +++ b/OpenUtauMobile/Controls/ProjectInfoEditPopup.axaml @@ -77,7 +77,7 @@ FontSize="22" FontWeight="Bold" TextAlignment="Center" - Watermark="{DynamicResource ProjectEdit.TempoWatermark}" /> + PlaceholderText="{DynamicResource ProjectEdit.TempoWatermark}" /> @@ -109,7 +109,7 @@ FontSize="26" FontWeight="Bold" TextAlignment="Center" - Watermark="4" /> + PlaceholderText="4" /> + PlaceholderText="4" /> - - - - - private sealed class Presentation(ToastMessage message) { + private readonly TaskCompletionSource _completed = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly long _startedAt = Stopwatch.GetTimestamp(); + + /// 当前展示持有的消息快照。 public ToastMessage Message { get; } = message; - public bool Handled { get; set; } + /// 到期、点击或关闭后不再归还消息。 + public bool Handled => _completed.Task.IsCompleted; + /// 无需轮询的用户处理信号。 + public Task Completion => _completed.Task; + /// 入场与驻留共用截止时间,后台延迟恢复不会重新开始完整驻留。 + public TimeSpan RemainingTime => MotionTokens.DurationMedium1 + TimeSpan.FromMilliseconds(Message.DurationMs) - + Stopwatch.GetElapsedTime(_startedAt); + + /// 点击、关闭和到期共用同一个完成信号。 + public void Complete() => _completed.TrySetResult(); } private readonly TranslateTransform _translate = new(0, 0); private CancellationTokenSource? _lifetime; private IDisposable? _shadowBinding; - private Window? _window; private Presentation? _current; - private bool _paused; - private bool _inactive; - private bool _modalOpening; - private bool _pressed; - private int _modalGeneration; - - /// 功能模态显示时暂停可见驻留并隐藏消息,保留未处理的内容。 - public bool IsPaused - { - get => _paused; - set - { - _paused = value; - RefreshVisibility(); - } - } /// 初始化共享按钮反馈与提示局部输入。 public ToastOverlay() { InitializeComponent(); ToastBorder.RenderTransform = _translate; - ToastActionButton.AddHandler(PointerPressedEvent, (_, _) => _pressed = true, RoutingStrategies.Tunnel, true); - ToastActionButton.AddHandler(PointerReleasedEvent, (_, _) => _pressed = false, RoutingStrategies.Tunnel, true); - ToastActionButton.PointerCaptureLost += (_, _) => _pressed = false; ToastActionButton.KeyDown += (_, e) => { if (e.Key != Key.Escape || _current == null) return; - _current.Handled = true; + _current.Complete(); RefreshVisibility(); e.Handled = true; }; @@ -74,34 +66,18 @@ protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) { base.OnAttachedToVisualTree(e); _lifetime = new CancellationTokenSource(); - _inactive = false; _shadowBinding = ToastBorder.GetResourceObservable("Sem.Value.Shadow").Subscribe(value => { if (value is Color color) ToastBorder.BoxShadow = ToastTokens.Elevation(color); }); - _window = TopLevel.GetTopLevel(this) as Window; - if (_window != null) - { - _window.Activated += WindowActivated; - _window.Deactivated += WindowDeactivated; - } - PopupService.Opening += ModalOpening; + ToastService.Register(ConsumeAsync); } protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e) { - PopupService.Opening -= ModalOpening; - if (_window != null) - { - _window.Activated -= WindowActivated; - _window.Deactivated -= WindowDeactivated; - } - _window = null; + ToastService.Unregister(); _shadowBinding?.Dispose(); _shadowBinding = null; - _modalGeneration++; - _modalOpening = false; - _pressed = false; _lifetime?.Cancel(); _lifetime?.Dispose(); _lifetime = null; @@ -110,48 +86,15 @@ protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e base.OnDetachedFromVisualTree(e); } - private void WindowActivated(object? sender, EventArgs e) - { - _inactive = false; - RefreshVisibility(); - } - - private void WindowDeactivated(object? sender, EventArgs e) - { - _inactive = true; - _pressed = false; - RefreshVisibility(); - } - - /// 宿主模态和局部暂停共同决定是否能展示及激活,避免按钮跨越模态。 - private bool IsBlocked => _paused || _inactive || _modalOpening || !IsEffectivelyVisible || - ServiceHub.DesktopWindowContext?.IsModalOpen == true || DialogHost.IsDialogOpen("MainDialogHost"); - + /// 提示只由自身展示会话控制,不依赖弹窗、告警中心或窗口激活状态。 private void RefreshVisibility() { if (ToastBorder == null) return; - bool visible = _lifetime != null && _current is { Handled: false } && !IsBlocked; + bool visible = _lifetime != null && _current is { Handled: false }; ToastBorder.IsVisible = visible; ToastBorder.IsHitTestVisible = visible && _current?.Message.Error != null; } - private async void ModalOpening() - { - _modalOpening = true; - RefreshVisibility(); - int generation = ++_modalGeneration; - CancellationToken token = _lifetime?.Token ?? new CancellationToken(true); - try - { - // Opening 先于实际 Show;之后以真实模态状态持续限制输入。 - await Task.Delay(100, token); - if (generation != _modalGeneration) return; - _modalOpening = false; - RefreshVisibility(); - } - catch (OperationCanceledException) { } - } - /// 顺序消费;卸载时归还未处理消息,重建宿主不会丢失错误详情。 public async Task ConsumeAsync() { @@ -162,7 +105,6 @@ public async Task ConsumeAsync() { while (true) { - while (IsBlocked) await Task.Delay(50, token); token.ThrowIfCancellationRequested(); ToastMessage? message = ToastService.Dequeue(); if (message == null) return; @@ -170,7 +112,7 @@ public async Task ConsumeAsync() if (message.Error == null && ServiceHub.DesktopWindowContext is { } context) { context.ShowMessage(message.Message, message.DurationMs); - owned.Handled = true; + owned.Complete(); owned = null; continue; } @@ -198,8 +140,10 @@ public async Task ConsumeAsync() _translate.Y = 0; ToastBorder.Opacity = 1; await Task.Delay(MotionTokens.DurationMedium1, token); - await WaitVisibleTimeAsync(owned, token); - owned.Handled = true; + token.ThrowIfCancellationRequested(); + await WaitForCompletionAsync(owned, token); + token.ThrowIfCancellationRequested(); + owned.Complete(); ToastBorder.IsHitTestVisible = false; ToastBorder.Transitions = new Transitions { @@ -212,6 +156,7 @@ public async Task ConsumeAsync() }; ToastBorder.Opacity = 0; await Task.Delay(MotionTokens.DurationExit, token); + token.ThrowIfCancellationRequested(); if (ReferenceEquals(_current, owned)) { _current = null; @@ -237,34 +182,29 @@ public async Task ConsumeAsync() } } - /// 仅累计可见驻留;错误消息被按住、悬停或聚焦时恢复完整阅读时间。 - private async Task WaitVisibleTimeAsync(Presentation presentation, CancellationToken token) + /// 只等待一次到期或用户处理信号,失焦、后台和其他浮层均不暂停计时。 + private static async Task WaitForCompletionAsync(Presentation presentation, CancellationToken token) { - double elapsed = 0; - Stopwatch clock = Stopwatch.StartNew(); double duration = presentation.Message.DurationMs; - while (!presentation.Handled && (duration <= 0 || elapsed < duration)) + if (duration <= 0) { - await Task.Delay(50, token); - double interval = clock.Elapsed.TotalMilliseconds; - clock.Restart(); - RefreshVisibility(); - if (IsBlocked) continue; - if (presentation.Message.Error != null && - (_pressed || ToastActionButton.IsPointerOver || ToastActionButton.IsKeyboardFocusWithin)) - elapsed = 0; - else elapsed += interval; + await presentation.Completion.WaitAsync(token); + return; } + TimeSpan remaining = presentation.RemainingTime; + if (remaining <= TimeSpan.Zero) return; + try { await presentation.Completion.WaitAsync(remaining, token); } + catch (TimeoutException) { } } /// 一次点击只处理当前错误快照,先停止命中,再打开既有错误弹窗。 private void OnToastClicked(object? sender, RoutedEventArgs e) { - if (IsBlocked || _current is not { Handled: false } current || current.Message.Error == null) return; - current.Handled = true; + if (_current is not { Handled: false } current || current.Message.Error == null) return; + current.Complete(); RefreshVisibility(); ErrorDialogService.Show(current.Message.Error); e.Handled = true; } } -} \ No newline at end of file +} diff --git a/OpenUtauMobile/Controls/TrackEditModeSwitcher.axaml b/OpenUtauMobile/Controls/TrackEditModeSwitcher.axaml index b84ad996..512e09b1 100644 --- a/OpenUtauMobile/Controls/TrackEditModeSwitcher.axaml +++ b/OpenUtauMobile/Controls/TrackEditModeSwitcher.axaml @@ -2,5 +2,5 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:c="clr-namespace:OpenUtauMobile.Controls" x:Class="OpenUtauMobile.Controls.TrackEditModeSwitcher"> - - \ No newline at end of file + + diff --git a/OpenUtauMobile/Controls/Warnings/WarningMotion.cs b/OpenUtauMobile/Controls/Warnings/WarningMotion.cs index 219f8221..7043ef50 100644 --- a/OpenUtauMobile/Controls/Warnings/WarningMotion.cs +++ b/OpenUtauMobile/Controls/Warnings/WarningMotion.cs @@ -21,22 +21,14 @@ public static Color MixColor(Color from, Color to, double progress) => Color.Fro (byte)Lerp(from.A, to.A, progress), (byte)Lerp(from.R, to.R, progress), (byte)Lerp(from.G, to.G, progress), (byte)Lerp(from.B, to.B, progress)); - /// 在界面上下文逐帧更新;顶部展示可传入前台时钟,在后台保留原动画进度。 - public static async Task Run(int milliseconds, Action frame, CancellationToken token, - Func? timestamp = null, Func? isPaused = null) + /// 按持续经过的时间更新动画,失焦和后台不暂停进度。 + public static async Task Run(int milliseconds, Action frame, CancellationToken token) { Stopwatch clock = Stopwatch.StartNew(); - double started = timestamp?.Invoke() ?? 0; while (true) { token.ThrowIfCancellationRequested(); - if (isPaused?.Invoke() == true) - { - await Task.Delay(32, token); - continue; - } - double elapsed = timestamp != null ? timestamp() - started : clock.Elapsed.TotalMilliseconds; - double progress = Math.Min(1, elapsed / milliseconds); + double progress = Math.Min(1, clock.Elapsed.TotalMilliseconds / milliseconds); frame(progress); if (progress >= 1) return; await Task.Delay(16, token); diff --git a/OpenUtauMobile/Controls/Warnings/WarningOverlay.Arrivals.cs b/OpenUtauMobile/Controls/Warnings/WarningOverlay.Arrivals.cs index 0c3fde0b..0cb18bbc 100644 --- a/OpenUtauMobile/Controls/Warnings/WarningOverlay.Arrivals.cs +++ b/OpenUtauMobile/Controls/Warnings/WarningOverlay.Arrivals.cs @@ -4,6 +4,7 @@ using Avalonia; using Avalonia.Automation; using Avalonia.Controls; +using Avalonia.Input; using Avalonia.Media; using OpenUtauMobile.Services.Warnings; using Serilog; @@ -12,9 +13,20 @@ namespace OpenUtauMobile.Controls.Warnings { public partial class WarningOverlay { + private const int ArrivalDwellDuration = 4000; + private long _arrivalDeadline; + + /// 点击当前顶部卡片后重新给予完整阅读时间,不重建展示或动画会话。 + private void ResetArrivalCountdown(object? sender, PointerPressedEventArgs e) + { + if (_arriving == null || !ArrivalCard.IsVisible || !ArrivalCard.IsHitTestVisible) return; + _arrivalDeadline = Environment.TickCount64 + ArrivalDwellDuration; + ArrivalCard.RemainingFraction = 1; + } + private void StartNextArrival() { - if (!_attached || !_presentationReady || PresentationSuspended || IsCenterOpen || HostModal || _arrivalAnimation != null || _arriving != null || _inbox == null || Bounds.Width < 1 || Bounds.Height < 1) return; + if (!_attached || !_presentationReady || IsCenterOpen || _arrivalAnimation != null || _arriving != null || _inbox == null || Bounds.Width < 1 || Bounds.Height < 1) return; foreach (WarningItem item in _inbox.Items) { if (item.Presented) continue; @@ -29,6 +41,8 @@ private async Task PresentArrivalAsync(WarningItem item) Cancel(ref _arrivalAnimation); CancellationTokenSource session = _arrivalAnimation = new(); CancellationToken token = session.Token; + const int enterDuration = 230; + _arrivalDeadline = Environment.TickCount64 + enterDuration + ArrivalDwellDuration; bool completed = false; try { @@ -41,31 +55,26 @@ private async Task PresentArrivalAsync(WarningItem item) ArrivalCard.RenderTransform = enter; AutomationProperties.SetLiveSetting(ArrivalCard, AutomationLiveSetting.Polite); AutomationProperties.SetName(ArrivalCard, item.Title); - await WarningMotion.Run(230, t => + await WarningMotion.Run(enterDuration, t => { ArrivalCard.Opacity = WarningMotion.Ease(t); enter.Y = -24 * (1 - WarningMotion.Ease(t)); - }, token, PresentationTimestamp, () => PresentationSuspended); + }, token); // 完成驻留和汇入后才算已展示,中断、宿主重建和布局变化不能吞掉提示。 // 同键内容更新不重建任务,不重置已经过去的驻留时间。 - double elapsed = 0; - const double dwellDuration = 4000; - double previousTime = PresentationTimestamp(); - while (elapsed < dwellDuration) + // 只有点击卡片才延长截止时间;焦点、后台及其他浮层不改变计时。 + while (true) { - await Task.Delay(16, token); - double now = PresentationTimestamp(); - double interval = now - previousTime; - previousTime = now; - if (PresentationSuspended) continue; - // 交互中断后必须重新获得完整阅读时间,边缘细线同时恢复全长。 - elapsed = _windowFocused && (ArrivalCard.IsPointerOver || ArrivalCard.IsKeyboardFocusWithin || _arrivalPressed) - ? 0 : Math.Min(dwellDuration, elapsed + interval); - ArrivalCard.RemainingFraction = 1 - elapsed / dwellDuration; + long remaining = _arrivalDeadline - Environment.TickCount64; + if (remaining <= 0) break; + await WarningMotion.Run((int)remaining, _ => ArrivalCard.RemainingFraction = + Math.Clamp((double)(_arrivalDeadline - Environment.TickCount64) / ArrivalDwellDuration, 0, 1), token); } - while (PresentationSuspended || _orbPointer != null || _dragging || _snapping) await Task.Delay(32, token); + token.ThrowIfCancellationRequested(); + ArrivalCard.RemainingFraction = 0; ArrivalCard.IsHitTestVisible = false; await MergeArrivalAsync(token); + token.ThrowIfCancellationRequested(); item.Presented = true; completed = true; _dockedVisible = true; @@ -104,55 +113,31 @@ private async Task MergeArrivalAsync(CancellationToken token) Flight.GlyphOpacity = 0; Flight.Dock = 0; Flight.Roundness = 0; - double previousTime = PresentationTimestamp(); - double progress = 0; - Point segmentFrom = from; - double segmentStart = 0; - bool paused = false; - while (progress < 1) + await WarningMotion.Run(600, t => { - await Task.Delay(16, token); - double now = PresentationTimestamp(); - double interval = now - previousTime; - previousTime = now; - if (PresentationSuspended || _orbPointer != null || _dragging || _snapping) - { - paused = true; - continue; - } - if (paused) - { - segmentFrom = new Point(Canvas.GetLeft(Flight), Canvas.GetTop(Flight)); - segmentStart = progress; - paused = false; - } - progress = Math.Min(1, progress + interval / 600); - double t = progress; // 已有球在飞行最后一段交给同一图标,避免长时间重叠两枚图标。 Orb.Opacity = 1 - Math.Clamp((t - 0.75) / 0.2, 0, 1); Orb.IsHitTestVisible = Orb.Opacity > 0.05; double position = WarningMotion.Ease(t); - double segmentProgress = WarningMotion.Ease((t - segmentStart) / Math.Max(0.001, 1 - segmentStart)); Point target = DockPoint(); Flight.Width = WarningMotion.Lerp(width, 56, position); Flight.Background = new SolidColorBrush(WarningMotion.MixColor(sourceColor, targetColor, position)); Flight.Foreground = new SolidColorBrush(WarningMotion.MixColor(sourceForeground, targetForeground, position)); Flight.Height = WarningMotion.Lerp(height, 56, position); - Canvas.SetLeft(Flight, WarningMotion.Lerp(segmentFrom.X, target.X, segmentProgress)); - Canvas.SetTop(Flight, WarningMotion.Lerp(segmentFrom.Y, target.Y, segmentProgress)); + Canvas.SetLeft(Flight, WarningMotion.Lerp(from.X, target.X, position)); + Canvas.SetTop(Flight, WarningMotion.Lerp(from.Y, target.Y, position)); Flight.Roundness = Math.Min(1, t * 2); Flight.Dock = (_right ? 1 : -1) * WarningMotion.Ease(Math.Clamp((t - 0.72) / 0.28, 0, 1)); Flight.GlyphOpacity = Math.Clamp((t - 0.15) / 0.25, 0, 1); Flight.Opacity = Math.Min(1, t / 0.18); ArrivalCard.Opacity = 1 - Math.Min(1, t / 0.18); - } + }, token); } private void StopArrival() { Cancel(ref _arrivalAnimation); _arriving = null; - _arrivalPressed = false; ArrivalCard.IsVisible = false; ArrivalCard.RemainingFraction = 1; ArrivalCard.IsHitTestVisible = true; diff --git a/OpenUtauMobile/Controls/Warnings/WarningOverlay.axaml.cs b/OpenUtauMobile/Controls/Warnings/WarningOverlay.axaml.cs index d06b7930..246191b5 100644 --- a/OpenUtauMobile/Controls/Warnings/WarningOverlay.axaml.cs +++ b/OpenUtauMobile/Controls/Warnings/WarningOverlay.axaml.cs @@ -1,14 +1,11 @@ using System; -using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Avalonia; using Avalonia.Automation; using Avalonia.Controls; -using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Controls.Platform; using Avalonia.Input; using Avalonia.Interactivity; @@ -17,10 +14,8 @@ using Avalonia.Platform; using Avalonia.Threading; using Avalonia.VisualTree; -using DialogHostAvalonia; using OpenUtau.Core.Util; using OpenUtauMobile.Helpers; -using OpenUtauMobile.Services.Dialogs; using OpenUtauMobile.Services.Warnings; using Serilog; using SkiaSharp; @@ -31,12 +26,9 @@ namespace OpenUtauMobile.Controls.Warnings public partial class WarningOverlay : UserControl { private readonly ObservableCollection _centerItems = []; - private readonly Stopwatch _presentationClock = new(); private WarningInbox? _inbox; private TopLevel? _top; private IInsetsManager? _insets; - private Window? _window; - private IActivatableLifetime? _activation; private ContentControl? _page; private CancellationTokenSource? _arrivalAnimation; private CancellationTokenSource? _orbAnimation; @@ -49,16 +41,11 @@ public partial class WarningOverlay : UserControl private Point _pressOrigin; private Point _orbPosition; private bool _dragging; - private bool _snapping; private bool _dockedVisible; private bool _right = true; private double _yRatio = 0.6; private bool _closing; private bool _clearing; - private bool _windowFocused = true; - private bool _applicationInBackground; - private bool _modalBlocked; - private bool _arrivalPressed; private bool _attached; private bool _presentationReady = true; private InputElement? _previousFocus; @@ -74,8 +61,6 @@ public partial class WarningOverlay : UserControl private double _elasticVelocity; private long _elasticLastInput; private bool _resourceRefreshQueued; - private int _modalGeneration; - private readonly HashSet _modalKeys = []; private Rect _lastUsable; /// 包含开场、关闭与清除动画在内的完整模态会话。 @@ -93,9 +78,10 @@ public WarningOverlay() ArrivalCard.ShowCountdown = true; ArrivalCard.Ignore += IgnoreArrival; ArrivalCard.CloseRequested += CloseArrival; - ArrivalCard.AddHandler(PointerPressedEvent, (_, _) => _arrivalPressed = true, RoutingStrategies.Tunnel, true); - ArrivalCard.AddHandler(PointerReleasedEvent, (_, _) => _arrivalPressed = false, RoutingStrategies.Tunnel, true); - ArrivalCard.PointerCaptureLost += (_, _) => _arrivalPressed = false; + ArrivalCard.AddHandler(PointerPressedEvent, ResetArrivalCountdown, RoutingStrategies.Tunnel, true); + // 键盘处理只作用于中心自身,不拦截上层弹窗或提示的输入。 + Center.AddHandler(KeyDownEvent, CenterKeyDown, RoutingStrategies.Bubble, true); + Center.AddHandler(KeyUpEvent, CenterKeyUp, RoutingStrategies.Bubble, true); Orb.AddHandler(PointerPressedEvent, OrbPressed, RoutingStrategies.Tunnel); Orb.AddHandler(PointerMovedEvent, OrbMoved, RoutingStrategies.Tunnel); Orb.AddHandler(PointerReleasedEvent, OrbReleased, RoutingStrategies.Tunnel); @@ -131,26 +117,8 @@ protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) _attached = true; AttachCardAppearance(); _top = TopLevel.GetTopLevel(this); - _window = _top as Window; - _activation = Application.Current?.TryGetFeature(typeof(IActivatableLifetime)) as IActivatableLifetime; - if (_activation != null) - { - _activation.Activated += ApplicationActivated; - _activation.Deactivated += ApplicationDeactivated; - } _insets = _top?.InsetsManager; if (_insets != null) _insets.SafeAreaChanged += SafeAreaChanged; - if (_window != null) - { - _window.Deactivated += WindowDeactivated; - _window.Activated += WindowActivated; - _window.PropertyChanged += WindowPropertyChanged; - } - if (!PresentationSuspended) _presentationClock.Start(); - _top?.AddHandler(KeyDownEvent, PreviewKey, RoutingStrategies.Tunnel, true); - _top?.AddHandler(KeyUpEvent, PreviewKeyUp, RoutingStrategies.Tunnel, true); - _top?.AddHandler(GotFocusEvent, ConstrainFocus, RoutingStrategies.Bubble, true); - PopupService.Opening += ExternalModalOpening; if (Application.Current != null) Application.Current.ResourcesChanged += OnResourcesChanged; _right = Preferences.Default.WarningOrbDockSide != 0; _yRatio = double.IsFinite(Preferences.Default.WarningOrbDockYRatio) @@ -168,29 +136,9 @@ protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e _attached = false; _clearShadowSubscription?.Dispose(); _clearShadowSubscription = null; - _modalGeneration++; - _modalBlocked = false; - _modalKeys.Clear(); if (_inbox != null) _inbox.Changed -= InboxChanged; - PopupService.Opening -= ExternalModalOpening; if (Application.Current != null) Application.Current.ResourcesChanged -= OnResourcesChanged; if (_insets != null) _insets.SafeAreaChanged -= SafeAreaChanged; - if (_activation != null) - { - _activation.Activated -= ApplicationActivated; - _activation.Deactivated -= ApplicationDeactivated; - _activation = null; - } - if (_window != null) - { - _window.Deactivated -= WindowDeactivated; - _window.Activated -= WindowActivated; - _window.PropertyChanged -= WindowPropertyChanged; - } - _presentationClock.Stop(); - _top?.RemoveHandler(KeyDownEvent, PreviewKey); - _top?.RemoveHandler(KeyUpEvent, PreviewKeyUp); - _top?.RemoveHandler(GotFocusEvent, ConstrainFocus); StopArrival(); CancelOrb(); FinishCenter(false); @@ -206,15 +154,8 @@ private static void Cancel(ref CancellationTokenSource? source) old?.Dispose(); } - private bool HostModal => _modalBlocked || DialogHost.IsDialogOpen("MainDialogHost"); private bool HasWarnings => _inbox?.Items.Count > 0; - /// 失去输入焦点不影响展示;真正进入后台或最小化才暂停前台时钟。 - private bool PresentationSuspended => _applicationInBackground || _window?.WindowState == WindowState.Minimized; - - /// 所有顶部动画共用前台时间,避免恢复时计入后台经过的时间或重建会话。 - private double PresentationTimestamp() => _presentationClock.Elapsed.TotalMilliseconds; - private void InboxChanged() { if (!_attached || _inbox == null) return; @@ -244,7 +185,6 @@ private void InboxChanged() private void UpdateOrb() { Orb.IsVisible = _presentationReady && HasWarnings && _dockedVisible && !IsCenterOpen; - Orb.IsEnabled = !HostModal && !PresentationSuspended; AutomationProperties.SetName(Orb, string.Format(LocalizationManager.Get("Warning.OrbName"), _inbox?.Items.Count ?? 0)); } @@ -279,11 +219,10 @@ private void PlaceOrb(Point point) /// 只有在球内开始的主指针可以建立拖动会话。 private void OrbPressed(object? sender, PointerPressedEventArgs e) { - if (_orbPointer != null || HostModal || PresentationSuspended || IsCenterOpen || + if (_orbPointer != null || IsCenterOpen || (e.Pointer.Type != PointerType.Touch && !e.GetCurrentPoint(Orb).Properties.IsLeftButtonPressed)) return; e.PreventGestureRecognition(); Cancel(ref _orbAnimation); - _snapping = false; _orbPointer = e.Pointer; Orb.IsPointerHeld = true; _pressPoint = e.GetPosition(this); @@ -339,7 +278,6 @@ private async Task SnapAsync(bool save) Point from = _orbPosition; double dockFrom = Orb.Dock; Point target = DockPoint(); - _snapping = true; try { await WarningMotion.Run(420, t => @@ -361,7 +299,6 @@ await WarningMotion.Run(420, t => { if (_orbAnimation == session) { - _snapping = false; Cancel(ref _orbAnimation); } } @@ -374,7 +311,7 @@ private void CancelOrb() _orbPointer = null; Orb.IsPointerHeld = false; pointer?.Capture(null); - _dragging = _snapping = false; + _dragging = false; PlaceOrb(DockPoint()); Orb.Dock = _right ? 1 : -1; } @@ -391,7 +328,7 @@ public bool RequestBack() private void OpenCenter() { - if (!_presentationReady || !HasWarnings || IsCenterOpen || HostModal || PresentationSuspended || _page == null || _inbox == null) return; + if (!_presentationReady || !HasWarnings || IsCenterOpen || _page == null || _inbox == null) return; WarningInbox.BeginCenter(); _previousFocus = _top?.FocusManager?.GetFocusedElement() as InputElement; CancelOrb(); @@ -505,6 +442,7 @@ private void FinishCenter(bool restoreFocus) ResetElastic(); CancelCardInteractions(); bool wasOpen = IsCenterOpen; + bool ownedFocus = IsKeyboardFocusWithin; Center.IsVisible = false; Center.Opacity = 1; CenterContent.IsEnabled = true; @@ -521,7 +459,7 @@ private void FinishCenter(bool restoreFocus) { if (_page != null) _page.IsEnabled = _pageWasEnabled; CenterVisibilityChanged?.Invoke(false); - if (restoreFocus && _previousFocus is { IsEffectivelyEnabled: true, IsEffectivelyVisible: true } previous && + if (restoreFocus && ownedFocus && _previousFocus is { IsEffectivelyEnabled: true, IsEffectivelyVisible: true } previous && TopLevel.GetTopLevel(previous) == _top) previous.Focus(); } _previousFocus = null; @@ -577,54 +515,15 @@ private Control[] VisibleContainers() => WarningItems.GetRealizedContainers().Wh private double CardY(Control card) => card.TranslatePoint(default, WarningItems)?.Y ?? 0; - private void ExternalModalOpening() + /// 中心只处理从自身内容冒泡的按键,保留上层浮层独立的焦点与返回行为。 + private void CenterKeyDown(object? sender, KeyEventArgs e) { - _modalBlocked = true; - StopArrival(); - CancelOrb(); - if (IsCenterOpen) FinishCenter(true); - UpdateOrb(); - _ = WaitForModalAsync(++_modalGeneration); - } - - private async Task WaitForModalAsync(int generation) - { - // Opening 在 DialogHost.Show 之前发出,至少让出一轮以免过早恢复。 - await Task.Delay(100); - while (_attached && generation == _modalGeneration && DialogHost.IsDialogOpen("MainDialogHost")) await Task.Delay(100); - if (!_attached || generation != _modalGeneration) return; - _modalBlocked = false; - UpdateOrb(); - StartNextArrival(); - } - - private void PreviewKey(object? sender, KeyEventArgs e) - { - if (!IsCenterOpen && _modalKeys.Contains(e.Key)) { e.Handled = true; return; } - if (!IsCenterOpen || HostModal) return; - _modalKeys.Add(e.Key); - if (e.Key == Key.Escape) - { - RequestBack(); - e.Handled = true; - } - else if (_clearing || _closing || e.Source is not Visual source || - !source.GetSelfAndVisualAncestors().Contains(Center)) e.Handled = true; - } - - private void PreviewKeyUp(object? sender, KeyEventArgs e) - { - bool fromModal = _modalKeys.Remove(e.Key); - if (!IsCenterOpen && fromModal) { e.Handled = true; return; } - if (IsCenterOpen && !HostModal && (_clearing || _closing || e.Source is not Visual source || - !source.GetSelfAndVisualAncestors().Contains(Center))) e.Handled = true; + if (e.Key == Key.Escape && !e.Handled) RequestBack(); + e.Handled = true; } - private void ConstrainFocus(object? sender, FocusChangedEventArgs e) - { - if (IsCenterOpen && !HostModal && e.Source is Visual source && - !source.GetSelfAndVisualAncestors().Contains(Center)) CloseButton.Focus(); - } + /// 中心内的按键释放不继续触发导航页快捷键。 + private void CenterKeyUp(object? sender, KeyEventArgs e) => e.Handled = true; private void SafeAreaChanged(object? sender, SafeAreaChangedArgs e) => ViewportChanged(); @@ -678,58 +577,5 @@ private void QueueViewportRefresh() if (_attached) ViewportChanged(); }, DispatcherPriority.Background); } - - private void WindowDeactivated(object? sender, EventArgs e) - { - _windowFocused = false; - CancelInputGestures(); - } - - /// 激活变化只终止输入手势,不关闭卡片、不改已展示标记,也不重置展示时钟。 - private void CancelInputGestures() - { - _modalKeys.Clear(); - CancelOrb(); - _arrivalPressed = false; - ResetElastic(); - CancelCardInteractions(); - } - - private void WindowActivated(object? sender, EventArgs e) - { - _windowFocused = true; - } - - private void WindowPropertyChanged(object? sender, AvaloniaPropertyChangedEventArgs e) - { - if (e.Property != Window.WindowStateProperty) return; - UpdatePresentationState(); - } - - /// 后台与最小化共用暂停门禁,已开始的展示保留原卡片、剩余时间及动画进度。 - private void UpdatePresentationState() - { - if (PresentationSuspended) - { - _presentationClock.Stop(); - CancelInputGestures(); - } - else _presentationClock.Start(); - UpdateOrb(); - StartNextArrival(); - } - - private void ApplicationDeactivated(object? sender, ActivatedEventArgs e) - { - if (e.Kind != ActivationKind.Background) return; - _applicationInBackground = true; - UpdatePresentationState(); - } - - private void ApplicationActivated(object? sender, ActivatedEventArgs e) - { - _applicationInBackground = false; - UpdatePresentationState(); - } } } diff --git a/OpenUtauMobile/OpenUtauMobile.csproj b/OpenUtauMobile/OpenUtauMobile.csproj index 7c446f2a..e9a80fc4 100644 --- a/OpenUtauMobile/OpenUtauMobile.csproj +++ b/OpenUtauMobile/OpenUtauMobile.csproj @@ -1,6 +1,6 @@ - net10.0 + net10.0;net10.0-windows enable preview true @@ -28,6 +28,7 @@ + @@ -45,5 +46,6 @@ + diff --git a/OpenUtauMobile/Services/AppService.cs b/OpenUtauMobile/Services/AppService.cs index 3c67e88f..34a9b860 100644 --- a/OpenUtauMobile/Services/AppService.cs +++ b/OpenUtauMobile/Services/AppService.cs @@ -1,5 +1,11 @@ using System; +using System.Threading.Tasks; using Avalonia.Controls; +using OpenUtauMobile.Services.Projects; +using Serilog; +using OpenUtau.Core; +using OpenUtau.Core.Pipeline; +using OpenUtau.Core.Ustx; namespace OpenUtauMobile.Services; @@ -39,11 +45,11 @@ public static bool ExitApplication() desktopLifetime.Shutdown(); return true; case Avalonia.Controls.ApplicationLifetimes.IActivityApplicationLifetime: - Environment.Exit(0); + _ = FlushAndExitAsync(); return true; case Avalonia.Controls.ApplicationLifetimes.ISingleViewApplicationLifetime when !OperatingSystem.IsBrowser(): - Environment.Exit(0); + _ = FlushAndExitAsync(); return true; case Avalonia.Controls.ApplicationLifetimes.ISingleViewApplicationLifetime: return false; // 在浏览器环境中,无法直接退出应用 @@ -51,4 +57,22 @@ public static bool ExitApplication() return false; } } -} \ No newline at end of file + + /// 退出前异步刷新合并的偏好请求,主线程继续处理平台输入。 + private static async Task FlushAndExitAsync() + { + UProject project = DocManager.Inst.Project; + DocRevision revision = DocManager.Inst.Revision; + try { await PreferencesWriter.Inst.FlushAsync(); } + catch (Exception error) { Log.Error(error, "退出时刷新偏好失败"); } + if (!ReferenceEquals(project, DocManager.Inst.Project) || revision != DocManager.Inst.Revision) return; + if (ServiceHub.PlatformExitApplication is { } exitApplication) + { + exitApplication(); + } + else if (!OperatingSystem.IsAndroid()) + { + Environment.Exit(0); + } + } +} diff --git a/OpenUtauMobile/Services/BitmapLoader.cs b/OpenUtauMobile/Services/BitmapLoader.cs new file mode 100644 index 00000000..5b3b16ba --- /dev/null +++ b/OpenUtauMobile/Services/BitmapLoader.cs @@ -0,0 +1,31 @@ +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Avalonia.Media.Imaging; + +namespace OpenUtauMobile.Services; + +/// 在后台解码独立图片数据,限制并行数以控制移动设备的内存峰值。 +internal static class BitmapLoader +{ + private static readonly SemaphoreSlim DecodeSlots = new(2, 2); + + /// 字节数据在解码期间保持只读;调用方拥有返回图片并负责释放晚到结果。 + public static async Task DecodeAsync(byte[] data, CancellationToken cancellationToken = default) + { + await DecodeSlots.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + return await Task.Run(() => + { + cancellationToken.ThrowIfCancellationRequested(); + using MemoryStream stream = new(data); + return new Bitmap(stream); + }, cancellationToken).ConfigureAwait(false); + } + finally + { + DecodeSlots.Release(); + } + } +} diff --git a/OpenUtauMobile/Services/BuiltinSingerInstallTransaction.cs b/OpenUtauMobile/Services/BuiltinSingerInstallTransaction.cs new file mode 100644 index 00000000..071f7d1b --- /dev/null +++ b/OpenUtauMobile/Services/BuiltinSingerInstallTransaction.cs @@ -0,0 +1,252 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using OpenUtau.Classic; +using OpenUtau.Core; +using OpenUtauMobile.Helpers; +using OpenUtauMobile.Services.SingerPlugins; + +namespace OpenUtauMobile.Services +{ + /// 内置安装的临时解包和可撤销发布;不改变上游归档布局与配置生成规则。 + internal sealed class BuiltinSingerInstallTransaction + { + private readonly string id = Guid.NewGuid().ToString("N"); + private readonly string workspace; + private readonly string payload; + private readonly string targetRoot; + private readonly List changes = []; + private readonly List createdDirectories = []; + private readonly List temporaryFiles = []; + private readonly IProgress<(double Percent, string Message)> progress; + private bool preserveWorkspace; + + /// 仅记录本会话已经替换的文件,原件只用于安装取消或失败时恢复。 + private sealed record FileChange(string Path, string? Original, FileAttributes Attributes, DateTime LastWriteTime) + { + public bool Applied { get; set; } + } + + internal BuiltinSingerInstallTransaction(IProgress<(double Percent, string Message)> progress) + { + this.progress = progress; + workspace = Path.GetFullPath(Path.Combine(PathManager.Inst.CachePath, "BuiltinSingerInstall", id)); + payload = Path.Combine(workspace, "payload"); + targetRoot = Path.GetFullPath(PathManager.Inst.SingersInstallPath); + } + + /// 解包期间不写歌手目录;发布与回滚均阻止并发扫描看到中间结果。 + internal async Task RunAsync(BuiltinSingerInstaller installer, string source, string singerType, + Encoding archiveEncoding, Encoding textEncoding, CancellationToken token) + { + try + { + Directory.CreateDirectory(payload); + if (installer.IsArchive) + { + await Task.Run(() => + { + bool first = true; + new VoicebankInstaller(payload, (percent, message) => + { + token.ThrowIfCancellationRequested(); + if (!first) Resolve(payload, message.Replace('\\', '/')); + first = false; + progress.Report((percent * 0.7, message)); + }, archiveEncoding, textEncoding).Install(source, singerType); + token.ThrowIfCancellationRequested(); + }, token); + } + else if (installer.Id == "builtin:vogen") + { + await CopyAsync(source, Path.Combine(payload, Path.GetFileName(source)), token); + } + else + { + throw new InvalidOperationException("未知的内置安装器。"); + } + token.ThrowIfCancellationRequested(); + await SingerDiscoveryService.Instance.WithCatalogLockAsync(async () => + { + try + { + await PublishAsync(installer.IsArchive, token); + token.ThrowIfCancellationRequested(); + await ServiceHub.FlushFileSystemAsync(); + token.ThrowIfCancellationRequested(); + } + catch (Exception failure) + { + try + { + await RollbackAsync(); + } + catch (Exception rollbackFailure) + { + // 保留仍可能含原件的会话,避免回滚失败后销毁恢复资料。 + preserveWorkspace = true; + throw new AggregateException($"{L.S("SingerSetup.RollbackFailed")}\n{workspace}", failure, rollbackFailure); + } + throw; + } + return true; + }, token); + } + finally + { + foreach (string path in temporaryFiles) + { + if (File.Exists(path)) File.Delete(path); + } + string cacheRoot = Path.GetFullPath(Path.Combine(PathManager.Inst.CachePath, "BuiltinSingerInstall")); + if (!preserveWorkspace && Directory.Exists(workspace)) + { + if (!string.Equals(Resolve(cacheRoot, id), workspace, PathComparison)) throw new IOException("临时目录超出会话范围。"); + List cachedFiles = []; + List cachedDirectories = []; + Collect(workspace, cachedFiles, cachedDirectories, CancellationToken.None); + foreach (string file in cachedFiles) File.SetAttributes(file, File.GetAttributes(file) & ~FileAttributes.ReadOnly); + Directory.Delete(workspace, true); + } + } + } + + /// 逐项合并到原目录,保留上游覆盖已有文件而不删除无关文件的行为。 + private async Task PublishAsync(bool overwrite, CancellationToken token) + { + List files = []; + List directories = []; + Collect(payload, files, directories, token); + foreach (string directory in directories) + { + token.ThrowIfCancellationRequested(); + EnsureDirectory(Resolve(targetRoot, Path.GetRelativePath(payload, directory))); + } + for (int index = 0; index < files.Count; index++) + { + token.ThrowIfCancellationRequested(); + string source = files[index]; + string relative = Path.GetRelativePath(payload, source); + string destination = Resolve(targetRoot, relative); + EnsureDirectory(Path.GetDirectoryName(destination)!); + if (Directory.Exists(destination) || !overwrite && File.Exists(destination)) + throw new IOException($"{L.S("SingerSetup.TargetExists")} {destination}"); + string? original = null; + FileAttributes attributes = FileAttributes.Normal; + DateTime lastWriteTime = default; + if (File.Exists(destination)) + { + original = Path.Combine(workspace, "originals", index.ToString()); + Directory.CreateDirectory(Path.GetDirectoryName(original)!); + attributes = File.GetAttributes(destination); + lastWriteTime = File.GetLastWriteTimeUtc(destination); + await CopyAsync(destination, original, token); + } + FileChange change = new(destination, original, attributes, lastWriteTime); + changes.Add(change); + string temporary = Path.Combine(Path.GetDirectoryName(destination)!, $".opum-install-{id}-{index}.tmp"); + temporaryFiles.Add(temporary); + await CopyAsync(source, temporary, token); + token.ThrowIfCancellationRequested(); + File.Move(temporary, destination, overwrite); + change.Applied = true; + File.SetLastWriteTimeUtc(destination, File.GetLastWriteTimeUtc(source)); + File.SetAttributes(destination, File.GetAttributes(source)); + progress.Report((70 + ((index + 1) * 30d / Math.Max(1, files.Count)), relative)); + } + } + + /// 回滚不使用已经取消的令牌,并继续尝试恢复其余文件;全部恢复后才能报告已取消。 + private async Task RollbackAsync() + { + progress.Report((-1, L.S("SingerSetup.RollingBack"))); + List failures = []; + foreach (FileChange change in changes.AsEnumerable().Reverse()) + { + if (!change.Applied) continue; + try + { + if (File.Exists(change.Path)) File.SetAttributes(change.Path, File.GetAttributes(change.Path) & ~FileAttributes.ReadOnly); + if (change.Original == null) + { + File.Delete(change.Path); + } + else + { + string temporary = Path.Combine(Path.GetDirectoryName(change.Path)!, $".opum-restore-{id}.tmp"); + temporaryFiles.Add(temporary); + await CopyAsync(change.Original, temporary, CancellationToken.None); + File.Move(temporary, change.Path, true); + File.SetLastWriteTimeUtc(change.Path, change.LastWriteTime); + File.SetAttributes(change.Path, change.Attributes); + } + } + catch (Exception exception) { failures.Add(exception); } + } + // 临时发布文件也必须先移除,之后才能移除本会话创建的空目录。 + foreach (string temporary in temporaryFiles) + { + try { if (File.Exists(temporary)) File.Delete(temporary); } + catch (Exception exception) { failures.Add(exception); } + } + foreach (string directory in createdDirectories.AsEnumerable().Reverse()) + { + try + { + if (Directory.Exists(directory)) Directory.Delete(directory, false); + } + catch (Exception exception) { failures.Add(exception); } + } + if (failures.Count > 0) throw new AggregateException(failures); + await ServiceHub.FlushFileSystemAsync(); + } + + /// 按父子顺序登记新目录,回滚仅删除本会话创建的空目录。 + private void EnsureDirectory(string path) + { + if (Directory.Exists(path)) return; + if (!string.Equals(path, targetRoot, PathComparison)) EnsureDirectory(Path.GetDirectoryName(path)!); + Directory.CreateDirectory(path); + createdDirectories.Add(path); + } + + /// 递归收集会话文件和目录,支持取消。 + private static void Collect(string root, List files, List directories, CancellationToken token) + { + foreach (string path in Directory.EnumerateFileSystemEntries(root)) + { + token.ThrowIfCancellationRequested(); + if (Directory.Exists(path)) + { + directories.Add(path); + Collect(path, files, directories, token); + } + else files.Add(path); + } + } + + /// 限定所有发布和归档条目在对应根目录内。 + private static string Resolve(string root, string relative) + { + if (Path.IsPathRooted(relative) || relative.Contains(':')) throw new IOException("安装路径超出允许范围。"); + string path = Path.GetFullPath(Path.Combine(root, relative)); + string prefix = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)) + Path.DirectorySeparatorChar; + if (!path.StartsWith(prefix, PathComparison)) throw new IOException("安装路径超出允许范围。"); + return path; + } + + private static StringComparison PathComparison => OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + + /// 异步复制支持在大文件中途取消,失败的临时文件由会话收尾清理。 + private static async Task CopyAsync(string source, string destination, CancellationToken token) + { + await using FileStream input = new(source, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, true); + await using FileStream output = new(destination, FileMode.CreateNew, FileAccess.Write, FileShare.None, 81920, true); + await input.CopyToAsync(output, token); + } + } +} diff --git a/OpenUtauMobile/Services/BuiltinSingerInstallers.cs b/OpenUtauMobile/Services/BuiltinSingerInstallers.cs new file mode 100644 index 00000000..9697c2dd --- /dev/null +++ b/OpenUtauMobile/Services/BuiltinSingerInstallers.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Immutable; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace OpenUtauMobile.Services +{ + /// 宿主明确支持的内置安装入口,不进入插件安装注册表。 + public sealed record BuiltinSingerInstaller(string Id, string DisplayName, string? SingerType, + ImmutableArray Extensions) + { + /// Vogen 使用单文件安装,其余入口使用编码向导。 + public bool IsArchive => SingerType != null; + } + + /// 内置归档复用上游安装器;单文件安装遵循桌面的复制与冲突规则。 + public static class BuiltinSingerInstallers + { + /// 内置入口独立于插件注册、排序和生命周期。 + public static ImmutableArray All => + [ + new("builtin:utau", "UTAU", "utau", [".zip", ".rar", ".uar"]), + new("builtin:diffsinger", "DiffSinger", "diffsinger", [".zip", ".rar", ".uar"]), + new("builtin:enunu", "ENUNU", "enunu", [".zip", ".rar", ".uar"]), + new("builtin:vogen", "Vogen", null, [".vogeon"]), + new("builtin:neutrino", "NEUTRINO", "neutrino", [".zip", ".rar", ".uar"]), + ]; + + /// 沿用桌面解包规则,通过会话暂存与文件变更记录提供取消和回滚。 + public static async Task InstallAsync(BuiltinSingerInstaller installer, string source, + string singerType, Encoding archiveEncoding, Encoding textEncoding, + IProgress<(double Percent, string Message)> progress, CancellationToken cancellationToken = default) + { + BuiltinSingerInstallTransaction transaction = new(progress); + await Task.Run(() => transaction.RunAsync(installer, source, singerType, archiveEncoding, textEncoding, cancellationToken), cancellationToken); + } + } +} diff --git a/OpenUtauMobile/Services/Dialogs/LoadingPopupService.cs b/OpenUtauMobile/Services/Dialogs/LoadingPopupService.cs index 2da3b5b8..bdd209bd 100644 --- a/OpenUtauMobile/Services/Dialogs/LoadingPopupService.cs +++ b/OpenUtauMobile/Services/Dialogs/LoadingPopupService.cs @@ -88,6 +88,8 @@ await Dispatcher.UIThread.InvokeAsync( try { + if (popupTask.IsCompleted) + throw new InvalidOperationException("Loading dialog closed before the operation started."); await operation(viewModel); } finally diff --git a/OpenUtauMobile/Services/Dialogs/SingerDeletePopupService.cs b/OpenUtauMobile/Services/Dialogs/SingerDeletePopupService.cs new file mode 100644 index 00000000..d2dcc1f7 --- /dev/null +++ b/OpenUtauMobile/Services/Dialogs/SingerDeletePopupService.cs @@ -0,0 +1,45 @@ +using System; +using System.Threading.Tasks; +using OpenUtau.Core; +using OpenUtau.Core.Ustx; +using OpenUtauMobile.Helpers; +using OpenUtauMobile.Services.SingerPlugins; +using OpenUtauMobile.ViewModels; +using Serilog; + +namespace OpenUtauMobile.Services.Dialogs; + +/// 内置和插件歌手共用卸载确认、加载弹窗和结果提示。 +public static class SingerDeletePopupService +{ + /// 按歌手归属选择后端,提供方缺失时不能回退到内置递归卸载。 + public static Task ShowAsync(USinger singer) => ShowAsync(singer.LocalizedName, () => + BuiltinSingerMaintenance.CanUninstall(singer) ? BuiltinSingerMaintenance.UninstallAsync(singer) + : SingerDeletionService.DeleteAsync(SingerDeletionService.Find(singer) + ?? throw new InvalidOperationException("歌手条目已改变,请刷新列表。"))); + + /// 没有可用歌手实例的候选也沿用同一卸载交互。 + public static Task ShowAsync(SingerCandidate candidate) => + ShowAsync(candidate.Entry.DisplayName, () => SingerDeletionService.DeleteAsync(candidate)); + + private static async Task ShowAsync(string name, Func uninstall) + { + string? choice = await OptionConfirmPopupService.ShowAsync(L.S("SingerDetail.UninstallConfirmTitle"), + string.Format(L.S("SingerDetail.UninstallConfirmMessage"), name), + [new OptionConfirmOption(L.S("Common.Cancel"), "cancel", isDefault: true), new(L.S("Common.Uninstall"), "uninstall", isDestructive: true)]); + if (choice != "uninstall") return false; + try + { + await LoadingPopupService.RunAsync(L.S("SingerDetail.Uninstalling"), _ => uninstall()); + ToastService.Enqueue(string.Format(L.S("SingerDetail.UninstallSucceeded"), name)); + return true; + } + catch (Exception exception) + { + Log.Error(exception, "Failed to uninstall singer {Singer}", name); + ErrorDialogService.Show(new ErrorDialogViewModel(new ErrorMessageNotification( + string.Format(L.S("SingerDetail.UninstallFailed"), name), exception))); + return false; + } + } +} diff --git a/OpenUtauMobile/Services/Dialogs/ToastService.cs b/OpenUtauMobile/Services/Dialogs/ToastService.cs index 6c4a297b..3473fd34 100644 --- a/OpenUtauMobile/Services/Dialogs/ToastService.cs +++ b/OpenUtauMobile/Services/Dialogs/ToastService.cs @@ -3,6 +3,7 @@ using System.Threading.Tasks; using Avalonia.Threading; using OpenUtauMobile.ViewModels; +using Serilog; namespace OpenUtauMobile.Services.Dialogs { @@ -105,10 +106,13 @@ private static void TryStartConsuming() { if (registration != _registration) return; } + bool completed = false; try { await consume(); + completed = true; } + catch (Exception exception) { Log.Error(exception, "提示浮层消费失败"); } finally { lock (Gate) @@ -116,11 +120,11 @@ private static void TryStartConsuming() if (registration == _registration) { _running = false; - TryStartConsuming(); + if (completed) TryStartConsuming(); } } } }); } } -} \ No newline at end of file +} diff --git a/OpenUtauMobile/Services/DocumentValidationScheduler.cs b/OpenUtauMobile/Services/DocumentValidationScheduler.cs new file mode 100644 index 00000000..9d56bacc --- /dev/null +++ b/OpenUtauMobile/Services/DocumentValidationScheduler.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using Avalonia.Controls; +using Avalonia.Threading; +using OpenUtau.Core; + +namespace OpenUtauMobile.Services; + +/// 把文档校验合并到下一动画帧,并在停止出帧或宿主卸载时完成待处理校验。 +internal sealed class DocumentValidationScheduler : IDisposable +{ + private readonly TopLevel _topLevel; + private readonly Action _requestFrame; + private readonly HashSet _pendingActions = []; + private readonly DispatcherTimer _fallbackTimer; + private int _generation; + private bool _isDisposed; + + /// 在 UI 线程为当前主视图接入 Core 已有的帧调度接口。 + public DocumentValidationScheduler(TopLevel topLevel) + { + Dispatcher.UIThread.VerifyAccess(); + _topLevel = topLevel; + _requestFrame = RequestFrame; + // 窗口隐藏或 Android 暂停出帧时也不能无限推迟校验;仅有待处理工作时启动。 + _fallbackTimer = new DispatcherTimer(DispatcherPriority.Background) + { + Interval = TimeSpan.FromMilliseconds(100) + }; + _fallbackTimer.Tick += OnFallbackTick; + DocManager.Inst.RequestFrame = _requestFrame; + } + + /// 合并同一帧内的重复冲刷请求,实际校验始终保留在 UI 线程。 + private void RequestFrame(Action action) + { + Dispatcher.UIThread.VerifyAccess(); + if (_isDisposed) + { + action(); + return; + } + + _pendingActions.Add(action); + if (_fallbackTimer.IsEnabled) + { + return; + } + + int generation = ++_generation; + _fallbackTimer.Start(); + _topLevel.RequestAnimationFrame(_ => + { + // 旧宿主、超时兜底以及上一次冲刷遗留的帧回调不能提前执行新一批校验。 + if (!_isDisposed && generation == _generation) + { + Flush(); + } + }); + } + + /// 没有动画帧到来时,在下一次可执行的 UI 调度中完成校验。 + private void OnFallbackTick(object? sender, EventArgs e) + { + Flush(); + } + + /// 先清理本批调度状态,再执行回调,允许校验过程中产生下一批请求。 + private void Flush() + { + _fallbackTimer.Stop(); + _generation++; + Action[] actions = [.. _pendingActions]; + _pendingActions.Clear(); + foreach (Action action in actions) + { + action(); + } + } + + /// 卸载宿主时撤销接线并立即冲刷,避免遗留回调或丢失待校验状态。 + public void Dispose() + { + Dispatcher.UIThread.VerifyAccess(); + if (_isDisposed) + { + return; + } + + _isDisposed = true; + if (DocManager.Inst.RequestFrame == _requestFrame) + { + DocManager.Inst.RequestFrame = null; + } + + _fallbackTimer.Tick -= OnFallbackTick; + Flush(); + } +} diff --git a/OpenUtauMobile/Services/Editor/EditorInputController.Keyboard.cs b/OpenUtauMobile/Services/Editor/EditorInputController.Keyboard.cs index 49fd1dc8..f13fc052 100644 --- a/OpenUtauMobile/Services/Editor/EditorInputController.Keyboard.cs +++ b/OpenUtauMobile/Services/Editor/EditorInputController.Keyboard.cs @@ -29,7 +29,7 @@ public enum EditArea { Tracks, PianoRoll, Mixer } private bool IsEditorInputActive => _inputRoot != null && TopLevel.GetTopLevel(_owner) == _inputRoot && _owner.IsEffectivelyVisible && _owner.IsEffectivelyEnabled && !IsModalOpen && !HasInputPopup && - _owner.DataContext is EditorViewModel { IsLoadingProject: false }; + _owner.DataContext is EditorViewModel { IsLoadingProject: false, CanEditProject: true }; private static bool IsWithin(Visual? source, Visual parent) => source != null && source.GetSelfAndVisualAncestors().Contains(parent); @@ -159,6 +159,8 @@ private async void OnEditorKeyDown(object? sender, KeyEventArgs e) return; } if (EditorShortcuts.IsTextInput(source)) return; + // 浮动工具栏的方向键、空格及 Escape 交给控件自身处理。 + if (source?.GetSelfAndVisualAncestors().Any(node => node is Themes.OpenUtauMobile.Controls.FloatingToolbar) == true) return; if (e.Key == Key.Escape && vm.UseDesktopInput && _activeEditArea != EditArea.Mixer) { _piano.NotesCanvas.CancelTemporaryPitchErase(); diff --git a/OpenUtauMobile/Services/Editor/NoteSelectionToolbarBinding.cs b/OpenUtauMobile/Services/Editor/NoteSelectionToolbarBinding.cs new file mode 100644 index 00000000..2bfc0586 --- /dev/null +++ b/OpenUtauMobile/Services/Editor/NoteSelectionToolbarBinding.cs @@ -0,0 +1,106 @@ +using System; +using System.Reactive.Disposables; +using System.Reactive.Linq; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.VisualTree; +using OpenUtauMobile.Controls; +using OpenUtauMobile.Themes.OpenUtauMobile.Controls; +using OpenUtauMobile.ViewModels; +using ReactiveUI; + +namespace OpenUtauMobile.Services.Editor; + +/// 在移动与桌面编辑页中,将选区或新建占位框映射到页级浮动工具栏。 +public sealed class NoteSelectionToolbarBinding : IDisposable +{ + private readonly FloatingToolbar _toolbar; + private readonly Control _viewport; + private readonly NotesCanvas _notes; + private readonly Control _creationPreview; + private readonly EditorViewModel _editor; + private readonly Func _isPianoVisible; + private readonly Action _activatePiano; + private readonly CompositeDisposable _subscriptions = new(); + + /// 跟随编辑页的挂载生命周期建立绑定;视口应为工具栏所在的覆盖层。 + public NoteSelectionToolbarBinding(FloatingToolbar toolbar, Control viewport, NotesCanvas notes, Control creationPreview, + EditorViewModel editor, Func isPianoVisible, Action activatePiano) + { + _toolbar = toolbar; + _viewport = viewport; + _notes = notes; + _creationPreview = creationPreview; + _editor = editor; + _isPianoVisible = isPianoVisible; + _activatePiano = activatePiano; + viewport.LayoutUpdated += OnLayoutUpdated; + viewport.AddHandler(InputElement.PointerPressedEvent, OnViewportPressed, RoutingStrategies.Tunnel, true); + viewport.AddHandler(InputElement.KeyDownEvent, OnViewportKeyDown, RoutingStrategies.Tunnel, true); + toolbar.AddHandler(InputElement.PointerPressedEvent, OnToolbarPressed, RoutingStrategies.Tunnel); + Observable.FromEvent( + handler => editor.PianoRollViewModel.RequestInvalidateVisual += handler, + handler => editor.PianoRollViewModel.RequestInvalidateVisual -= handler) + .Subscribe(_ => UpdateNoteToolbarAnchor()) + .DisposeWith(_subscriptions); + editor.PianoRollViewModel.WhenAnyValue(model => model.NoteToolbarActions) + .Subscribe(_ => UpdateNoteToolbarAnchor()) + .DisposeWith(_subscriptions); + } + + /// 页面布局、分割和窗口尺寸变化后重新换算坐标。 + private void OnLayoutUpdated(object? sender, EventArgs e) => UpdateNoteToolbarAnchor(); + + /// 选区工具栏的输入始终归属钢琴卷帘。 + private void OnToolbarPressed(object? sender, PointerPressedEventArgs e) => _activatePiano(); + + /// 画布内点击交给音符手势;点击页面其他区域时收起新建占位框。 + private void OnViewportPressed(object? sender, PointerPressedEventArgs e) + { + if (!_editor.PianoRollViewModel.IsNoteCreationPreviewVisible) return; + if (e.Source is Visual source && + (source == _notes || _notes.IsVisualAncestorOf(source) || + source == _creationPreview || _creationPreview.IsVisualAncestorOf(source) || + source == _toolbar || _toolbar.IsVisualAncestorOf(source))) return; + _editor.PianoRollViewModel.DismissNoteCreationPreview(); + } + + /// 占位框及其工具栏允许通过 Escape 取消。 + private void OnViewportKeyDown(object? sender, KeyEventArgs e) + { + if (e.Key != Key.Escape || !_editor.PianoRollViewModel.IsNoteCreationPreviewVisible) return; + _editor.PianoRollViewModel.DismissNoteCreationPreview(); + e.Handled = true; + } + + /// 将当前选区的画布锚点转换到编辑页覆盖层,覆盖音符笔、多选和锚点模式。 + private void UpdateNoteToolbarAnchor() + { + if (!_isPianoVisible() || _editor.IsLoadingProject || + _editor.PianoRollViewModel.GetSelectionToolbarAnchorRect() is not { } anchor) + { + _toolbar.IsVisible = false; + return; + } + Point? origin = _notes.TranslatePoint(anchor.TopLeft, _viewport); + _toolbar.IsVisible = origin.HasValue; + if (origin.HasValue) + { + _toolbar.AnchorRect = new Rect(origin.Value, anchor.Size); + } + } + + /// 解除页级输入、布局与视图模型订阅,离开页面后不再更新工具栏。 + public void Dispose() + { + _viewport.LayoutUpdated -= OnLayoutUpdated; + _viewport.RemoveHandler(InputElement.PointerPressedEvent, OnViewportPressed); + _viewport.RemoveHandler(InputElement.KeyDownEvent, OnViewportKeyDown); + _toolbar.RemoveHandler(InputElement.PointerPressedEvent, OnToolbarPressed); + _subscriptions.Dispose(); + _editor.PianoRollViewModel.DismissNoteCreationPreview(); + _toolbar.IsVisible = false; + } +} diff --git a/OpenUtauMobile/Services/Editor/PartSelectionToolbarBinding.cs b/OpenUtauMobile/Services/Editor/PartSelectionToolbarBinding.cs new file mode 100644 index 00000000..cab83f8f --- /dev/null +++ b/OpenUtauMobile/Services/Editor/PartSelectionToolbarBinding.cs @@ -0,0 +1,75 @@ +using System; +using System.Reactive.Disposables; +using System.Reactive.Linq; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Interactivity; +using OpenUtauMobile.Controls; +using OpenUtauMobile.Themes.OpenUtauMobile.Controls; +using OpenUtauMobile.ViewModels; +using ReactiveUI; + +namespace OpenUtauMobile.Services.Editor; + +/// 在移动与桌面编辑页中,将最后选中的分片映射到页级浮动工具栏。 +public sealed class PartSelectionToolbarBinding : IDisposable +{ + private readonly FloatingToolbar _toolbar; + private readonly Control _viewport; + private readonly PartsCanvas _parts; + private readonly EditorViewModel _editor; + private readonly Func _isArrangementVisible; + private readonly Action _activateArrangement; + private readonly CompositeDisposable _subscriptions = new(); + + /// 绑定分片选区和视口变换;视口为工具栏所在的页级覆盖层。 + public PartSelectionToolbarBinding(FloatingToolbar toolbar, Control viewport, PartsCanvas parts, + EditorViewModel editor, Func isArrangementVisible, Action activateArrangement) + { + _toolbar = toolbar; + _viewport = viewport; + _parts = parts; + _editor = editor; + _isArrangementVisible = isArrangementVisible; + _activateArrangement = activateArrangement; + viewport.LayoutUpdated += OnLayoutUpdated; + toolbar.AddHandler(InputElement.PointerPressedEvent, OnToolbarPressed, RoutingStrategies.Tunnel); + Observable.FromEvent( + handler => editor.RequestInvalidateVisual += handler, + handler => editor.RequestInvalidateVisual -= handler) + .Subscribe(_ => UpdateAnchor()) + .DisposeWith(_subscriptions); + editor.WhenAnyValue(model => model.PartToolbarActions, model => model.IsPartToolbarExpanded) + .Subscribe(_ => UpdateAnchor()) + .DisposeWith(_subscriptions); + } + + /// 页面分割、视口滚动和窗口尺寸变化后重新换算锚点。 + private void OnLayoutUpdated(object? sender, EventArgs e) => UpdateAnchor(); + + /// 操作工具栏时将键盘快捷键的目标切回走带编曲。 + private void OnToolbarPressed(object? sender, PointerPressedEventArgs e) => _activateArrangement(); + + /// 将最后选中的分片从画布坐标转换到页级覆盖层坐标。 + private void UpdateAnchor() + { + if (!_isArrangementVisible() || _editor.IsLoadingProject || _editor.GetPartToolbarAnchorRect() is not { } anchor) + { + _toolbar.IsVisible = false; + return; + } + Point? origin = _parts.TranslatePoint(anchor.TopLeft, _viewport); + _toolbar.IsVisible = origin.HasValue; + if (origin.HasValue) _toolbar.AnchorRect = new Rect(origin.Value, anchor.Size); + } + + /// 离开页面后解除选区、布局与输入订阅。 + public void Dispose() + { + _viewport.LayoutUpdated -= OnLayoutUpdated; + _toolbar.RemoveHandler(InputElement.PointerPressedEvent, OnToolbarPressed); + _subscriptions.Dispose(); + _toolbar.IsVisible = false; + } +} diff --git a/OpenUtauMobile/Services/ExternalSingerPluginService.cs b/OpenUtauMobile/Services/ExternalSingerPluginService.cs new file mode 100644 index 00000000..01844655 --- /dev/null +++ b/OpenUtauMobile/Services/ExternalSingerPluginService.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using OpenUtau.Core.Ustx; +using OpenUtauMobile.Services.SingerPlugins; +using Serilog; + +namespace OpenUtauMobile.Services; + +/// 初始化声明启动入口的外部插件,并集中筛选具体歌手的渲染器。 +public static class ExternalSingerPluginService +{ + private static readonly List> policies = []; + private static readonly HashSet initialized = []; + private static readonly List refreshers = []; + private static readonly List> normalizers = []; + + /// 在核心歌手首次扫描后、工程载入前调用插件的约定入口。 + public static void Initialize() + { + SingerPluginService.Initialize(); + foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) + { + if (!PluginActivationService.ShouldInitialize(assembly)) continue; + if (initialized.Contains(assembly)) continue; + string? entry = assembly.GetCustomAttributes() + .FirstOrDefault(attribute => attribute.Key == "OpumPluginStartup")?.Value; + if (entry == null) continue; + try + { + Type type = assembly.GetType(entry, true)!; + MethodInfo method = type.GetMethod("Initialize", [typeof(Action>)]) + ?? throw new MissingMethodException(entry, "Initialize"); + List> pending = []; + method.Invoke(null, [new Action>(pending.Add)]); + policies.AddRange(pending); + if (type.GetMethod("RefreshSingers", Type.EmptyTypes) is { } refresh) + refreshers.Add(() => refresh.Invoke(null, null)); + if (type.GetMethod("NormalizeProject", [typeof(UProject)]) is { } normalize) + normalizers.Add(project => (bool)normalize.Invoke(null, [project])!); + initialized.Add(assembly); + } + catch (Exception exception) { Log.Error(exception, "Failed to initialize singer plugin {Assembly}", assembly.FullName); } + } + } + + /// 在没有发布歌手变更通知的直接重扫之后恢复外部注册。 + public static void RefreshSingers() + { + foreach (Action refresh in refreshers) + try { refresh(); } catch (Exception exception) { Log.Error(exception, "Failed to refresh external singers"); } + } + + /// 按实际歌手实例筛选可用渲染器。 + public static string[] GetSupportedRenderers(USinger singer) + { + foreach (Func policy in policies) + if (policy(singer) is { } options) return options; + return SingerPluginService.Registry.GetSupportedRenderers(singer.SingerType); + } + + /// 返回具体歌手的默认渲染器。 + public static string GetDefaultRenderer(USinger singer) + { + string[] options = GetSupportedRenderers(singer); + if (options.Length == 0) return string.Empty; + string preferred = SingerPluginService.Registry.GetDefaultRenderer(singer.SingerType); + return options.Contains(preferred) ? preferred : options.FirstOrDefault() ?? string.Empty; + } + + /// 在载入及轨道导入时补正外部 renderer,并重新校验快照。 + public static void NormalizeProject(UProject project) + { + UnavailableSinger.PreserveReferences(project); + bool changed = false; + foreach (Func normalize in normalizers) changed |= normalize(project); + if (changed) project.ValidateFull(); + } +} diff --git a/OpenUtauMobile/Services/PluginActivationService.cs b/OpenUtauMobile/Services/PluginActivationService.cs new file mode 100644 index 00000000..d98ee497 --- /dev/null +++ b/OpenUtauMobile/Services/PluginActivationService.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Reflection.Metadata; +using System.Reflection.PortableExecutable; +using System.Threading; +using System.Threading.Tasks; +using Avalonia.Threading; +using OpenUtau.Core.Util; +using OpenUtauMobile.Services.Projects; +using Serilog; + +namespace OpenUtauMobile.Services; + +/// 持久化插件启用名单,并在启动时冻结本进程使用的加载范围。 +public static class PluginActivationService +{ + private static readonly SemaphoreSlim Gate = new(1, 1); + private static HashSet? startupPaths; + private static HashSet disabledModules = []; + internal static StringComparer PathComparer => OperatingSystem.IsWindows() + ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; + + /// 查询已提交的启用状态,未列入名单的插件默认禁用。 + public static bool IsEnabled(string relativePath) => + Preferences.Default.EnabledPlugins.Contains(relativePath, PathComparer); + + /// 串行保存名单,成功后才发布状态,避免安装与页面操作覆盖彼此。 + public static async Task SetEnabledAsync(string relativePath, bool enabled) + { + string normalized = Path.GetRelativePath(PluginManagementService.Root, + PluginManagementService.ResolvePluginPath(relativePath)); + await Gate.WaitAsync(); + try + { + await Dispatcher.UIThread.InvokeAsync(async () => + { + HashSet paths = [with(Preferences.Default.EnabledPlugins, PathComparer)]; + if (enabled) paths.Add(normalized); + else paths.Remove(normalized); + List saved = [.. paths.Order(PathComparer)]; + await PreferencesWriter.Inst.SaveAsync(preferences => preferences.EnabledPlugins = [.. saved]); + }); + } + finally { Gate.Release(); } + } + + /// 固定启动名单并记录禁用模块,只有用户启用或安装操作能够加入名单。 + public static async Task PrepareStartupAsync() + { + IReadOnlyList files = await Task.Run(PluginManagementService.ListFiles); + await Dispatcher.UIThread.InvokeAsync(() => + { + startupPaths = [with(Preferences.Default.EnabledPlugins, PathComparer)]; + }); + HashSet disabled = []; + foreach (PluginFileEntry file in files) + { + if (startupPaths!.Contains(file.RelativePath)) continue; + try + { + using FileStream stream = File.OpenRead(PluginManagementService.ResolvePluginPath(file.RelativePath)); + using PEReader pe = new(stream); + if (pe.HasMetadata) + { + MetadataReader reader = pe.GetMetadataReader(); + disabled.Add(reader.GetGuid(reader.GetModuleDefinition().Mvid)); + } + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException or BadImageFormatException) + { Log.Debug(error, "Failed to inspect disabled plugin {Plugin}", file.RelativePath); } + } + disabledModules = disabled; + } + + /// 在加载文件前使用启动快照过滤,内置目录中的程序集不受外部名单限制。 + public static bool ShouldLoadFile(string path) + { + string fullPath = Path.GetFullPath(path); + string prefix = Path.TrimEndingDirectorySeparator(PluginManagementService.Root) + Path.DirectorySeparatorChar; + if (!fullPath.StartsWith(prefix, OperatingSystem.IsWindows() + ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) return true; + return startupPaths?.Contains(Path.GetRelativePath(PluginManagementService.Root, fullPath)) == true; + } + + /// 禁止已因依赖解析进入进程的禁用模块执行插件入口,兼容移动端映射路径。 + public static bool ShouldInitialize(Assembly assembly) => + !assembly.IsDynamic && !disabledModules.Contains(assembly.ManifestModule.ModuleVersionId); +} diff --git a/OpenUtauMobile/Services/PluginDataService.cs b/OpenUtauMobile/Services/PluginDataService.cs new file mode 100644 index 00000000..d0f1c721 --- /dev/null +++ b/OpenUtauMobile/Services/PluginDataService.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Avalonia.Threading; +using OpenUtau.Core.Util; +using OpenUtauMobile.Plugin.Abstractions; +using OpenUtauMobile.Services.Projects; +using OpenUtauMobile.Services.SingerPlugins; +using Serilog; + +namespace OpenUtauMobile.Services; + +/// 在插件启动前执行用户已确认的数据清除,避免与运行中的插件争用文件。 +public static class PluginDataService +{ + private static readonly SemaphoreSlim Gate = new(1, 1); + + /// 查询插件是否已登记下次启动清除数据。 + public static bool IsPending(string pluginId) => Preferences.Default.PendingPluginDataClears.Contains(pluginId, StringComparer.Ordinal); + + /// 等待清除或取消任务持久化,当前进程内不触碰插件数据。 + public static async Task SetPendingAsync(string pluginId, bool clear) + { + SingerPluginContract.ValidatePluginId(pluginId); + await Gate.WaitAsync(); + try + { + await Dispatcher.UIThread.InvokeAsync(async () => + { + HashSet pending = [with(Preferences.Default.PendingPluginDataClears, StringComparer.Ordinal)]; + if (clear) pending.Add(pluginId); + else pending.Remove(pluginId); + List saved = [.. pending.Order(StringComparer.Ordinal)]; + await PreferencesWriter.Inst.SaveAsync(preferences => preferences.PendingPluginDataClears = [.. saved]); + }); + } + finally { Gate.Release(); } + } + + /// 启动时一次性消费清除请求;持久化失败不删除,执行失败不会静默重试。 + public static async Task ApplyPendingAsync() + { + await Gate.WaitAsync(); + try + { + string[] pending = await Dispatcher.UIThread.InvokeAsync(async () => + { + string[] ids = [.. Preferences.Default.PendingPluginDataClears]; + if (ids.Length > 0) + await PreferencesWriter.Inst.SaveAsync(preferences => preferences.PendingPluginDataClears = []); + return ids; + }); + return await Task.Run(() => + { + int failures = 0; + foreach (string id in pending) + { + try { Clear(id); } + catch (Exception error) + { + failures++; + Log.Warning(error, "Failed to clear plugin data {PluginId}", id); + } + } + return failures; + }); + } + catch (Exception error) { Log.Error(error, "Failed to process pending plugin data clears"); return 1; } + finally { Gate.Release(); } + } + + /// 目录由验证后的插件 ID 唯一确定,先检查整个子树及父级,拒绝跨目录链接。 + private static void Clear(string pluginId) + { + string directory = Path.GetFullPath(PluginWebSettingsService.Storage(pluginId).DataDirectory); + if (!Directory.Exists(directory)) return; + for (DirectoryInfo? parent = new(directory); parent != null; parent = parent.Parent) + RejectLink(parent); + Inspect(new DirectoryInfo(directory)); + Directory.Delete(directory, recursive: true); + } + + private static void Inspect(DirectoryInfo directory) + { + RejectLink(directory); + foreach (FileSystemInfo item in directory.EnumerateFileSystemInfos()) + { + RejectLink(item); + if (item is DirectoryInfo child) Inspect(child); + } + } + + private static void RejectLink(FileSystemInfo item) + { + if ((item.Attributes & FileAttributes.ReparsePoint) != 0) + throw new IOException("插件数据目录包含链接,无法自动清除。"); + } +} diff --git a/OpenUtauMobile/Services/PluginInformationService.cs b/OpenUtauMobile/Services/PluginInformationService.cs new file mode 100644 index 00000000..501fda54 --- /dev/null +++ b/OpenUtauMobile/Services/PluginInformationService.cs @@ -0,0 +1,191 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Reflection.Metadata; +using System.Reflection.PortableExecutable; +using System.Security.Cryptography; +using OpenUtau.Core; +using OpenUtauMobile.Services.Projects; +using OpenUtauMobile.Services.SingerPlugins; +using Serilog; + +namespace OpenUtauMobile.Services; + +/// 详情页可展示的一项信息,标签使用本地化资源键。 +public sealed record PluginInformationItem(string LabelKey, string Value); + +/// 按模块标识保存的插件身份和能力,不序列化插件实例。 +public sealed record PluginRegistrationInfo(string Id, string Name, PluginInformationItem[] Capabilities); + +/// 静态文件信息与最近一次成功登记的能力快照。 +public sealed record PluginInformation(string Name, Guid ModuleId, PluginInformationItem[] Metadata, + PluginRegistrationInfo? Registration, PluginInformationItem[] StaticCapabilities); + +/// 只读提取程序集元数据,并缓存已登记的插件信息;不会加载外部程序集。 +public static class PluginInformationService +{ + /// 从磁盘提取版本、签名标志、引用和文件摘要,优先使用本进程的登记信息。 + public static PluginInformation Read(string relativePath) + { + string path = PluginManagementService.ResolvePluginPath(relativePath); + using FileStream stream = File.OpenRead(path); + using PEReader pe = new(stream, PEStreamOptions.LeaveOpen); + MetadataReader reader = pe.GetMetadataReader(); + AssemblyDefinition assembly = reader.GetAssemblyDefinition(); + Guid moduleId = reader.GetGuid(reader.GetModuleDefinition().Mvid); + string assemblyName = reader.GetString(assembly.Name); + List items = + [ + new("PluginDetails.Assembly", assemblyName), + new("PluginDetails.Version", assembly.Version.ToString()), + new("PluginDetails.File", relativePath), + new("PluginDetails.Size", $"{stream.Length / 1024d:N1} KB"), + new("PluginDetails.Architecture", pe.PEHeaders.CoffHeader.Machine.ToString()), + new("PluginDetails.Module", moduleId.ToString()), + ]; + string name = assemblyName; + foreach (CustomAttributeHandle handle in assembly.GetCustomAttributes()) + { + CustomAttribute attribute = reader.GetCustomAttribute(handle); + if (attribute.Constructor.Kind != HandleKind.MemberReference) continue; + MemberReference constructor = reader.GetMemberReference((MemberReferenceHandle)attribute.Constructor); + if (constructor.Parent.Kind != HandleKind.TypeReference) continue; + TypeReference type = reader.GetTypeReference((TypeReferenceHandle)constructor.Parent); + if (reader.GetString(type.Namespace) == "OpenUtauMobile.Plugin.Abstractions" + && reader.GetString(type.Name) == "SingerPluginAttribute") + { + BlobReader entry = reader.GetBlobReader(attribute.Value); + if (entry.ReadUInt16() == 1) + { + items.Add(new("PluginDetails.EntryPoint", entry.ReadSerializedString() ?? "")); + items.Add(new("PluginDetails.ContractVersion", entry.ReadInt32().ToString())); + } + continue; + } + string? label = (reader.GetString(type.Namespace), reader.GetString(type.Name)) switch + { + ("System.Reflection", "AssemblyTitleAttribute") => "PluginDetails.Name", + ("System.Reflection", "AssemblyDescriptionAttribute") => "PluginDetails.Description", + ("System.Reflection", "AssemblyCompanyAttribute") => "PluginDetails.Author", + ("System.Reflection", "AssemblyProductAttribute") => "PluginDetails.Product", + ("System.Reflection", "AssemblyCopyrightAttribute") => "PluginDetails.Copyright", + ("System.Reflection", "AssemblyInformationalVersionAttribute") => "PluginDetails.ProductVersion", + ("System.Reflection", "AssemblyFileVersionAttribute") => "PluginDetails.FileVersion", + ("System.Runtime.Versioning", "TargetFrameworkAttribute") => "PluginDetails.Framework", + _ => null, + }; + if (label == null) continue; + BlobReader blob = reader.GetBlobReader(attribute.Value); + if (blob.ReadUInt16() != 1 || blob.ReadSerializedString() is not { Length: > 0 } value) continue; + items.Add(new(label, value)); + if (label == "PluginDetails.Name") name = value; + } + byte[] key = reader.GetBlobBytes(assembly.PublicKey); + if (key.Length > 0) + { + byte[] hash = SHA1.HashData(key); + byte[] token = [.. hash.TakeLast(8).Reverse()]; + items.Add(new("PluginDetails.PublicKeyToken", Convert.ToHexString(token).ToLowerInvariant())); + items.Add(new("PluginDetails.PublicKey", Convert.ToHexString(key))); + } + items.Add(new("PluginDetails.StrongName", Helpers.L.S( + (pe.PEHeaders.CorHeader!.Flags & CorFlags.StrongNameSigned) != 0 + ? "PluginDetails.SignaturePresent" : "PluginDetails.Unsigned"))); + items.Add(new("PluginDetails.Authenticode", Helpers.L.S( + pe.PEHeaders.PEHeader?.CertificateTableDirectory.Size > 0 + ? "PluginDetails.SignaturePresent" : "PluginDetails.Unsigned"))); + items.Add(new("PluginDetails.References", string.Join(Environment.NewLine, + reader.AssemblyReferences.Select(handle => reader.GetAssemblyReference(handle)) + .Select(reference => $"{reader.GetString(reference.Name)}, {reference.Version}")))); + stream.Position = 0; + items.Add(new("PluginDetails.Hash", Convert.ToHexString(SHA256.HashData(stream)))); + + PluginRegistrationInfo? registration = CurrentRegistration(relativePath) ?? ReadCached(moduleId); + List staticCapabilities = []; + foreach (TypeDefinitionHandle handle in reader.TypeDefinitions) + { + TypeDefinition type = reader.GetTypeDefinition(handle); + if ((type.Attributes & TypeAttributes.VisibilityMask) is not TypeAttributes.Public and not TypeAttributes.NestedPublic + || (type.Attributes & TypeAttributes.Abstract) != 0) continue; + string fullName = reader.GetString(type.Namespace) + "." + reader.GetString(type.Name); + if (DerivesFrom(reader, type.BaseType, "OpenUtau.Api", "Phonemizer")) + staticCapabilities.Add(new("PluginDetails.Phonemizer", fullName)); + if (DerivesFrom(reader, type.BaseType, "OpenUtau.Core.Editing", "BatchEdit")) + staticCapabilities.Add(new("PluginDetails.BatchEdit", fullName)); + } + return new(registration?.Name ?? name, moduleId, [.. items], registration, [.. staticCapabilities]); + } + + /// 在启动登记结束后保存快照,使禁用后的详情页仍可展示稳定 ID 和能力。 + public static void CacheRegistrations() + { + IReadOnlyList files; + try { files = PluginManagementService.ListFiles(); } + catch (Exception error) { Log.Warning(error, "Failed to list plugins for information cache"); return; } + foreach (PluginFileEntry file in files) + { + try + { + if (CurrentRegistration(file.RelativePath) is not { } registration) continue; + using FileStream stream = File.OpenRead(PluginManagementService.ResolvePluginPath(file.RelativePath)); + using PEReader pe = new(stream); + MetadataReader reader = pe.GetMetadataReader(); + Guid module = reader.GetGuid(reader.GetModuleDefinition().Mvid); + AtomicFileWriter.Write(CachePath(module), writer => writer.Write(Json.Serialize(registration))); + } + catch (Exception error) { Log.Warning(error, "Failed to cache plugin information {Plugin}", file.RelativePath); } + } + } + + private static PluginRegistrationInfo? CurrentRegistration(string relativePath) + { + RegisteredSingerPlugin? plugin = PluginWebSettingsService.FindPlugin(relativePath); + if (plugin == null) return null; + SingerPluginSnapshot snapshot = SingerPluginService.Registry.Snapshot; + List capabilities = []; + foreach (RegisteredSingerType type in snapshot.Types.Values.Where(type => type.PluginId == plugin.PluginId).OrderBy(type => type.Descriptor.Id)) + { + capabilities.Add(new("PluginDetails.SingerType", $"{type.Descriptor.DisplayName} ({type.Descriptor.Id})")); + foreach (string renderer in type.Descriptor.RendererIds) + capabilities.Add(new("PluginDetails.Renderer", renderer)); + } + foreach (RegisteredSingerProvider provider in snapshot.Providers.Values.Where(provider => provider.PluginId == plugin.PluginId).OrderBy(provider => provider.Id)) + capabilities.Add(new("PluginDetails.Provider", provider.Id)); + foreach (RegisteredSingerInstaller installer in snapshot.Installers.Values.Where(installer => installer.PluginId == plugin.PluginId).OrderBy(installer => installer.Descriptor.Id)) + capabilities.Add(new("PluginDetails.Installer", $"{installer.Descriptor.DisplayName} ({installer.Descriptor.Id}) {string.Join(", ", installer.Descriptor.Extensions)}")); + return new(plugin.PluginId, snapshot.Plugins[plugin.PluginId].DisplayName, [.. capabilities]); + } + + private static PluginRegistrationInfo? ReadCached(Guid module) + { + try + { + return File.Exists(CachePath(module)) + ? Json.Deserialize(File.ReadAllText(CachePath(module))) : null; + } + catch (Exception error) { Log.Debug(error, "Failed to read plugin information cache {Module}", module); return null; } + } + + private static string CachePath(Guid module) => Path.Combine(PathManager.Inst.DataPath, "PluginInfoCache", $"{module:N}.json"); + + /// 只沿元数据继承链识别可导出的能力,不解析或加载外部依赖。 + private static bool DerivesFrom(MetadataReader reader, EntityHandle handle, string expectedNamespace, string expectedName) + { + HashSet visited = []; + while (!handle.IsNil && visited.Add(handle)) + { + if (handle.Kind == HandleKind.TypeReference) + { + TypeReference type = reader.GetTypeReference((TypeReferenceHandle)handle); + return reader.GetString(type.Namespace) == expectedNamespace && reader.GetString(type.Name) == expectedName; + } + if (handle.Kind != HandleKind.TypeDefinition) return false; + TypeDefinition definition = reader.GetTypeDefinition((TypeDefinitionHandle)handle); + if (reader.GetString(definition.Namespace) == expectedNamespace && reader.GetString(definition.Name) == expectedName) return true; + handle = definition.BaseType; + } + return false; + } +} diff --git a/OpenUtauMobile/Services/PluginLoadErrorReporter.cs b/OpenUtauMobile/Services/PluginLoadErrorReporter.cs index f199a294..4219b941 100644 --- a/OpenUtauMobile/Services/PluginLoadErrorReporter.cs +++ b/OpenUtauMobile/Services/PluginLoadErrorReporter.cs @@ -24,11 +24,23 @@ private PluginLoadErrorReporter() public void Emit(LogEvent logEvent) { - if (logEvent.Level < LogEventLevel.Warning || logEvent.Exception == null) + if (logEvent.Level < LogEventLevel.Warning) { return; } + // 仅元数据检查失败也应进入统一通知,不在歌手目录中生成错误条目。 + if (logEvent.MessageTemplate.Text == "Plugin assembly unavailable: {Location}: {Message}" + && logEvent.Properties.TryGetValue("Location", out LogEventPropertyValue? source) + && source is ScalarValue { Value: string unavailable } + && logEvent.Properties.TryGetValue("Message", out LogEventPropertyValue? detail) + && detail is ScalarValue { Value: string message }) + { + _pendingErrors.Enqueue(new IOException(unavailable, logEvent.Exception ?? new InvalidOperationException(message))); + return; + } + if (logEvent.Exception == null) return; + // 上游没有公开逐文件加载结果;按结构化模板识别,不解析日志文件或本地化文本。 switch (logEvent.MessageTemplate.Text) { @@ -42,6 +54,11 @@ public void Emit(LogEvent logEvent) case "Failed to search plugins.": _pendingErrors.Enqueue(new IOException(PathManager.Inst.PluginsPath, logEvent.Exception)); break; + case "Failed to initialize singer plugin {Assembly}": + string location = logEvent.Properties.TryGetValue("Assembly", out LogEventPropertyValue? assembly) + && assembly is ScalarValue { Value: string path } ? path : PathManager.Inst.PluginsPath; + _pendingErrors.Enqueue(new IOException(location, logEvent.Exception)); + break; } } diff --git a/OpenUtauMobile/Services/PluginManagementService.cs b/OpenUtauMobile/Services/PluginManagementService.cs index 6ac6c0fe..28e241f6 100644 --- a/OpenUtauMobile/Services/PluginManagementService.cs +++ b/OpenUtauMobile/Services/PluginManagementService.cs @@ -4,11 +4,13 @@ using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; -using System.Text.Json; +using System.Threading; using System.Threading.Tasks; +using Avalonia.Threading; using OpenUtau.Core; using OpenUtau.Core.Util; using OpenUtauMobile.Helpers; +using OpenUtauMobile.Services.Projects; using OpenUtauMobile.ViewModels; using Serilog; @@ -24,7 +26,8 @@ public sealed record PluginFileEntry(string RelativePath, long Size, bool IsPend public static class PluginManagementService { private const string BuiltinFileName = "OpenUtau.Plugin.Builtin.dll"; - private static string Root => Path.GetFullPath(PathManager.Inst.PluginsPath); + private static readonly SemaphoreSlim DeletionGate = new(1, 1); + internal static string Root => Path.GetFullPath(PathManager.Inst.PluginsPath); private static StringComparer PathComparer => OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; @@ -32,12 +35,11 @@ public static IReadOnlyList ListFiles() { Directory.CreateDirectory(Root); HashSet pending = ReadPendingDeletions(); - // 不跟随目录链接,避免将插件目录之外的文件纳入管理。 EnumerationOptions options = new() { RecurseSubdirectories = true, IgnoreInaccessible = false, - AttributesToSkip = FileAttributes.ReparsePoint, + AttributesToSkip = 0, }; return Directory.EnumerateFiles(Root, "*", options) .Where(path => string.Equals(Path.GetExtension(path), ".dll", StringComparison.OrdinalIgnoreCase)) @@ -48,24 +50,40 @@ public static IReadOnlyList ListFiles() .ToArray(); } - public static async Task InstallAsync(string sourcePath, LoadingPopupViewModel loading) + /// 在询问信任前检查安装条件,仅读取元数据,不加载程序集。 + public static void ValidateForInstall(string sourcePath) + { + using FileStream source = new(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read); + ValidateForInstall(sourcePath, source); + } + + /// 校验安装条件并返回目标路径,不写入插件目录。 + private static string ValidateForInstall(string sourcePath, Stream source) { - // TODO:补充 iOS 外部程序集执行能力和 Web 导入、加载链路的专门适配。 string fileName = Path.GetFileName(sourcePath); if (!string.Equals(Path.GetExtension(fileName), ".dll", StringComparison.OrdinalIgnoreCase)) throw new InvalidDataException(L.S("PluginManager.InvalidAssembly")); if (string.Equals(fileName, BuiltinFileName, StringComparison.OrdinalIgnoreCase)) throw new InvalidDataException(L.S("PluginManager.BuiltinNotAllowed")); - await using FileStream source = new(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read); - loading.UpdateProgress(0, L.S("PluginManager.Checking")); ValidateAssembly(source); - source.Position = 0; - Directory.CreateDirectory(Root); string destination = ResolvePluginPath(fileName); if (File.Exists(destination) || ReadPendingDeletions().Contains(fileName)) throw new IOException(L.S("PluginManager.AlreadyExists")); + return destination; + } + + /// 重新校验并复制已获用户信任的插件,不加载程序集。 + public static async Task InstallAsync(string sourcePath, LoadingPopupViewModel loading) + { + // TODO:补充 iOS 外部程序集执行能力和 Web 导入、加载链路的专门适配。 + await using FileStream source = new(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read); + loading.UpdateProgress(0, L.S("PluginManager.Checking")); + // 确认期间源文件或安装状态可能变化,复制前再次检查。 + string destination = ValidateForInstall(sourcePath, source); + source.Position = 0; + Directory.CreateDirectory(Root); // 临时文件不使用 DLL 扩展名,只有完整复制后才进入插件列表。 string temporaryPath = Path.Combine(Root, $".{Guid.NewGuid():N}.installing"); @@ -86,6 +104,16 @@ public static async Task InstallAsync(string sourcePath, LoadingPopupViewModel l await target.FlushAsync(); } File.Move(temporaryPath, destination); + try + { + await PluginActivationService.SetEnabledAsync(Path.GetRelativePath(Root, destination), true); + } + catch + { + // 名单保存失败时撤销本次新文件,避免安装失败却残留无法再次安装的文件。 + DeletePluginFile(destination); + throw; + } loading.UpdateProgress(95, L.S("PluginManager.Completed")); } finally @@ -111,31 +139,37 @@ private static void ValidateAssembly(Stream source) } } - /// 仅登记删除任务,插件文件统一在下次启动加载前删除。 - public static void ScheduleDeletion(string relativePath) + /// 等待删除任务持久化,插件文件统一在下次启动加载前删除。 + public static Task ScheduleDeletionAsync(string relativePath) { - string path = ResolvePluginPath(relativePath); - HashSet pending = ReadPendingDeletions(); - pending.Add(Path.GetRelativePath(Root, path)); - WritePendingDeletions(pending); + return UpdatePendingDeletionAsync(relativePath, delete: true); } - /// 取消待删除标记,不修改插件文件。 - public static void CancelDeletion(string relativePath) + /// 等待取消标记持久化,不修改插件文件。 + public static Task CancelDeletionAsync(string relativePath) { - string path = ResolvePluginPath(relativePath); - HashSet pending = ReadPendingDeletions(); - pending.Remove(Path.GetRelativePath(Root, path)); - List previous = Preferences.Default.PendingPluginDeletions; + return UpdatePendingDeletionAsync(relativePath, delete: false); + } + + /// 串行读取和修改删除队列,避免并发登记或取消覆盖彼此。 + private static async Task UpdatePendingDeletionAsync(string relativePath, bool delete) + { + await DeletionGate.WaitAsync(); try { - WritePendingDeletions(pending); + await Dispatcher.UIThread.InvokeAsync(async () => + { + string path = ResolvePluginPath(relativePath); + HashSet pending = ReadPendingDeletions(); + string normalized = Path.GetRelativePath(Root, path); + if (delete) pending.Add(normalized); + else pending.Remove(normalized); + await WritePendingDeletionsAsync(pending); + }); } - catch + finally { - // 取消未能保存时仍显示待删除标记,避免误认为下次启动不会删除。 - Preferences.Default.PendingPluginDeletions = previous; - throw; + DeletionGate.Release(); } } @@ -153,43 +187,55 @@ private static void DeletePluginFile(string path) File.Delete(path); } - /// 必须在启动时的插件扫描之前调用,任务只消费一次,失败也不保留。 - public static int ApplyPendingDeletions() + /// 在插件扫描前等待队列消费持久化;文件删除只尝试一次,消费保存失败则不删除。 + public static async Task ApplyPendingDeletionsAsync() { + await DeletionGate.WaitAsync(); try { - HashSet pending = ReadPendingDeletions(); - if (pending.Count == 0) return 0; - int failures = 0; - // 先清空并保存队列,再执行删除,避免失败或中途退出后反复重试。 - try - { - WritePendingDeletions([with(PathComparer)]); - } - catch (Exception exception) - { - Log.Error(exception, "Failed to consume pending plugin deletions."); - failures++; - } - foreach (string relativePath in pending) + HashSet pending = await Dispatcher.UIThread.InvokeAsync(async () => { - try + HashSet snapshot = ReadPendingDeletions(); + // 必须先确认队列已消费,再删除文件,避免保存失败后下次启动重复执行。 + if (snapshot.Count > 0) { - DeletePluginFile(ResolvePluginPath(relativePath)); + List enabled = [.. Preferences.Default.EnabledPlugins.Where(path => !snapshot.Contains(path))]; + await PreferencesWriter.Inst.SaveAsync(preferences => + { + preferences.PendingPluginDeletions = []; + preferences.EnabledPlugins = [.. enabled]; + }); } - catch (Exception exception) + return snapshot; + }); + if (pending.Count == 0) return 0; + return await Task.Run(() => + { + int failures = 0; + foreach (string relativePath in pending) { - failures++; - Log.Warning(exception, "Failed to delete pending plugin {Plugin}", relativePath); + try + { + DeletePluginFile(ResolvePluginPath(relativePath)); + } + catch (Exception exception) + { + failures++; + Log.Warning(exception, "Failed to delete pending plugin {Plugin}", relativePath); + } } - } - return failures; + return failures; + }); } catch (Exception exception) { Log.Error(exception, "Failed to process pending plugin deletions"); return 1; } + finally + { + DeletionGate.Release(); + } } private static HashSet ReadPendingDeletions() @@ -197,22 +243,14 @@ private static HashSet ReadPendingDeletions() return [with(Preferences.Default.PendingPluginDeletions ?? [], PathComparer)]; } - private static void WritePendingDeletions(HashSet pending) + /// 仅在保存成功后发布新列表,保存失败保留原有状态并传播实际异常。 + private static Task WritePendingDeletionsAsync(HashSet pending) { - Preferences.Default.PendingPluginDeletions = pending.OrderBy(path => path, PathComparer).ToList(); - Preferences.Save(); - - // 保存方法会自行捕获异常,回读字段以免将未持久化的任务提示为成功。 - using JsonDocument saved = JsonDocument.Parse(File.ReadAllText(PathManager.Inst.PrefsFilePath)); - string[] persisted = saved.RootElement.GetProperty(nameof(Preferences.SerializablePreferences.PendingPluginDeletions)) - .EnumerateArray().Select(value => value.GetString()!).ToArray(); - if (!pending.SetEquals(persisted)) - { - throw new IOException("Failed to save pending plugin deletions in preferences."); - } + List paths = [.. pending.OrderBy(path => path, PathComparer)]; + return PreferencesWriter.Inst.SaveAsync(preferences => preferences.PendingPluginDeletions = [.. paths]); } - private static string ResolvePluginPath(string relativePath) + internal static string ResolvePluginPath(string relativePath) { ArgumentException.ThrowIfNullOrWhiteSpace(relativePath); string path = Path.GetFullPath(Path.Combine(Root, relativePath)); diff --git a/OpenUtauMobile/Services/Projects/AtomicFileWriter.cs b/OpenUtauMobile/Services/Projects/AtomicFileWriter.cs new file mode 100644 index 00000000..ea4dea15 --- /dev/null +++ b/OpenUtauMobile/Services/Projects/AtomicFileWriter.cs @@ -0,0 +1,43 @@ +using System; +using System.IO; +using System.Text; +using Serilog; + +namespace OpenUtauMobile.Services.Projects; + +/// 将独立数据写入同目录暂存文件,再替换目标;失败时保留旧目标。 +internal static class AtomicFileWriter +{ + /// 仅供后台调用;显式刷新编码器及文件后才执行替换。 + public static long Write(string path, Action serialize, Action? replacing = null) + { + string fullPath = Path.GetFullPath(path); + string directory = Path.GetDirectoryName(fullPath)!; + Directory.CreateDirectory(directory); + string staging = Path.Combine(directory, $".{Path.GetFileName(path)}.{Guid.NewGuid():N}.tmp"); + try + { + long length; + using (FileStream stream = new(staging, FileMode.CreateNew, FileAccess.Write, FileShare.None, 65536)) + { + using (StreamWriter writer = new(stream, Encoding.UTF8, 65536, leaveOpen: true)) + { + serialize(writer); + writer.Flush(); + } + // 一次最终持久化刷新,不对每个缓冲块同步闪存。 + if (OperatingSystem.IsBrowser()) stream.Flush(); + else stream.Flush(flushToDisk: true); + length = stream.Length; + } + replacing?.Invoke(); + File.Move(staging, fullPath, overwrite: true); + return length; + } + finally + { + try { if (File.Exists(staging)) File.Delete(staging); } + catch (Exception error) { Log.Warning(error, "无法清理保存暂存文件 {Path}", staging); } + } + } +} diff --git a/OpenUtauMobile/Services/Projects/PreferencesWriter.cs b/OpenUtauMobile/Services/Projects/PreferencesWriter.cs new file mode 100644 index 00000000..9cfe0fc0 --- /dev/null +++ b/OpenUtauMobile/Services/Projects/PreferencesWriter.cs @@ -0,0 +1,185 @@ +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +using Avalonia.Threading; +using OpenUtau.Core; +using OpenUtau.Core.Util; +using Serilog; + +namespace OpenUtauMobile.Services.Projects; + +/// 宿主偏好单写入器;UI 只复制内存,后台合并并原子写入,关键事务可等待持久化。 +public sealed class PreferencesWriter +{ + /// 应用进程唯一的偏好写入器,平台生命周期通过此实例请求刷新。 + public static PreferencesWriter Inst { get; } = new(); + private static readonly ConcurrentDictionary Members = new(); + private readonly List<(long Version, TaskCompletionSource Completion)> _waiters = []; + private readonly SemaphoreSlim _changeGate = new(1, 1); + private PendingChange? _change; + private PendingSave? _pending; + private Task? _pump; + private long _version; + private long _completedVersion; + private string? _lastWrittenJson; + private string? _lastWrittenPath; + + /// 在应用启动时注册;未注册宿主的上游程序仍使用原同步实现。 + public void Install() => Preferences.SaveOverride = RequestSave; + + /// 统一将请求派发到 UI,避免后台枚举可变偏好集合。 + private void RequestSave() + { + if (!Dispatcher.UIThread.CheckAccess()) + { + Dispatcher.UIThread.Post(RequestSave); + return; + } + _pending = CapturePendingSave(); + _pump ??= PumpAsync(); + } + + /// 复制已提交的偏好,并将尚未提交的事务叠加到每个后台快照。 + private PendingSave CapturePendingSave() + { + var snapshot = (Preferences.SerializablePreferences)CopyValue(Preferences.Default)!; + _change?.Apply(snapshot); + return new(++_version, snapshot, PathManager.Inst.PrefsFilePath); + } + + /// 关键事务直接请求并等待持久化,捕获失败也向调用者传播。 + public Task SaveAsync() + { + Dispatcher.UIThread.VerifyAccess(); + RequestSave(); + return FlushAsync(); + } + + /// 串行暂存字段更新,落盘后才发布到内存;更新委托只能赋值偏好字段,不能产生外部副作用。 + public async Task SaveAsync(Action update) + { + Dispatcher.UIThread.VerifyAccess(); + await _changeGate.WaitAsync(); + try + { + _change = new(_version + 1, update); + await SaveAsync(); + } + finally + { + _change = null; + _changeGate.Release(); + } + } + + /// 等待调用时已请求的偏好版本持久化;失败向调用者传播,下一请求可重试。 + public Task FlushAsync() + { + Dispatcher.UIThread.VerifyAccess(); + if (_completedVersion == _version) return Task.CompletedTask; + TaskCompletionSource completion = new(TaskCreationOptions.RunContinuationsAsynchronously); + _waiters.Add((_version, completion)); + _pump ??= PumpAsync(); + return completion.Task; + } + + /// 偏好数据仅含公开 DTO 字段/可写属性;复制集合及嵌套 DTO,不序列化活动对象。 + private static object? CopyValue(object? value) + { + if (value == null || value is string || value.GetType().IsValueType) return value; + Type type = value.GetType(); + if (value is Array array) + { + Array copy = Array.CreateInstance(type.GetElementType()!, array.Length); + for (int i = 0; i < array.Length; i++) copy.SetValue(CopyValue(array.GetValue(i)), i); + return copy; + } + if (value is IDictionary dictionary) + { + IDictionary copy = (IDictionary)Activator.CreateInstance(type)!; + foreach (DictionaryEntry entry in dictionary) copy.Add(entry.Key, CopyValue(entry.Value)); + return copy; + } + if (value is IList list) + { + IList copy = (IList)Activator.CreateInstance(type)!; + foreach (object? item in list) copy.Add(CopyValue(item)); + return copy; + } + object result = Activator.CreateInstance(type)!; + var members = Members.GetOrAdd(type, current => ( + [.. current.GetFields(BindingFlags.Instance | BindingFlags.Public).Where(field => !field.IsInitOnly)], + [.. current.GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(property => property.CanRead && property.SetMethod?.IsPublic == true && property.GetIndexParameters().Length == 0)])); + foreach (FieldInfo field in members.Fields) field.SetValue(result, CopyValue(field.GetValue(value))); + foreach (PropertyInfo property in members.Properties) property.SetValue(result, CopyValue(property.GetValue(value))); + return result; + } + + /// 每批只保留最新偏好快照,避免连续操作反复写入闪存。 + private async Task PumpAsync() + { + await Task.Delay(200); + try + { + while (_pending is { } pending) + { + _pending = null; + try + { + await Task.Run(() => + { + string json = Json.Serialize(pending.Snapshot, Json.WriteIndentedOptions); + // 自动保存通常只重复同一个恢复路径;数据未变时不再写偏好文件。 + if (json == _lastWrittenJson && pending.Path == _lastWrittenPath && File.Exists(pending.Path)) return; + AtomicFileWriter.Write(pending.Path, writer => writer.Write(json)); + _lastWrittenJson = json; + _lastWrittenPath = pending.Path; + }); + if (_change is { } change && change.Version <= pending.Version) + { + change.Apply(Preferences.Default); + _change = null; + } + _completedVersion = pending.Version; + FinishWaiters(pending.Version, null); + } + catch (Exception error) + { + _pending ??= pending; + if (_change != null) + { + // 失败的事务不能随生命周期刷新重试;同时保留其他偏好的最新值。 + _change = null; + _pending = CapturePendingSave(); + } + Log.Error(error, "偏好后台保存失败"); + FinishWaiters(long.MaxValue, error); + break; + } + } + } + finally { _pump = null; } + } + + /// 完成已落盘版本的等待者;失败保留最新待写快照供后续重试。 + private void FinishWaiters(long version, Exception? error) + { + for (int i = _waiters.Count - 1; i >= 0; i--) + { + if (_waiters[i].Version > version) continue; + TaskCompletionSource completion = _waiters[i].Completion; + _waiters.RemoveAt(i); + if (error == null) completion.TrySetResult(); + else completion.TrySetException(error); + } + } + + private sealed record PendingSave(long Version, Preferences.SerializablePreferences Snapshot, string Path); + private sealed record PendingChange(long Version, Action Apply); +} diff --git a/OpenUtauMobile/Services/Projects/ProjectSaveCoordinator.cs b/OpenUtauMobile/Services/Projects/ProjectSaveCoordinator.cs new file mode 100644 index 00000000..2c2c6bc2 --- /dev/null +++ b/OpenUtauMobile/Services/Projects/ProjectSaveCoordinator.cs @@ -0,0 +1,160 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Avalonia.Threading; +using OpenUtau.Core; +using OpenUtau.Core.Ustx; +using OpenUtau.Core.Util; +using Serilog; + +namespace OpenUtauMobile.Services.Projects; + +/// 保存阶段由功能调用方本地化,后台不读取 UI 资源。 +internal enum ProjectSaveStage { Capturing, Waiting, Preparing, Serializing, Writing, Replacing, Synchronizing, Confirming } + +/// 手动、模板及自动保存共用的单写入队列;活动工程只在 UI 捕获和确认阶段访问。 +internal sealed class ProjectSaveCoordinator +{ + // 保存独占实例在后台首次创建,避免默认序列化器的锁阻塞 UI 上的表达式图指纹计算。 + private static readonly Lazy SaveSerializer = new(() => new Yaml()); + /// 所有保存入口共用进程内唯一的工程写入队列。 + public static ProjectSaveCoordinator Inst { get; } = new(); + private readonly SemaphoreSlim _writer = new(1, 1); + private bool _autoSaveRunning; + private int _manualRequests; + private string _backupPath = string.Empty; + private long _recoveryGeneration; + + /// 用户明确丢弃恢复时使在途自动任务失去发布恢复提示的资格。 + public void DismissRecovery() + { + Dispatcher.UIThread.VerifyAccess(); + _recoveryGeneration++; + } + + /// 调用方在模态窗口内等待整个事务;模板保存不会更改活动工程保存点。 + public async Task SaveManualAsync(DocManager.SaveCheckpoint owner, string path, bool template, + IProgress? progress = null) + { + Dispatcher.UIThread.VerifyAccess(); + _manualRequests++; + try { return await SaveAsync(owner, path, template, autoSave: false, progress); } + finally { _manualRequests--; } + } + + /// 无编辑、开放撤销组、有手动请求或已有自动任务时跳过,不积压快照。 + public async Task AutoSaveAsync(DocManager.SaveCheckpoint owner) + { + Dispatcher.UIThread.VerifyAccess(); + DocManager doc = DocManager.Inst; + if (_autoSaveRunning || _manualRequests != 0 || !doc.IsSaveCheckpointCurrent(owner) || doc.HasOpenUndoGroup) + return false; + DocManager.SaveCheckpoint point = doc.CaptureSaveCheckpoint(); + if (!doc.NeedsAutoSave(point)) return false; + if (string.IsNullOrEmpty(_backupPath)) + { + // DocManager 只拥有一个活动工程,队列统一替换同一个恢复文件,避免重开工程积累备份。 + _backupPath = Path.Combine(PathManager.Inst.BackupsPath, "Mobile-autosave.ustx"); + } + _autoSaveRunning = true; + try { return await SaveAsync(owner, _backupPath, template: false, autoSave: true, progress: null); } + catch (Exception error) + { + // 不推进检查点,下一次定时请求仍能重试;不弹模态打断编辑。 + Log.Error(error, "自动保存失败"); + return false; + } + finally { _autoSaveRunning = false; } + } + + /// 捕获开始时版本,后台准备及写入,最后按文档会话确认结果。 + private async Task SaveAsync(DocManager.SaveCheckpoint owner, string path, bool template, bool autoSave, + IProgress? progress) + { + DocManager doc = DocManager.Inst; + if (!doc.IsSaveCheckpointCurrent(owner) || doc.HasOpenUndoGroup || string.IsNullOrWhiteSpace(path)) return false; + progress?.Report(ProjectSaveStage.Capturing); + string previousRecovery = Preferences.Default.RecoveryPath; + long recoveryGeneration = _recoveryGeneration; + DocManager.SaveCheckpoint point = doc.CaptureSaveCheckpoint(); + Stopwatch total = Stopwatch.StartNew(); + UProject snapshot = ProjectSaveSnapshot.Capture(doc.Project, template); + Log.Information("保存阶段 {Stage}:{Milliseconds:F2} ms,Auto={Auto},Template={Template}", + "Capture", total.Elapsed.TotalMilliseconds, autoSave, template); + + progress?.Report(ProjectSaveStage.Waiting); + Stopwatch phase = Stopwatch.StartNew(); + await _writer.WaitAsync(); + try + { + LogPhase("Wait", phase); + // 排队期间已经换工程的任务无需再消耗磁盘;已开始的写盘始终使用捕获路径。 + if (!doc.IsSaveCheckpointCurrent(point)) return false; + await Task.Run(() => WriteSnapshot(snapshot, path, progress)); + progress?.Report(ProjectSaveStage.Synchronizing); + phase.Restart(); + await ServiceHub.FlushFileSystemAsync(); + LogPhase("SyncProject", phase); + if (!doc.IsSaveCheckpointCurrent(point)) return false; + if (template) return true; + + progress?.Report(ProjectSaveStage.Confirming); + if (autoSave) + { + // 用户丢弃恢复或其他事务已经发布恢复路径时,旧任务不得恢复该提示。 + if (_recoveryGeneration != recoveryGeneration || Preferences.Default.RecoveryPath != previousRecovery) return false; + Preferences.Default.RecoveryPath = path; + } + else + { + Preferences.Default.RecoveryPath = string.Empty; + Preferences.Default.LastSaveProjectDirectory = Path.GetDirectoryName(path) ?? string.Empty; + // 已知目标刚刚成功写入,最近记录不再逐个同步查盘。 + var recent = Preferences.Default.RecentFiles; + recent.RemoveAll(file => string.IsNullOrEmpty(file) || file == path || + file.StartsWith(PathManager.Inst.TemplatesPath + Path.DirectorySeparatorChar, StringComparison.Ordinal)); + recent.Insert(0, path); + if (recent.Count > 16) recent.RemoveRange(16, recent.Count - 16); + } + await PreferencesWriter.Inst.SaveAsync(); + LogPhase("Preferences", phase); + await ServiceHub.FlushFileSystemAsync(); + LogPhase("SyncPreferences", phase); + if (autoSave && (_recoveryGeneration != recoveryGeneration || Preferences.Default.RecoveryPath != path)) return false; + bool committed = doc.CompleteSave(point, path, autoSave); + Log.Information("保存完成:{Milliseconds:F2} ms,Auto={Auto},Committed={Committed}", + total.Elapsed.TotalMilliseconds, autoSave, committed); + return committed; + } + finally { _writer.Release(); } + } + + /// 只访问独立快照;分开记录 CPU 序列化、文件写入和替换阶段。 + private static void WriteSnapshot(UProject snapshot, string path, IProgress? progress) + { + Stopwatch phase = Stopwatch.StartNew(); + progress?.Report(ProjectSaveStage.Preparing); + ProjectSaveSnapshot.Prepare(snapshot, path); + LogPhase("Prepare", phase); + progress?.Report(ProjectSaveStage.Serializing); + string yaml = SaveSerializer.Value.Serialize(snapshot); + LogPhase("Serialize", phase); + progress?.Report(ProjectSaveStage.Writing); + long bytes = AtomicFileWriter.Write(path, writer => writer.Write(yaml), () => + { + LogPhase("Write", phase); + progress?.Report(ProjectSaveStage.Replacing); + }); + LogPhase("Replace", phase); + Log.Information("工程写入 {Bytes} bytes:{Path}", bytes, path); + } + + /// 记录阶段耗时并开始下一阶段计时。 + private static void LogPhase(string stage, Stopwatch watch) + { + Log.Information("保存阶段 {Stage}:{Milliseconds:F2} ms", stage, watch.Elapsed.TotalMilliseconds); + watch.Restart(); + } +} diff --git a/OpenUtauMobile/Services/Projects/ProjectSaveSnapshot.cs b/OpenUtauMobile/Services/Projects/ProjectSaveSnapshot.cs new file mode 100644 index 00000000..f15955e5 --- /dev/null +++ b/OpenUtauMobile/Services/Projects/ProjectSaveSnapshot.cs @@ -0,0 +1,136 @@ +using System; +using System.Linq; +using Avalonia.Threading; +using OpenUtau.Core.Format; +using OpenUtau.Core.Ustx; + +namespace OpenUtauMobile.Services.Projects; + +/// 仅包含 USTX 持久化数据的独立副本,不持有活动歌手、音素器或渲染数据。 +internal static class ProjectSaveSnapshot +{ + /// 在一个 UI 调度回合捕获一致版本;返回后后台只能访问该副本。 + public static UProject Capture(UProject source, bool template) + { + Dispatcher.UIThread.VerifyAccess(); + UProject copy = new() + { + ustxVersion = Ustx.kUstxVersion, + expressionGraphs = source.expressionGraphs == null ? null : [.. source.expressionGraphs.Select(graph => graph.Clone())], + defaultExpressionGraphs = source.defaultExpressionGraphs == null ? null : new(source.defaultExpressionGraphs), + }; + foreach (var pair in source.expressions) copy.expressions.Add(pair.Key, CopyExpression(pair.Value)); + // 保留现有模板语义:表达式和表达式图沿用,内容、轨道和时序使用新工程默认值。 + if (template) + { + copy.tracks = [.. copy.tracks.Select(CopyTrack)]; + return copy; + } + + copy.name = source.name; + copy.comment = source.comment; + copy.outputDir = source.outputDir; + copy.cacheDir = source.cacheDir; +#pragma warning disable CS0618 + copy.bpm = source.bpm; + copy.beatPerBar = source.beatPerBar; + copy.beatUnit = source.beatUnit; +#pragma warning restore CS0618 + copy.expSelectors = [.. source.expSelectors]; + copy.expPrimary = source.expPrimary; + copy.expSecondary = source.expSecondary; + copy.key = source.key; + copy.timeSignatures = [.. source.timeSignatures.Select(value => new UTimeSignature(value.barPosition, value.beatPerBar, value.beatUnit))]; + copy.tempos = [.. source.tempos.Select(value => new UTempo(value.position, value.bpm))]; + copy.tracks = [.. source.tracks.Select(CopyTrack)]; + copy.parts = [.. source.parts.Select(CopyPart)]; + return copy; + } + + /// 复制表达式的原始字段,保留自定义默认值的空值语义。 + private static UExpressionDescriptor CopyExpression(UExpressionDescriptor source) => new() + { + name = source.name, abbr = source.abbr, type = source.type, + min = source.min, max = source.max, defaultValue = source.defaultValue, + _customDefaultValue = source._customDefaultValue, + isFlag = source.isFlag, flag = source.flag, + options = source.options == null ? null! : [.. source.options], + skipOutputIfDefault = source.skipOutputIfDefault, + }; + + /// 捕获 BeforeSave 所需的运行时标识,后台不再接触歌手实例。 + private static UTrack CopyTrack(UTrack source) => new() + { + singer = source.Singer?.Id!, + phonemizer = source.Phonemizer.GetType().FullName!, + RendererSettings = new URenderSettings + { + renderer = source.RendererSettings.renderer, + resampler = source.RendererSettings.resampler, + wavtool = source.RendererSettings.wavtool, + }, + TrackName = source.TrackName, TrackColor = source.TrackColor, + Mute = source.Mute, Solo = source.Solo, + MixFx = source.MixFx?.Clone()!, Volume = source.Volume, Pan = source.Pan, + TrackExpressions = [.. source.TrackExpressions.Select(CopyExpression)], + ExpressionGraph = source.ExpressionGraph, + VoiceColorNames = source.Singer is { Found: true } && source.VoiceColorExp?.options is { Length: > 0 } colors + ? [.. colors] : [string.Empty], + }; + + /// 复制片段持久化字段,音频片段只记录引用,不读取或加载波形。 + private static UPart CopyPart(UPart source) + { + UPart copy = source switch + { + UVoicePart voice => new UVoicePart + { + duration = voice.duration, + notes = [.. voice.notes.Select(CopyNote)], + curves = [.. voice.curves.Select(curve => new UCurve(curve.abbr) { xs = [.. curve.xs], ys = [.. curve.ys] })], + maskedCurves = [.. voice.maskedCurves.Select(curve => curve.Clone())], + }, + UWavePart wave => new UWavePart + { + FilePath = wave.FilePath, relativePath = wave.relativePath, + fileDurationMs = wave.fileDurationMs, skip = wave.skip, trim = wave.trim, + fadein = wave.fadein, fadeout = wave.fadeout, + }, + _ => throw new NotSupportedException($"Unsupported project part: {source.GetType().Name}"), + }; + copy.name = source.name; + copy.comment = source.comment; + copy.trackNo = source.trackNo; + copy.position = source.position; + return copy; + } + + /// 音符表达式只保留值,避免 Clone 引用活动表达式描述符。 + private static UNote CopyNote(UNote source) => new() + { + position = source.position, duration = source.duration, tone = source.tone, + lyric = source.lyric, pitch = source.pitch.Clone(), vibrato = source.vibrato.Clone(), + tuning = source.tuning, PhonemizerOverride = source.PhonemizerOverride, + phonemeExpressions = [.. source.phonemeExpressions.Select(value => new UExpression + { + abbr = value.abbr, index = value.index, value = value.value, + })], + phonemeOverrides = [.. source.phonemeOverrides.Select(value => value.Clone())], + }; + + /// 在后台执行原 BeforeSave 的纯数据归一化,不调用具有运行时副作用的保存入口。 + public static void Prepare(UProject copy, string path) + { + copy.FilePath = path; + foreach (UPart part in copy.parts) + { + if (part is UWavePart wave) + wave.relativePath = System.IO.Path.GetRelativePath(System.IO.Path.GetDirectoryName(path)!, wave.FilePath); + else if (part is UVoicePart voice) + foreach (UNote note in voice.notes) + note.phonemeExpressions = [.. note.phonemeExpressions.OrderBy(value => value.index).ThenBy(value => value.abbr)]; + } + copy.voiceParts = [.. copy.parts.OfType().OrderBy(part => part.trackNo).ThenBy(part => part.position)]; + copy.waveParts = [.. copy.parts.OfType().OrderBy(part => part.trackNo).ThenBy(part => part.position)]; + } +} diff --git a/OpenUtauMobile/Services/ServiceHub.cs b/OpenUtauMobile/Services/ServiceHub.cs index 215111d8..14a0397c 100644 --- a/OpenUtauMobile/Services/ServiceHub.cs +++ b/OpenUtauMobile/Services/ServiceHub.cs @@ -1,6 +1,8 @@ using System; +using System.Collections.Generic; using System.Threading.Tasks; using Avalonia.Media; +using OpenUtau.Audio; using OpenUtauMobile.Services.Graphics; using OpenUtauMobile.Services.Performance; using OpenUtauMobile.Services.Platform; @@ -15,6 +17,8 @@ namespace OpenUtauMobile.Services; /// public static class ServiceHub { + /// 通过平台生命周期退出应用,避免直接终止进程。 + public static Action? PlatformExitApplication { get; set; } public static Func? DesktopWindowFactory { get; set; } public static IDesktopWindowContext? DesktopWindowContext { get; set; } public static Func? DesktopPopupSizeProvider { get; set; } @@ -28,6 +32,10 @@ public static class ServiceHub public static IGraphicsBackendService? GraphicsBackendService { get; set; } public static Controls.Gestures.IViewportInputPlatform? ViewportInputPlatform { get; set; } public static Action? InitAudioOutput { get; set; } + /// 创建系统管理的音频路由选择控件,路由变化时通知设置页刷新。 + public static Func? AudioDevicePickerFactory { get; set; } + /// 读取系统路由的实际输出端口,独立于当前音频后端的设备枚举。 + public static Func>? GetSystemAudioOutputDevices { get; set; } public static IClipboardService ClipboardService { get; set; } = new AvaloniaClipboardService(); public static IExternalUrlLauncher? ExternalUrlLauncher { get; set; } public static IExternalStorageService? ExternalStorageService { get; set; } diff --git a/OpenUtauMobile/Services/SingerInstallation/VogenPackage.cs b/OpenUtauMobile/Services/SingerInstallation/VogenPackage.cs new file mode 100644 index 00000000..76fcc45a --- /dev/null +++ b/OpenUtauMobile/Services/SingerInstallation/VogenPackage.cs @@ -0,0 +1,31 @@ +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Threading; +using SharpCompress.Archives; +using SharpCompress.Readers; + +namespace OpenUtauMobile.Services.SingerInstallation +{ + /// 仅读取 Vogen 展示信息,与安装提交及模型加载无关。 + internal static class VogenPackage + { + /// 无法取得可展示的名称时返回空;读取异常由页面转换为非阻断提示。 + internal static (string Name, string Version)? ReadMetadata(string source, CancellationToken token) + { + token.ThrowIfCancellationRequested(); + using FileStream input = File.OpenRead(source); + using IArchive archive = ArchiveFactory.OpenArchive(input, new ReaderOptions { LeaveStreamOpen = false }); + IArchiveEntry? meta = archive.Entries.FirstOrDefault(entry => !entry.IsDirectory && entry.Key == "meta.json"); + if (meta == null) return null; + using Stream stream = meta.OpenEntryStream(); + using JsonDocument document = JsonDocument.Parse(stream); + JsonElement root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("name", out JsonElement name) + || name.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(name.GetString())) return null; + token.ThrowIfCancellationRequested(); + return (name.GetString()!, root.TryGetProperty("version", out JsonElement version) && version.ValueKind == JsonValueKind.String + ? version.GetString()! : ""); + } + } +} diff --git a/OpenUtauMobile/Services/SingerPlugins/BuiltinSingerMaintenance.cs b/OpenUtauMobile/Services/SingerPlugins/BuiltinSingerMaintenance.cs new file mode 100644 index 00000000..e829e246 --- /dev/null +++ b/OpenUtauMobile/Services/SingerPlugins/BuiltinSingerMaintenance.cs @@ -0,0 +1,36 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using OpenUtau.Core; +using OpenUtau.Core.Ustx; +using OpenUtauMobile.Services.SingerPlugins.Installation; + +namespace OpenUtauMobile.Services.SingerPlugins +{ + /// 保留内置卸载入口,重扫统一经过 Mobile 协调器。 + internal static class BuiltinSingerMaintenance + { + /// 类型和实例均由 Core 提供时才允许内置目录卸载。 + internal static bool CanUninstall(USinger singer) => singer.GetType().Assembly == typeof(USinger).Assembly && + SingerPluginService.Registry.Snapshot.TypesByBridge.TryGetValue(singer.SingerType, out RegisteredSingerType? type) && + type.PluginId == "opum.builtin"; + + internal static async Task UninstallAsync(USinger singer) + { + if (!CanUninstall(singer)) throw new InvalidOperationException("此歌手的维护操作由提供方管理。"); + string path = Path.GetFullPath(singer.Location); + bool inside = false; + foreach (string root in PathManager.Inst.SingersPaths) + if (path.StartsWith(Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)) + Path.DirectorySeparatorChar, + InstallPaths.Comparison)) inside = true; + if (!inside) throw new IOException("不能卸载歌手根目录或目录外的内容。"); + await SingerDiscoveryService.Instance.MaintainAsync(() => Task.Run(() => + { + singer.FreeMemory(); + if (Directory.Exists(path)) Directory.Delete(path, true); + else if (File.Exists(path)) File.Delete(path); + else throw new FileNotFoundException("歌手位置不存在。", path); + })); + } + } +} diff --git a/OpenUtauMobile/Services/SingerPlugins/Installation/InstallFileOperations.cs b/OpenUtauMobile/Services/SingerPlugins/Installation/InstallFileOperations.cs new file mode 100644 index 00000000..f10662af --- /dev/null +++ b/OpenUtauMobile/Services/SingerPlugins/Installation/InstallFileOperations.cs @@ -0,0 +1,134 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Threading; +using System.Threading.Tasks; +using OpenUtauMobile.Plugin.Abstractions; +using Serilog; + +namespace OpenUtauMobile.Services.SingerPlugins.Installation +{ + /// 发布已校验文件,记录提交回执并清理本会话独占的临时目录。 + internal sealed class InstallFileOperations(InstallWorkspace workspace, ImmutableArray targets, + Guid sessionId) : IInstallFileOperations + { + private readonly List staging = []; + private readonly List published = []; + internal ImmutableArray Published => published.ToImmutableArray(); + internal bool CanPublish { get; set; } + internal ImmutableArray PlannedPaths { get; set; } = []; + + public string ResolveEntryPath(string workspaceDirectory, string entryPath) + { + string directory = workspace.GetPath(workspaceDirectory); + return InstallPaths.Resolve(directory, entryPath.TrimEnd('/', '\\')); + } + + public async ValueTask PublishAsync(PublishRequest request, + IProgress progress, CancellationToken cancellationToken) + { + if (!CanPublish) throw new InvalidOperationException("当前阶段不允许发布文件。"); + InstallTarget target = targets.FirstOrDefault(item => item.Id == request.TargetId) + ?? throw new IOException("安装目标不可用。"); + string source = workspace.GetPath(request.SourceRelativePath); + string destination = InstallPaths.Resolve(target.Path, request.DestinationRelativePath); + RequirePlanned(destination); + RequireAbsent(destination); + bool directory = request.Kind == InstallArtifactKind.Directory; + if (directory ? !Directory.Exists(source) : !File.Exists(source)) throw new IOException("已校验的安装源不存在。"); + cancellationToken.ThrowIfCancellationRequested(); + Directory.CreateDirectory(Path.GetDirectoryName(destination)!); + progress.Report(new(InstallPhase.Publishing, request.DestinationRelativePath)); + try + { + Move(source, destination, directory); + } + catch (IOException) when (!File.Exists(destination) && !Directory.Exists(destination) && + (directory ? Directory.Exists(source) : File.Exists(source))) + { + // 不同挂载点的 Move 可能失败;将同一份内容复制到目标卷后校验再移动。 + string temporary = InstallPaths.Resolve(target.Path, $".singer-install-{sessionId:N}-{Guid.NewGuid():N}"); + Directory.CreateDirectory(temporary); + staging.Add(temporary); + string copy = Path.Combine(temporary, "payload"); + await CopyCheckedAsync(source, copy, directory, cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); + RequireAbsent(destination); + Move(copy, destination, directory); + } + PublishedLocation location = new(destination, request.Kind); + // Move 已完成后即记录回执,后续取消不能将它回退成未安装。 + published.Add(location); + return location; + } + + private static void Move(string source, string destination, bool directory) + { + if (directory) Directory.Move(source, destination); + else File.Move(source, destination, false); + } + + internal static void RequireAbsent(string path) + { + if (File.Exists(path) || Directory.Exists(path)) throw new IOException($"安装目标已存在:{path}"); + } + + private static async Task CopyCheckedAsync(string source, string destination, bool directory, CancellationToken token) + { + token.ThrowIfCancellationRequested(); + if (directory) + { + Directory.CreateDirectory(destination); + foreach (string child in Directory.EnumerateFileSystemEntries(source)) + await CopyCheckedAsync(child, Path.Combine(destination, Path.GetFileName(child)), Directory.Exists(child), token); + return; + } + await using FileStream input = File.OpenRead(source); + await using (FileStream output = new(destination, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + await input.CopyToAsync(output, token); + input.Position = 0; + byte[] originalHash = await SHA256.HashDataAsync(input, token); + await using FileStream copied = File.OpenRead(destination); + byte[] copiedHash = await SHA256.HashDataAsync(copied, token); + if (!originalHash.AsSpan().SequenceEqual(copiedHash)) throw new IOException("跨卷复制校验失败。"); + } + + public void RegisterTemporaryPath(string path) + { + InstallPaths.RequireInside(workspace.RootPath, path); + // Workspace 统一清理,无需再保存可与正式目录混淆的额外列表。 + } + + public void RecordPublishedLocation(PublishedLocation location) + { + if (!CanPublish) throw new InvalidOperationException("当前阶段不允许登记发布结果。"); + string path = Path.GetFullPath(location.Path); + RequirePlanned(path); + if (!targets.Any(target => path.StartsWith(Path.TrimEndingDirectorySeparator(Path.GetFullPath(target.Path)) + Path.DirectorySeparatorChar, + InstallPaths.Comparison))) throw new IOException("发布位置不属于配置的安装目标。"); + if (location.Kind == InstallArtifactKind.Directory ? !Directory.Exists(path) : !File.Exists(path)) + throw new IOException("正式发布内容不存在。"); + if (published.All(item => !string.Equals(item.Path, path, InstallPaths.Comparison))) published.Add(location with { Path = path }); + } + + private void RequirePlanned(string path) + { + if (!PlannedPaths.Any(item => string.Equals(Path.GetFullPath(item), path, InstallPaths.Comparison))) + throw new IOException("发布位置不在当前安装计划中。"); + } + + /// 仅清理宿主独占的缓存和目标卷暂存目录。 + internal void Cleanup() + { + foreach (string path in staging.Append(workspace.RootPath)) + try + { + InstallPaths.DeleteTemporary(path); + } + catch (Exception exception) { Log.Warning(exception, "Failed to clean singer installation workspace {Path}", path); } + } + } +} diff --git a/OpenUtauMobile/Services/SingerPlugins/Installation/InstallWorkspace.cs b/OpenUtauMobile/Services/SingerPlugins/Installation/InstallWorkspace.cs new file mode 100644 index 00000000..6ebcb2b7 --- /dev/null +++ b/OpenUtauMobile/Services/SingerPlugins/Installation/InstallWorkspace.cs @@ -0,0 +1,94 @@ +using System; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using OpenUtauMobile.Plugin.Abstractions; + +namespace OpenUtauMobile.Services.SingerPlugins.Installation +{ + /// 限定会话路径边界,拒绝越界路径。 + internal static class InstallPaths + { + internal static StringComparison Comparison => OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + + /// 仅接受根目录下的相对路径,拒绝跨平台分隔符绕过。 + internal static string Resolve(string root, string relative) + { + if (string.IsNullOrWhiteSpace(relative) || Path.IsPathRooted(relative) || relative.Contains(':')) + throw new IOException("无效的安装相对路径。"); + string normalized = relative.Replace('\\', '/'); + if (normalized.Split('/').Any(part => part is ".." or "." or "")) + throw new IOException("安装路径不能包含空路径或上级目录。"); + string full = Path.GetFullPath(Path.Combine(root, normalized)); + RequireInside(root, full); + return full; + } + + internal static void RequireInside(string root, string path) + { + string prefix = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)) + Path.DirectorySeparatorChar; + if (!Path.GetFullPath(path).StartsWith(prefix, Comparison)) throw new IOException("安装路径超出允许范围。"); + } + + internal static void DeleteTemporary(string path) + { + if (Directory.Exists(path)) Directory.Delete(path, true); + else if (File.Exists(path)) File.Delete(path); + } + } + + /// 宿主拥有的会话缓存,不删除任何正式发布内容。 + internal sealed class InstallWorkspace : IInstallWorkspace + { + public string RootPath { get; } + internal InstallWorkspace(string cachePath, Guid sessionId) + { + RootPath = Path.GetFullPath(Path.Combine(cachePath, "SingerInstall", sessionId.ToString("N"))); + Directory.CreateDirectory(RootPath); + } + public string GetPath(string relativePath) => InstallPaths.Resolve(RootPath, relativePath); + public string CreateDirectory(string relativePath) + { + string path = GetPath(relativePath); + Directory.CreateDirectory(path); + return path; + } + } + + /// 将所选包固定到会话缓存,之后分析、预览和提交共用同一来源。 + internal sealed class InstallSource(string originalPath, InstallWorkspace workspace) : IInstallSource + { + private string? localPath; + private readonly SemaphoreSlim materialize = new(1, 1); + public string DisplayName => Path.GetFileName(originalPath); + public long? Length => new FileInfo(localPath ?? originalPath).Length; + public async ValueTask OpenReadAsync(CancellationToken cancellationToken) => + File.OpenRead(await GetLocalPathAsync(cancellationToken)); + public async ValueTask GetLocalPathAsync(CancellationToken cancellationToken) + { + await materialize.WaitAsync(cancellationToken); + try + { + if (localPath != null) return localPath; + string path = Path.Combine(workspace.CreateDirectory("source"), DisplayName); + bool created = false; + try + { + await using FileStream source = File.OpenRead(originalPath); + await using FileStream destination = new(path, FileMode.CreateNew, FileAccess.Write, FileShare.None); + created = true; + await source.CopyToAsync(destination, cancellationToken); + localPath = path; + return path; + } + catch + { + if (created) File.Delete(path); + throw; + } + } + finally { materialize.Release(); } + } + } +} diff --git a/OpenUtauMobile/Services/SingerPlugins/Installation/SingerInstallController.cs b/OpenUtauMobile/Services/SingerPlugins/Installation/SingerInstallController.cs new file mode 100644 index 00000000..9b20217e --- /dev/null +++ b/OpenUtauMobile/Services/SingerPlugins/Installation/SingerInstallController.cs @@ -0,0 +1,247 @@ +using System; +using System.Collections.Immutable; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using OpenUtau.Core; +using OpenUtauMobile.Plugin.Abstractions; +using Serilog; + +namespace OpenUtauMobile.Services.SingerPlugins.Installation +{ + /// 拥有安装会话、版本和临时文件;页面只能驱动串行操作。 + public sealed class SingerInstallController : IAsyncDisposable + { + private readonly SemaphoreSlim gate = new(1, 1); + private readonly CancellationTokenSource lifetime = new(); + private readonly RegisteredSingerInstaller installer; + private readonly SingerInstallContext context; + private readonly InstallFileOperations files; + private ISingerInstallSession? session; + private Task? closing; + private bool finished; + private bool installStarted; + private long inputVersion; + /// 最后一次经过宿主验证的页面快照。 + public InstallView? View { get; private set; } + /// 当前唯一可提交计划,输入变化立即清除。 + public PreparedInstall? Plan { get; private set; } + /// 本会话可选的配置目标。 + public ImmutableArray Targets => context.InstallTargets; + /// 遵循宿主当前安装目录设置。 + public string DefaultTargetId => context.DefaultTargetId; + /// 预览资源只能从本会话缓存读取。 + public string PreviewPath(string relativePath) => context.Workspace.GetPath(relativePath); + + /// 在已有会话串行器内后台预读图片,清理缓存前完成文件访问。 + public Task ReadPreviewAsync(string relativePath) => RunAsync(token => + File.ReadAllBytesAsync(PreviewPath(relativePath), token)); + + public SingerInstallController(RegisteredSingerInstaller installer, string sourcePath) + { + this.installer = installer; + Guid id = Guid.NewGuid(); + ImmutableArray targets = [new("configured", Path.GetFullPath(PathManager.Inst.SingersInstallPath), + PathManager.Inst.SingersInstallPath)]; + string fullSource = Path.GetFullPath(sourcePath); + ImmutableArray roots = SingerPluginRuntime.Roots(); + // 只提供插件目录,配置格式和兼容性由插件负责。 + PluginStorageContext storage = SingerPluginRuntime.Storage(installer.PluginId); + InstallWorkspace workspace = new(PathManager.Inst.CachePath, id); + files = new(workspace, targets, id); + context = new(id, CultureInfo.CurrentUICulture, new InstallSource(fullSource, workspace), + workspace, roots, targets, targets[0].Id, new InstalledLookup(), files, + storage, new SingerPluginRuntime.PluginLog(installer.PluginId)); + } + + /// 创建失败与分析失败均等待释放插件句柄,再清理缓存。 + public Task AnalyzeAsync(IProgress progress) => RunAsync(async token => + { + if (session != null || View != null) throw new InvalidOperationException("会话已初始化。"); + try + { + session = await installer.Instance.CreateSessionAsync(context, token); + return Accept(await session.AnalyzeAsync(progress, token)); + } + catch + { + await FinishAsync(); + throw; + } + }); + + /// 提交当前字段后前进,拒绝过期 Revision。 + public Task NextAsync(InstallSubmission submission, IProgress progress) => RunAsync(async token => + { + RequireSubmission(submission); + if (!View!.CanGoNext) throw new InvalidOperationException("当前步骤不能前进。"); + Plan = null; + return Accept(await session!.NextAsync(submission, progress, token)); + }); + + /// 回退后旧计划永远失效。 + public Task BackAsync() => RunAsync(async token => + { + if (View?.CanGoBack != true) throw new InvalidOperationException("当前步骤不能回退。"); + Plan = null; + return Accept(await session!.BackAsync(View.Revision, token)); + }); + + /// 末步输入与目标同时校验,避免摘要遗漏最后一次编辑。 + public Task PrepareAsync(InstallSubmission submission, string targetId, + IProgress progress) => RunAsync(async token => + { + RequireSubmission(submission); + if (!View!.CanPrepare || !Targets.Any(item => item.Id == targetId)) + throw new InvalidOperationException("当前状态不能准备安装。"); + Plan = null; + long version = Interlocked.Read(ref inputVersion); + PreparedInstall plan = await session!.PrepareAsync(new(targetId), submission, progress, token); + if (plan.PlanId == Guid.Empty || plan.InstallerId != installer.Descriptor.Id || plan.TargetId != targetId || + plan.Revision != View.Revision || plan.DestinationPaths.IsDefaultOrEmpty || + (!plan.Diagnostics.IsDefault && plan.Diagnostics.Any(item => item.Severity == PluginDiagnosticSeverity.Error))) + throw new SingerInstallException("install.invalid-plan", "安装计划无效。"); + InstallTarget target = Targets.Single(item => item.Id == targetId); + foreach (string path in plan.DestinationPaths) + { + InstallPaths.RequireInside(target.Path, path); + InstallFileOperations.RequireAbsent(path); + } + if (version != Interlocked.Read(ref inputVersion)) + throw new SingerInstallException("install.stale-plan", "输入已变化,请重新检查安装。"); + Plan = plan; + return plan; + }); + + /// 字段或目标编辑后不允许提交旧摘要。 + public void InvalidatePlan() + { + Interlocked.Increment(ref inputVersion); + Plan = null; + } + + /// 计划只消费一次;发布后的异常返回真实部分成功结果。 + public Task InstallAsync(Guid planId, IProgress progress) => RunAsync(async token => + { + if (Plan?.PlanId != planId || installStarted) throw new InvalidOperationException("安装计划已失效。"); + PreparedInstall plan = Plan; + Plan = null; + installStarted = true; + InstallResult result = await SingerDiscoveryService.Instance.WithCatalogLockAsync(async () => + { + InstallResult committed; + try + { + token.ThrowIfCancellationRequested(); + files.PlannedPaths = plan.DestinationPaths; + files.CanPublish = true; + committed = await session!.InstallAsync(planId, progress, token); + if (files.Published.IsDefaultOrEmpty) throw new IOException("安装器未返回正式发布回执。"); + committed = committed with { Locations = files.Published }; + if (plan.DestinationPaths.Any(path => files.Published.All(item => + !string.Equals(item.Path, Path.GetFullPath(path), InstallPaths.Comparison)))) + committed = AddFailure(committed, "install.incomplete", "安装器未提交计划中的全部内容。"); + } + catch (Exception exception) when (!files.Published.IsDefaultOrEmpty) + { + committed = new(InstallResultStatus.PartialFailure, files.Published, plan.Singers, + [new("install.partial", exception.Message)]); + } + finally + { + files.CanPublish = false; + await FinishAsync(); + } + return committed; + }, token); + try + { + await ServiceHub.FlushFileSystemAsync(); + progress.Report(new(InstallPhase.Refreshing, "")); + await SingerDiscoveryService.Instance.RefreshAsync(); + foreach (SingerReference singer in result.Singers.IsDefault ? [] : result.Singers) + { + ImmutableArray matches = await context.InstalledSingers.FindAsync(singer, CancellationToken.None); + if (matches.All(item => item.Availability != SingerAvailability.Ready)) + result = AddFailure(result, "install.not-discovered", $"已安装,但读取失败:{singer.SingerId}"); + } + } + catch (Exception exception) { result = AddFailure(result, "install.refresh-failed", exception.Message); } + return result; + }); + + private static InstallResult AddFailure(InstallResult result, string code, string message) => result with + { + Status = InstallResultStatus.PartialFailure, + Diagnostics = (result.Diagnostics.IsDefault ? ImmutableArray.Empty : result.Diagnostics).Add(new(code, message)), + }; + + private void RequireSubmission(InstallSubmission submission) + { + if (View == null || session == null || submission.ExpectedRevision != View.Revision || submission.StepId != View.CurrentStepId) + throw new SingerInstallException("install.stale-view", "安装步骤已变化,请重新检查输入。"); + } + + private InstallView Accept(InstallView view) + { + if (view.Steps.IsDefaultOrEmpty || view.Steps.Select(item => item.Id).Distinct().Count() != view.Steps.Length || + !view.Steps.Any(item => item.Id == view.CurrentStepId) || (View != null && view.Revision <= View.Revision)) + throw new SingerInstallException("install.invalid-view", "安装器返回了无效步骤。"); + foreach (InstallStep step in view.Steps) + { + if (string.IsNullOrWhiteSpace(step.Id) || string.IsNullOrWhiteSpace(step.Title)) + throw new SingerInstallException("install.invalid-step", "安装步骤缺少标识或名称。"); + SingerPluginRegistration.ValidateFields(step.Fields.IsDefault ? [] : step.Fields); + } + View = view; + return view; + } + + private async Task RunAsync(Func> operation) + { + await gate.WaitAsync(lifetime.Token); + try + { + ObjectDisposedException.ThrowIf(finished, this); + return await Task.Run(() => operation(lifetime.Token)); + } + finally { gate.Release(); } + } + + private async Task FinishAsync() + { + if (finished) return; + finished = true; + try { if (session != null) await session.DisposeAsync(); } + catch (Exception exception) { Log.Warning(exception, "Failed to dispose singer installation session"); } + finally { files.Cleanup(); } + } + + /// 发出取消后等待正在执行的插件操作返回,不并发删除缓存。 + public ValueTask DisposeAsync() + { + lock (gate) return new(closing ??= CloseAsync()); + } + + private async Task CloseAsync() + { + lifetime.Cancel(); + await gate.WaitAsync(); + try { await FinishAsync(); } + finally { gate.Release(); } + } + + private sealed class InstalledLookup : IInstalledSingerLookup + { + public ValueTask> FindAsync(SingerReference singer, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + return ValueTask.FromResult(SingerDiscoveryService.Instance.Candidates + .Where(item => item.ProviderId == singer.ProviderId && item.Entry.Singer?.Id == singer.SingerId) + .Select(item => new InstalledSingerLocation(singer, item.Entry.Location, item.Entry.Availability)).ToImmutableArray()); + } + } + } +} diff --git a/OpenUtauMobile/Services/SingerPlugins/PluginWebSettingsService.cs b/OpenUtauMobile/Services/SingerPlugins/PluginWebSettingsService.cs new file mode 100644 index 00000000..d5383b49 --- /dev/null +++ b/OpenUtauMobile/Services/SingerPlugins/PluginWebSettingsService.cs @@ -0,0 +1,69 @@ +using System; +using System.IO; +using System.Linq; +using System.Reflection.Metadata; +using System.Reflection.PortableExecutable; +using System.Threading; +using System.Threading.Tasks; +using OpenUtau.Core; +using OpenUtauMobile.Plugin.Abstractions; +using Serilog; + +namespace OpenUtauMobile.Services.SingerPlugins; + +/// 按插件隔离存储;只在用户打开页面时创建插件网页会话。 +public static class PluginWebSettingsService +{ + /// 插件 ID 直接作为独占目录名,不迁移或读取旧哈希目录。 + public static PluginStorageContext Storage(string pluginId) + { + SingerPluginContract.ValidatePluginId(pluginId); + return new(Path.Combine(PathManager.Inst.DataPath, "PluginData", pluginId)); + } + + /// 按模块标识映射已登记的插件,支持移动端映射路径及内存加载,不加载未激活的 DLL。 + public static RegisteredSingerPlugin? FindPlugin(string relativePath) + { + string path = Path.GetFullPath(Path.Combine(PathManager.Inst.PluginsPath, relativePath)); + try + { + using FileStream stream = File.OpenRead(path); + using PEReader pe = new(stream); + if (!pe.HasMetadata) return null; + MetadataReader metadata = pe.GetMetadataReader(); + Guid moduleId = metadata.GetGuid(metadata.GetModuleDefinition().Mvid); + return SingerPluginService.Registry.Snapshot.Instances.Values.FirstOrDefault(plugin => + !plugin.Assembly.IsDynamic && plugin.Assembly.ManifestModule.ModuleVersionId == moduleId); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or BadImageFormatException) + { + Log.Debug(exception, "Failed to identify loaded plugin {Plugin}", relativePath); + return null; + } + } + + private static PluginWebSettingsContext Context(string pluginId) => new(Storage(pluginId), new SingerPluginRuntime.PluginLog(pluginId)); + + /// 查询当前声明,不缓存登记时的能力状态。 + public static ValueTask QueryAsync(RegisteredSingerPlugin plugin, CancellationToken token) => + plugin.Instance.GetWebSettingsAsync(Context(plugin.PluginId), token); + + /// 再次查询后打开,处理查询与点击之间能力改变的情况。 + public static async Task OpenAsync(RegisteredSingerPlugin plugin, CancellationToken token) + { + PluginWebSettingsContext context = Context(plugin.PluginId); + if (await plugin.Instance.GetWebSettingsAsync(context, token) == null) + throw new InvalidOperationException(Helpers.L.S("PluginWebSettings.Unavailable")); + Directory.CreateDirectory(context.Storage.DataDirectory); + IPluginWebSettingsSession session = await plugin.Instance.OpenWebSettingsAsync(context, token); + try + { + token.ThrowIfCancellationRequested(); + if (session.Address is not { IsAbsoluteUri: true } address || + (address.Scheme != Uri.UriSchemeHttp && address.Scheme != Uri.UriSchemeHttps)) + throw new InvalidOperationException(Helpers.L.S("PluginWebSettings.InvalidAddress")); + return session; + } + catch { await session.DisposeAsync(); throw; } + } +} diff --git a/OpenUtauMobile/Services/SingerPlugins/SingerDeletionService.cs b/OpenUtauMobile/Services/SingerPlugins/SingerDeletionService.cs new file mode 100644 index 00000000..f1de7a2f --- /dev/null +++ b/OpenUtauMobile/Services/SingerPlugins/SingerDeletionService.cs @@ -0,0 +1,45 @@ +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using OpenUtau.Core.Ustx; +using OpenUtauMobile.Plugin.Abstractions; +using Serilog; + +namespace OpenUtauMobile.Services.SingerPlugins +{ + /// 提供方控制删除范围,宿主只校验归属并协调发现刷新。 + public static class SingerDeletionService + { + /// 按实例或稳定身份及位置找到当前条目。 + public static SingerCandidate? Find(USinger singer) => SingerDiscoveryService.Instance.Candidates.FirstOrDefault(item => + ReferenceEquals(item.Entry.Singer, singer) || (item.Entry.Singer?.Id == singer.Id + && item.Entry.Singer?.SingerType == singer.SingerType && item.Entry.Location == singer.Location)); + + /// 取得刷新后的同一位置,不能把重复 ID 的另一个位置当作删除目标。 + public static SingerCandidate? Current(SingerCandidate candidate) => SingerDiscoveryService.Instance.Candidates.FirstOrDefault(item => + item.ProviderId == candidate.ProviderId && item.Entry.Location == candidate.Entry.Location); + + /// 绑定阶段隔离提供方错误,不因能力查询失败使详情页面崩溃。 + public static bool CanDelete(SingerCandidate candidate) + { + try + { + return SingerPluginService.Registry.Snapshot.Providers.TryGetValue(candidate.ProviderId, out RegisteredSingerProvider? provider) + && provider.Instance.CanDelete(candidate.Entry); + } + catch (Exception exception) { Log.Warning(exception, "Failed to query singer deletion capability {Provider}", candidate.ProviderId); return false; } + } + + /// 执行前重新查询条目和权限,成功、失败或取消后均刷新目录。 + public static async Task DeleteAsync(SingerCandidate candidate, CancellationToken cancellationToken = default) + { + SingerCandidate current = Current(candidate) ?? throw new InvalidOperationException("歌手条目已改变,请刷新列表。"); + if (!CanDelete(current) || !SingerPluginService.Registry.Snapshot.Providers.TryGetValue(current.ProviderId, out RegisteredSingerProvider? provider)) + throw new InvalidOperationException("此歌手不允许删除。"); + await SingerDiscoveryService.Instance.MaintainAsync(() => Task.Run(async () => + await provider.Instance.DeleteAsync(current.Entry, new SingerDeletionContext(SingerPluginRuntime.Roots(), + new SingerPluginRuntime.PluginLog(provider.PluginId)), cancellationToken), cancellationToken)); + } + } +} diff --git a/OpenUtauMobile/Services/SingerPlugins/SingerDiscoveryService.cs b/OpenUtauMobile/Services/SingerPlugins/SingerDiscoveryService.cs new file mode 100644 index 00000000..724aa183 --- /dev/null +++ b/OpenUtauMobile/Services/SingerPlugins/SingerDiscoveryService.cs @@ -0,0 +1,244 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using System.Runtime.CompilerServices; +using Avalonia.Threading; +using OpenUtau.Classic; +using OpenUtau.Core; +using OpenUtau.Core.Ustx; +using OpenUtau.Core.Render; +using OpenUtau.Core.Vogen; +using OpenUtauMobile.Plugin.Abstractions; +using Serilog; + +namespace OpenUtauMobile.Services.SingerPlugins +{ + /// 保留提供方归属的发现候选,用于卸载及安装定位。 + public sealed record SingerCandidate(string ProviderId, SingerDiscoveryEntry Entry); + + /// 串行发现、合并和发布歌手;工程引用更新后才释放被替换实例。 + public sealed class SingerDiscoveryService : ICmdSubscriber + { + public static SingerDiscoveryService Instance { get; } = new(); + private readonly SemaphoreSlim gate = new(1, 1); + private ImmutableArray candidates = []; + private bool subscribed; + private long legacyGeneration; + private readonly ConditionalWeakTable providerInstances = new(); + /// 仅供卸载及安装定位使用的内部发现快照,不向管理页发布诊断条目。 + internal ImmutableArray Candidates => candidates; + /// 仅在最终目录和工程引用都已更新后触发。 + public event Action? Changed; + + /// 在 Core 初始化后接入旧通知;新调用方直接等待 RefreshAsync。 + public void Initialize() + { + if (subscribed) return; + subscribed = true; + DocManager.Inst.AddSubscriber(this); + } + + /// 目录维护与扫描互斥,无论维护成功与否都重新发布目录。 + internal async Task MaintainAsync(Func operation) + { + await gate.WaitAsync(); + try { await operation(); } + finally + { + gate.Release(); + await RefreshAsync(); + } + } + + /// 提交期间阻止扫描看见尚未发布完整的目标卷暂存内容。 + internal async Task WithCatalogLockAsync(Func> operation, CancellationToken cancellationToken) + { + await gate.WaitAsync(cancellationToken); + try { return await operation(); } + finally { gate.Release(); } + } + + /// 扫描不修改公共目录,所有变更在 UI 线程一次性发布。 + public async Task RefreshAsync(CancellationToken cancellationToken = default, bool scanBuiltins = true) + { + await gate.WaitAsync(cancellationToken); + List owned = []; + List offered = []; + try + { + long generation = Interlocked.Read(ref legacyGeneration); + HashSet previous = await Dispatcher.UIThread.InvokeAsync(() => + SingerManager.Inst.Singers.Values.ToHashSet(ReferenceEqualityComparer.Instance)); + SingerPluginSnapshot registry = SingerPluginService.Registry.Snapshot; + ImmutableArray roots = SingerPluginRuntime.Roots(); + List found = scanBuiltins + ? await Task.Run(() => ClassicSingerLoader.FindAllSingers().Concat(VogenSingerLoader.FindAllSingers()).ToList(), cancellationToken) + : await Dispatcher.UIThread.InvokeAsync(() => SingerManager.Inst.Singers.Values + .Where(singer => !providerInstances.TryGetValue(singer, out _)).ToList()); + if (scanBuiltins) owned.AddRange(found); + List entries = []; + foreach (RegisteredSingerProvider provider in registry.Providers.Values.OrderBy(item => item.Id, StringComparer.Ordinal)) + { + cancellationToken.ThrowIfCancellationRequested(); + SingerPluginRuntime.PluginLog log = new(provider.PluginId); + try + { + CultureInfo culture = CultureInfo.CurrentUICulture; + SingerDiscoveryResult result = await Task.Run(async () => + { + SingerDiscoveryContext context = new(roots, culture, SingerPluginRuntime.Storage(provider.PluginId), log); + return await provider.Instance.DiscoverAsync(context, new Progress(), cancellationToken); + }, cancellationToken); + foreach (SingerDiscoveryEntry entry in result.Entries.IsDefault ? [] : result.Entries) + { + try + { + SingerDiscoveryEntry checkedEntry = entry; + if (entry.Singer is { } singer) + { + bool seen = providerInstances.TryGetValue(singer, out _) || previous.Contains(singer); + if (!seen) { owned.Add(singer); offered.Add(singer); } + bool validType = registry.TypesByBridge.TryGetValue(singer.SingerType, out RegisteredSingerType? type) + && provider.SingerTypeIds.Contains(type.Descriptor.Id); + bool invalidReady = entry.Availability == SingerAvailability.Ready && + (type?.Descriptor.IsAvailable != true || !singer.Found || !RendererReady(singer)); + if (seen || !validType || string.IsNullOrWhiteSpace(singer.Id) || + invalidReady) + { + log.Write(new("discovery.invalid-singer", "歌手实例或渲染器不可用。", Location: entry.Location)); + checkedEntry = entry with + { + Singer = null, + Availability = SingerAvailability.Unavailable + }; + } + else if (entry.Availability == SingerAvailability.Ready) found.Add(singer); + } + else if (entry.Availability == SingerAvailability.Ready) + { + log.Write(new("discovery.missing-singer", "未返回歌手实例。", Location: entry.Location)); + checkedEntry = entry with + { + Availability = SingerAvailability.Invalid + }; + } + entries.Add(new(provider.Id, checkedEntry)); + } + catch (Exception exception) + { + PluginDiagnostic diagnostic = new("discovery.invalid-entry", exception.Message, Location: entry.Location); + log.Write(diagnostic, exception); + entries.Add(new(provider.Id, entry with + { + Singer = null, + Availability = SingerAvailability.Invalid + })); + } + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } + catch (Exception exception) + { + PluginDiagnostic diagnostic = new("discovery.failed", exception.Message, Location: provider.Id); + log.Write(diagnostic, exception); + } + } + cancellationToken.ThrowIfCancellationRequested(); + await Dispatcher.UIThread.InvokeAsync(() => + { + cancellationToken.ThrowIfCancellationRequested(); + if (generation != Interlocked.Read(ref legacyGeneration)) return; + Publish(found, entries, scanBuiltins); + }); + } + finally + { + // 取消或失败时也释放新实例,但不能触碰仍在公共目录里的旧实例。 + HashSet retained = await Dispatcher.UIThread.InvokeAsync(() => + SingerManager.Inst.Singers.Values.ToHashSet(ReferenceEqualityComparer.Instance)); + foreach (USinger singer in offered) + providerInstances.GetValue(singer, _ => new object()); + foreach (USinger singer in owned.Distinct(ReferenceEqualityComparer.Instance)) + { + if (!retained.Contains(singer)) DisposeSinger(singer); + } + gate.Release(); + } + } + + private static bool RendererReady(USinger singer) + { + try + { + string[] renderers = SingerPluginService.Registry.GetSupportedRenderers(singer.SingerType); + return renderers.Length > 0 && renderers.All(id => Renderers.GetOrCreate(id)?.SingerType == singer.SingerType); + } + catch { return false; } + } + + /// 合并按 ID 保留首个,重复项沿用现有警告通知。 + private void Publish(List found, List entries, bool refreshLegacy) + { + USinger[] old = SingerManager.Inst.Singers.Values.ToArray(); + Dictionary next = found.GroupBy(item => item.Id, StringComparer.Ordinal) + .ToDictionary(group => group.Key, group => group.First(), StringComparer.Ordinal); + SingerManager.Inst.Singers.Clear(); + foreach (KeyValuePair item in next) SingerManager.Inst.Singers.Add(item.Key, item.Value); + SingerManager.Inst.SingerGroups.Clear(); + foreach (IGrouping group in next.Values.GroupBy(item => item.SingerType)) + SingerManager.Inst.SingerGroups.Add(group.Key, group.OrderBy(item => item.LocalizedName, StringComparer.CurrentCulture).ToList()); + if (refreshLegacy) + { + ExternalSingerPluginService.RefreshSingers(); + next = SingerManager.Inst.Singers.ToDictionary(item => item.Key, item => item.Value, StringComparer.Ordinal); + } + // 插件程序集错误由启动错误通知展示,不能伪装成不可用歌手占据管理列表。 + foreach (UTrack track in DocManager.Inst.Project.tracks) + { + string? id = track.Singer?.Id ?? track.singer; + if (string.IsNullOrWhiteSpace(id)) continue; + if (next.TryGetValue(id, out USinger? replacement)) track.Singer = replacement; + else + { + if (track.Singer?.Found == true) track.Singer = new UnavailableSinger(id, track.Singer.Name, track.Singer.SingerType); + } + } + candidates = [.. entries]; + HashSet retained = next.Values.ToHashSet(ReferenceEqualityComparer.Instance); + try { DocManager.Inst.ExecuteCmd(new SingersRefreshedNotification()); } + finally { foreach (USinger singer in old) if (!retained.Contains(singer)) DisposeSinger(singer); } + foreach (IGrouping group in found.GroupBy(item => item.Id).Where(group => group.Count() > 1)) + DocManager.Inst.ExecuteCmd(new WarningNotification($"singers.duplicate:{group.Key}", + "warnings.singers.duplicate", "warnings.singers.duplicate.detail", group.Key, + group.First().Location, string.Join("\n", group.Skip(1).Select(item => item.Location)))); + foreach (Delegate handler in Changed?.GetInvocationList() ?? []) + try { ((Action)handler)(); } + catch (Exception exception) { Log.Warning(exception, "Failed to update singer discovery consumer"); } + } + + private static void DisposeSinger(USinger singer) + { + try { (singer as IDisposable)?.Dispose(); } + catch (Exception exception) { Log.Warning(exception, "Failed to dispose singer instance {SingerType}", singer.GetType().FullName); } + } + + public void OnNext(UCommand cmd, bool isUndo) + { + if (cmd is SingersChangedNotification) + { + Interlocked.Increment(ref legacyGeneration); + _ = AdaptLegacyRefreshAsync(); + } + } + + private async Task AdaptLegacyRefreshAsync() + { + try { await RefreshAsync(scanBuiltins: false); } + catch (Exception exception) { Log.Error(exception, "Failed to refresh singer providers"); } + } + } +} diff --git a/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistration.cs b/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistration.cs new file mode 100644 index 00000000..16b00296 --- /dev/null +++ b/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistration.cs @@ -0,0 +1,266 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection; +using OpenUtau.Core.Render; +using OpenUtau.Core.Ustx; +using OpenUtauMobile.Plugin.Abstractions; + +namespace OpenUtauMobile.Services.SingerPlugins +{ + /// 短生命周期登记收集器;关闭后拒绝插件保留引用继续追加。 + internal sealed class SingerPluginRegistration : ISingerPluginRegistrar + { + private readonly SingerPluginDescriptor plugin; + private readonly Assembly assembly; + private readonly Dictionary types = new(StringComparer.Ordinal); + private readonly Dictionary providers = new(StringComparer.Ordinal); + private readonly Dictionary installers = new(StringComparer.Ordinal); + private readonly int registrationThread = Environment.CurrentManagedThreadId; + private bool closed; + + internal IReadOnlyCollection Types => types.Values; + internal IReadOnlyCollection Providers => providers.Values; + internal IReadOnlyCollection Installers => installers.Values; + + internal SingerPluginRegistration(SingerPluginDescriptor plugin, Assembly assembly) + { + SingerPluginContract.ValidatePluginId(plugin.Id); + RequireText(plugin.DisplayName, "插件名称"); + this.plugin = plugin; + this.assembly = assembly; + } + + /// 固定类型描述;值类型集合不会随插件后续代码改变。 + public void RegisterSingerType(SingerTypeDescriptor descriptor) + { + RequireOpen(); + ArgumentNullException.ThrowIfNull(descriptor); + RequireOwnedId(descriptor.Id); + RequireText(descriptor.DisplayName, "类型名称"); + if ((int)descriptor.BridgeValue < SingerPluginContract.ExternalTypeMinimum) + { + throw new InvalidOperationException($"类型 {descriptor.Id} 的桥接值不在外部区间。"); + } + descriptor = descriptor with + { + RendererIds = OrEmpty(descriptor.RendererIds), + LocalizedNames = descriptor.LocalizedNames?.WithComparers(StringComparer.OrdinalIgnoreCase), + }; + Add(types, descriptor.Id, new(plugin.Id, descriptor)); + } + + /// 捕获提供方身份,不在登记阶段扫描声库。 + public void RegisterProvider(ISingerProvider provider) + { + RequireOpen(); + ArgumentNullException.ThrowIfNull(provider); + string id = provider.Id; + RequireOwnedId(id); + Add(providers, id, new(plugin.Id, id, OrEmpty(provider.SingerTypeIds), provider)); + } + + /// 捕获文件选择器描述,允许不同安装器使用相同后缀。 + public void RegisterInstaller(ISingerPackageInstaller installer) + { + RequireOpen(); + ArgumentNullException.ThrowIfNull(installer); + SingerInstallerDescriptor descriptor = installer.Descriptor + ?? throw new InvalidOperationException("安装器缺少描述。"); + RequireOwnedId(descriptor.Id); + RequireText(descriptor.DisplayName, "安装器名称"); + ImmutableArray extensions = OrEmpty(descriptor.Extensions); + if (extensions.IsEmpty || extensions.Any(extension => !IsValidExtension(extension))) + { + throw new InvalidOperationException($"安装器 {descriptor.Id} 的文件后缀无效。"); + } + descriptor = descriptor with + { + Extensions = extensions.Select(extension => extension.ToLowerInvariant()).Distinct(StringComparer.Ordinal).ToImmutableArray(), + SingerTypeIds = OrEmpty(descriptor.SingerTypeIds), + MimeTypes = OrEmpty(descriptor.MimeTypes), + }; + foreach (string mime in descriptor.MimeTypes) + { + RequireText(mime, "MIME 类型"); + if (!mime.Contains('/') || mime.Any(char.IsWhiteSpace)) + { + throw new InvalidOperationException($"无效的 MIME 类型:{mime}"); + } + } + Add(installers, descriptor.Id, new(plugin.Id, descriptor, installer)); + } + + internal void Close() => closed = true; + + /// 校验整批引用与工厂;允许先登记提供方再登记类型。 + internal void Validate() + { + RequireDistinct(types.Values.Select(type => type.Descriptor.BridgeValue), "类型桥接值"); + foreach (RegisteredSingerType type in types.Values) + { + ValidateRenderers(type.Descriptor); + } + foreach (RegisteredSingerProvider provider in providers.Values) + { + ValidateTypeReferences(provider.SingerTypeIds, provider.Id); + } + foreach (RegisteredSingerInstaller installer in installers.Values) + { + ValidateTypeReferences(installer.Descriptor.SingerTypeIds, installer.Descriptor.Id); + } + } + + /// Core 默认选择不能被宿主描述覆盖,因此登记时要求二者一致。 + private void ValidateRenderers(SingerTypeDescriptor type) + { + RequireDistinct(type.RendererIds, "渲染器 ID"); + if (!type.IsAvailable) + { + RequireText(type.UnavailableReason, "不可用原因"); + if (!type.RendererIds.IsEmpty || type.DefaultRendererId != null) + { + throw new InvalidOperationException($"不可用类型 {type.Id} 不能声明可选渲染器。"); + } + return; + } + if (type.RendererIds.IsEmpty || type.DefaultRendererId == null || !type.RendererIds.Contains(type.DefaultRendererId)) + { + throw new InvalidOperationException($"类型 {type.Id} 缺少有效默认渲染器。"); + } + string[] coreIds = Renderers.GetSupportedRenderers(type.BridgeValue); + if (!coreIds.ToHashSet(StringComparer.Ordinal).SetEquals(type.RendererIds) + || Renderers.GetDefaultRenderer(type.BridgeValue) != type.DefaultRendererId) + { + throw new InvalidOperationException($"类型 {type.Id} 的渲染器声明与 Core 工厂或默认顺序不一致。"); + } + foreach (string id in type.RendererIds) + { + RequireText(id, "渲染器 ID"); + IRenderer renderer = Renderers.GetOrCreate(id) + ?? throw new InvalidOperationException($"无法创建渲染器 {id}。"); + if (renderer.SingerType != type.BridgeValue || renderer.GetType().Assembly != assembly) + { + throw new InvalidOperationException($"渲染器 {id} 的类型值或所属程序集与插件不一致。"); + } + } + } + + private void ValidateTypeReferences(ImmutableArray ids, string owner) + { + if (ids.IsEmpty || ids.Any(id => id == null || !types.ContainsKey(id))) + { + throw new InvalidOperationException($"{owner} 必须引用本插件已登记的歌手类型。"); + } + RequireDistinct(ids, "引用类型 ID"); + } + + private void RequireOwnedId(string id) + { + RequireId(id); + if (!id.StartsWith(plugin.Id + ":", StringComparison.Ordinal) || id.Length == plugin.Id.Length + 1) + { + throw new InvalidOperationException($"能力 ID {id} 必须位于 {plugin.Id}: 命名空间。"); + } + } + + private void RequireOpen() + { + if (closed || Environment.CurrentManagedThreadId != registrationThread) + { + throw new InvalidOperationException("只能在 Register 的同步调用范围内登记能力。"); + } + } + + private static void RequireId(string id) + { + if (string.IsNullOrEmpty(id) || id.Length > 160 || !char.IsAsciiLetterLower(id[0]) + || id.Any(character => !char.IsAsciiLetterLower(character) && !char.IsAsciiDigit(character) + && character is not '.' and not '-' and not '_' and not ':')) + { + throw new InvalidOperationException($"无效的稳定 ID:{id}"); + } + } + + private static void RequireText(string? text, string name) + { + if (string.IsNullOrWhiteSpace(text)) + { + throw new InvalidOperationException($"{name} 不能为空。"); + } + } + + private static void RequireDistinct(IEnumerable values, string name) + { + HashSet seen = []; + foreach (T value in values) + { + if (!seen.Add(value)) + { + throw new InvalidOperationException($"{name} 重复:{value}"); + } + } + } + + private static void Add(Dictionary items, string id, T value) + { + if (!items.TryAdd(id, value)) + { + throw new InvalidOperationException($"同批能力 ID 重复:{id}"); + } + } + + private static ImmutableArray OrEmpty(ImmutableArray items) => items.IsDefault ? [] : items; + + private static bool IsValidExtension(string extension) + { + return !string.IsNullOrWhiteSpace(extension) && extension.StartsWith('.') + && extension[1..].Split('.').All(part => part.Length > 0 && part.All(char.IsAsciiLetterOrDigit)); + } + + /// 在注册边界拒绝无法由宿主表单表达的字段描述。 + internal static void ValidateFields(IEnumerable fields) + { + HashSet ids = new(StringComparer.Ordinal); + foreach (PluginFieldDescriptor field in fields) + { + RequireId(field.Id); + RequireText(field.Label, "字段名称"); + if (!ids.Add(field.Id) || !Enum.IsDefined(field.Kind) || field.Minimum > field.Maximum) + { + throw new InvalidOperationException($"无效或重复的字段:{field.Id}"); + } + ImmutableArray options = OrEmpty(field.Options); + if (OrEmpty(field.FileExtensions).Any(extension => !IsValidExtension(extension))) + { + throw new InvalidOperationException($"字段 {field.Id} 包含无效文件后缀。"); + } + RequireDistinct(options.Select(option => option.Id), "选项 ID"); + foreach (PluginFieldOption option in options) + { + RequireText(option.Id, "选项 ID"); + RequireText(option.Label, "选项名称"); + } + bool valueMatches = field.DefaultValue switch + { + null => true, + PluginValue.Text => field.Kind == PluginFieldKind.Text, + PluginValue.Boolean => field.Kind == PluginFieldKind.Boolean, + PluginValue.Number number => field.Kind == PluginFieldKind.Number + && (!field.Minimum.HasValue || number.Value >= field.Minimum.Value) + && (!field.Maximum.HasValue || number.Value <= field.Maximum.Value), + PluginValue.Selection selection => field.Kind == PluginFieldKind.Selection && options.Any(option => option.Id == selection.Value), + PluginValue.MultipleSelection selection => field.Kind == PluginFieldKind.MultipleSelection + && OrEmpty(selection.Values).All(value => options.Any(option => option.Id == value)), + PluginValue.Path path => path.IsDirectory ? field.Kind == PluginFieldKind.Directory : field.Kind == PluginFieldKind.File, + _ => false, + }; + if (!valueMatches || (field.Kind is PluginFieldKind.Selection or PluginFieldKind.MultipleSelection && options.IsEmpty)) + { + throw new InvalidOperationException($"字段 {field.Id} 的默认值或选项与类型不符。"); + } + } + } + } +} diff --git a/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistry.cs b/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistry.cs new file mode 100644 index 00000000..cec3d475 --- /dev/null +++ b/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistry.cs @@ -0,0 +1,125 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection; +using System.Threading; +using OpenUtau.Core.Render; +using OpenUtau.Core.Ustx; +using OpenUtauMobile.Plugin.Abstractions; + +namespace OpenUtauMobile.Services.SingerPlugins +{ + /// 持有歌手能力快照,单个插件通过全部校验后才发布登记。 + public sealed class SingerPluginRegistry + { + private readonly object gate = new(); + private SingerPluginSnapshot snapshot = CreateBuiltinSnapshot(); + + /// 不可变的当前能力目录;不会暴露尚未提交的插件。 + public SingerPluginSnapshot Snapshot => Volatile.Read(ref snapshot); + + /// 收集并提交插件;插件代码在提交锁之外执行,避免锁内回调。 + internal void Register(ISingerPlugin plugin, Assembly assembly) + { + SingerPluginDescriptor descriptor = plugin.Descriptor + ?? throw new InvalidOperationException("插件没有身份描述。"); + SingerPluginRegistration batch = new(descriptor, assembly); + try + { + plugin.Register(batch); + } + finally + { + batch.Close(); + } + batch.Validate(); + lock (gate) + { + SingerPluginSnapshot current = snapshot; + RequireUnique(current.Plugins.ContainsKey(descriptor.Id), "插件 ID", descriptor.Id); + foreach (RegisteredSingerType type in batch.Types) + { + RequireUnique(current.Types.ContainsKey(type.Descriptor.Id), "类型 ID", type.Descriptor.Id); + RequireUnique(current.TypesByBridge.ContainsKey(type.Descriptor.BridgeValue), + "类型桥接值", ((int)type.Descriptor.BridgeValue).ToString()); + } + foreach (RegisteredSingerProvider provider in batch.Providers) + { + RequireUnique(current.Providers.ContainsKey(provider.Id), "提供方 ID", provider.Id); + } + foreach (RegisteredSingerInstaller installer in batch.Installers) + { + RequireUnique(current.Installers.ContainsKey(installer.Descriptor.Id), "安装器 ID", installer.Descriptor.Id); + } + + // 所有构造都成功后才替换快照,失败不会遗留半个插件的能力。 + SingerPluginSnapshot next = new( + current.Plugins.Add(descriptor.Id, descriptor), + current.Types.AddRange(batch.Types.Select(type => new KeyValuePair(type.Descriptor.Id, type))), + current.TypesByBridge.AddRange(batch.Types.Select(type => new KeyValuePair(type.Descriptor.BridgeValue, type))), + current.Providers.AddRange(batch.Providers.Select(provider => new KeyValuePair(provider.Id, provider))), + current.Installers.AddRange(batch.Installers.Select(installer => new KeyValuePair(installer.Descriptor.Id, installer))), + current.Instances.Add(descriptor.Id, new(descriptor.Id, assembly, plugin))); + Volatile.Write(ref snapshot, next); + } + } + + /// 按已验证类型返回渲染器;不可用或未登记类型返回空数组。 + public string[] GetSupportedRenderers(USingerType bridge) + { + if (!Snapshot.TypesByBridge.TryGetValue(bridge, out RegisteredSingerType? type) || !type.Descriptor.IsAvailable) + { + return []; + } + return type.PluginId == "opum.builtin" + ? Renderers.GetSupportedRenderers(bridge).ToArray() + : type.Descriptor.RendererIds.ToArray(); + } + + /// 安全取得默认渲染器,保留 Classic 的宿主偏好。 + public string GetDefaultRenderer(USingerType bridge) + { + SingerPluginSnapshot current = Snapshot; + if (!current.TypesByBridge.TryGetValue(bridge, out RegisteredSingerType? type) || !type.Descriptor.IsAvailable) + { + return string.Empty; + } + return type.PluginId == "opum.builtin" + ? Renderers.GetDefaultRenderer(bridge) + : type.Descriptor.DefaultRendererId ?? string.Empty; + } + + private static void RequireUnique(bool exists, string kind, string id) + { + if (exists) + { + throw new InvalidOperationException($"{kind} 冲突:{id}"); + } + } + + /// 固定内置身份,不把已加载的第三方 renderer 纳入内置描述。 + private static SingerPluginSnapshot CreateBuiltinSnapshot() + { + SingerTypeDescriptor[] descriptors = + [ + new("builtin:utau", USingerType.Classic, "UTAU", + [Renderers.WORLDLINE_R, Renderers.WORLDLINE_R11, Renderers.WORLDLINE_R2, Renderers.CLASSIC], Renderers.WORLDLINE_R), + new("builtin:enunu", USingerType.Enunu, "ENUNU", [Renderers.ENUNU], Renderers.ENUNU), + new("builtin:vogen", USingerType.Vogen, "Vogen", [Renderers.VOGEN], Renderers.VOGEN), + new("builtin:diffsinger", USingerType.DiffSinger, "DiffSinger", [Renderers.DIFFSINGER], Renderers.DIFFSINGER), + new("builtin:voicevox", USingerType.Voicevox, "VOICEVOX", [Renderers.VOICEVOX], Renderers.VOICEVOX), + new("builtin:neutrino", USingerType.Neutrino, "NEUTRINO", [Renderers.NEUTRINO], Renderers.NEUTRINO), + ]; + RegisteredSingerType[] types = descriptors.Select(descriptor => new RegisteredSingerType("opum.builtin", descriptor)).ToArray(); + return new( + ImmutableDictionary.Empty.WithComparers(StringComparer.Ordinal) + .Add("opum.builtin", new("opum.builtin", "OpenUtau Mobile")), + types.ToImmutableDictionary(type => type.Descriptor.Id, StringComparer.Ordinal), + types.ToImmutableDictionary(type => type.Descriptor.BridgeValue), + ImmutableDictionary.Empty.WithComparers(StringComparer.Ordinal), + ImmutableDictionary.Empty.WithComparers(StringComparer.Ordinal), + ImmutableDictionary.Empty.WithComparers(StringComparer.Ordinal)); + } + } +} diff --git a/OpenUtauMobile/Services/SingerPlugins/SingerPluginRuntime.cs b/OpenUtauMobile/Services/SingerPlugins/SingerPluginRuntime.cs new file mode 100644 index 00000000..dd4c6683 --- /dev/null +++ b/OpenUtauMobile/Services/SingerPlugins/SingerPluginRuntime.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using Avalonia.Threading; +using OpenUtau.Core; +using OpenUtauMobile.Plugin.Abstractions; +using Serilog; + +namespace OpenUtauMobile.Services.SingerPlugins +{ + /// 发现和安装共享的宿主上下文,不依赖插件目录结构。 + internal static class SingerPluginRuntime + { + /// 对本次操作固定根目录顺序,避免设置变化影响正在执行的任务。 + internal static ImmutableArray Roots() => PathManager.Inst.SingersPaths + .Select((path, index) => new SingerRoot($"root-{index}", Path.GetFullPath(path), + string.Equals(Path.GetFullPath(path), Path.GetFullPath(PathManager.Inst.SingersInstallPath), + Installation.InstallPaths.Comparison))).ToImmutableArray(); + + /// 发现和安装提供方使用插件独占目录,自行读取持久化配置。 + internal static PluginStorageContext Storage(string pluginId) => + PluginWebSettingsService.Storage(pluginId); + + /// 复用已绑定插件身份的宿主服务,分别实现日志和用户通知接口。 + internal sealed class PluginLog(string pluginId) : IPluginLog, IPluginNotifications + { + public void Write(PluginDiagnostic diagnostic, Exception? exception = null) + { + Serilog.Events.LogEventLevel level = diagnostic.Severity switch + { + PluginDiagnosticSeverity.Error => Serilog.Events.LogEventLevel.Error, + PluginDiagnosticSeverity.Warning => Serilog.Events.LogEventLevel.Warning, + _ => Serilog.Events.LogEventLevel.Information, + }; + Log.Write(level, exception, "Plugin {PluginId}: {Code}: {Message} ({Location})", + pluginId, diagnostic.Code, diagnostic.Message, diagnostic.Location); + } + + /// 同插件同代码更新原警告,后台调用经界面队列发布。 + public void PublishWarning(PluginWarning warning) + { + ArgumentNullException.ThrowIfNull(warning); + ArgumentException.ThrowIfNullOrWhiteSpace(warning.Code); + ArgumentException.ThrowIfNullOrWhiteSpace(warning.Message); + Write(new(warning.Code, warning.Message, PluginDiagnosticSeverity.Warning)); + Dispatcher.UIThread.Post(() => + { + string name = SingerPluginService.Registry.Snapshot.Plugins.TryGetValue(pluginId, out SingerPluginDescriptor? plugin) + ? plugin.DisplayName : pluginId; + DocManager.Inst.ExecuteCmd(new WarningNotification(Key(warning.Code), "Warning.Plugin.Title", + string.IsNullOrWhiteSpace(warning.Details) ? null : "Warning.Plugin.Detail", + name, warning.Message, warning.Details ?? string.Empty)); + }); + } + + /// 问题恢复后清除当前插件的指定警告,不能清除其他插件通知。 + public void ClearWarning(string code) + { + ArgumentException.ThrowIfNullOrWhiteSpace(code); + Dispatcher.UIThread.Post(() => DocManager.Inst.ExecuteCmd(new ClearWarningsNotification(Key(code)))); + } + + /// 插件 ID 不含冒号,固定前缀确保调用方不能跨插件清除通知。 + private string Key(string code) => $"plugin:{pluginId}:{code}"; + } + } +} diff --git a/OpenUtauMobile/Services/SingerPlugins/SingerPluginService.cs b/OpenUtauMobile/Services/SingerPlugins/SingerPluginService.cs new file mode 100644 index 00000000..8e531447 --- /dev/null +++ b/OpenUtauMobile/Services/SingerPlugins/SingerPluginService.cs @@ -0,0 +1,162 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection; +using System.Reflection.Metadata; +using System.Reflection.PortableExecutable; +using System.Runtime.InteropServices; +using System.IO; +using OpenUtau.Core; +using OpenUtauMobile.Plugin.Abstractions; +using Serilog; + +namespace OpenUtauMobile.Services.SingerPlugins +{ + /// 加载版本化歌手入口,隔离失败插件,不执行发现、安装或设置操作。 + public static class SingerPluginService + { + private static readonly object gate = new(); + private static readonly HashSet attempted = []; + private static ImmutableArray diagnostics = []; + + /// 供 Mobile 各子系统读取的统一能力目录。 + public static SingerPluginRegistry Registry { get; } = new(); + + /// 登记失败的诊断快照,保留程序集位置与原始错误消息。 + public static ImmutableArray Diagnostics + { + get + { + lock (gate) + { + return diagnostics; + } + } + } + + /// 在 Core 扫描外部 DLL 前固定契约依赖的程序集身份。 + public static void EnsureContractsLoaded() + { + _ = typeof(ISingerPlugin).Assembly.GetName(); + } + + /// 在歌手首次发现及工程恢复之前调用;重复调用不会重新实例化入口。 + public static void Initialize() + { + EnsureContractsLoaded(); + foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) + { + if (!PluginActivationService.ShouldInitialize(assembly)) + { + continue; + } + lock (gate) + { + if (!attempted.Add(assembly)) + { + continue; + } + } + try + { + SingerPluginAttribute? attribute = assembly.GetCustomAttribute(); + if (attribute == null) + { + if (assembly.GetCustomAttributesData().Any(data => data.AttributeType.FullName == typeof(SingerPluginAttribute).FullName)) + { + throw new InvalidOperationException("插件使用了另一份契约程序集,请引用宿主提供的 OpenUtauMobile.Plugin.Abstractions。"); + } + continue; + } + // 必须在创建插件实例和调用任何插件方法之前验证契约版本。 + if (attribute.ContractVersion != SingerPluginContract.Version) + { + throw new NotSupportedException($"歌手插件契约版本 {attribute.ContractVersion} 不受支持,宿主版本为 {SingerPluginContract.Version}。"); + } + Type entry = attribute.EntryPoint; + if (entry.Assembly != assembly || !entry.IsVisible || entry.IsAbstract || entry.ContainsGenericParameters + || !typeof(ISingerPlugin).IsAssignableFrom(entry) || entry.GetConstructor(Type.EmptyTypes) == null) + { + throw new InvalidOperationException("歌手插件入口必须是当前程序集内实现 ISingerPlugin 的公开非抽象类型,并有公开无参构造函数。"); + } + ISingerPlugin plugin = (ISingerPlugin)Activator.CreateInstance(entry)!; + Registry.Register(plugin, assembly); + } + catch (Exception exception) + { + Exception error = exception is TargetInvocationException { InnerException: { } inner } ? inner : exception; + string location = assembly.Location; + PluginDiagnostic diagnostic = new("plugin.registration.failed", error.Message, + Location: string.IsNullOrEmpty(location) ? assembly.FullName : location); + lock (gate) + { + diagnostics = diagnostics.Add(diagnostic); + } + Log.Error(error, "Failed to initialize singer plugin {Assembly}", diagnostic.Location); + } + } + InspectUnloadedEntries(); + } + + /// 只读检查未载入的声明入口,补充启动错误通知中的依赖及位数诊断。 + private static void InspectUnloadedEntries() + { + string root = PathManager.Inst.PluginsPath; + if (!Directory.Exists(root)) return; + HashSet loaded = new(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + HashSet loadedModules = []; + foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) + { + if (assembly.IsDynamic) continue; + if (!string.IsNullOrEmpty(assembly.Location)) loaded.Add(Path.GetFullPath(assembly.Location)); + // Android 运行时可能返回映射后的 Location,模块标识仍能对应磁盘上的同一份程序集。 + loadedModules.Add(assembly.ManifestModule.ModuleVersionId); + } + try + { + EnumerationOptions options = new() { RecurseSubdirectories = true, AttributesToSkip = 0, IgnoreInaccessible = false }; + foreach (string path in Directory.EnumerateFiles(root, "*", options).Where(path => Path.GetExtension(path).Equals(".dll", StringComparison.OrdinalIgnoreCase))) + { + if (!PluginActivationService.ShouldLoadFile(path)) continue; + if (loaded.Contains(Path.GetFullPath(path))) continue; + try + { + using FileStream stream = File.OpenRead(path); + using PEReader pe = new(stream); + if (!pe.HasMetadata) continue; + MetadataReader reader = pe.GetMetadataReader(); + if (!reader.IsAssembly) continue; + if (loadedModules.Contains(reader.GetGuid(reader.GetModuleDefinition().Mvid))) continue; + bool entry = reader.GetAssemblyDefinition().GetCustomAttributes().Any(handle => + { + CustomAttribute attribute = reader.GetCustomAttribute(handle); + if (attribute.Constructor.Kind != HandleKind.MemberReference) return false; + MemberReference constructor = reader.GetMemberReference((MemberReferenceHandle)attribute.Constructor); + if (constructor.Parent.Kind != HandleKind.TypeReference) return false; + TypeReference type = reader.GetTypeReference((TypeReferenceHandle)constructor.Parent); + return reader.GetString(type.Namespace) == typeof(SingerPluginAttribute).Namespace + && reader.GetString(type.Name) == nameof(SingerPluginAttribute); + }); + if (!entry) continue; + AddLoadDiagnostic(path, $"插件程序集未能载入,请检查依赖及进程架构({RuntimeInformation.ProcessArchitecture})。"); + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException or BadImageFormatException) + { AddLoadDiagnostic(path, error.Message); } + } + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException) + { AddLoadDiagnostic(root, error.Message); } + } + + private static void AddLoadDiagnostic(string path, string message) + { + lock (gate) + { + if (diagnostics.Any(item => item.Location == path)) return; + diagnostics = diagnostics.Add(new("plugin.load.failed", message, Location: path)); + } + Log.Error("Plugin assembly unavailable: {Location}: {Message}", path, message); + } + } +} diff --git a/OpenUtauMobile/Services/SingerPlugins/SingerPluginSnapshot.cs b/OpenUtauMobile/Services/SingerPlugins/SingerPluginSnapshot.cs new file mode 100644 index 00000000..0db762aa --- /dev/null +++ b/OpenUtauMobile/Services/SingerPlugins/SingerPluginSnapshot.cs @@ -0,0 +1,30 @@ +using System.Collections.Immutable; +using OpenUtau.Core.Ustx; +using OpenUtauMobile.Plugin.Abstractions; + +namespace OpenUtauMobile.Services.SingerPlugins +{ + /// 归属明确的歌手类型;内置类型的 PluginId 固定为 opum.builtin。 + public sealed record RegisteredSingerType(string PluginId, SingerTypeDescriptor Descriptor); + + /// 登记时固定身份与类型范围的发现提供方。 + public sealed record RegisteredSingerProvider(string PluginId, string Id, + ImmutableArray SingerTypeIds, ISingerProvider Instance); + + /// 登记时固定描述的文件安装器。 + public sealed record RegisteredSingerInstaller(string PluginId, SingerInstallerDescriptor Descriptor, + ISingerPackageInstaller Instance); + + /// 已登记的插件入口,用于运行时查询 Web 设置能力。 + public sealed record RegisteredSingerPlugin(string PluginId, System.Reflection.Assembly Assembly, + ISingerPlugin Instance); + + /// 一次性发布的能力目录;消费者应持有同一快照完成查询。 + public sealed record SingerPluginSnapshot( + ImmutableDictionary Plugins, + ImmutableDictionary Types, + ImmutableDictionary TypesByBridge, + ImmutableDictionary Providers, + ImmutableDictionary Installers, + ImmutableDictionary Instances); +} diff --git a/OpenUtauMobile/Services/SingerPlugins/SingerTypePresentation.cs b/OpenUtauMobile/Services/SingerPlugins/SingerTypePresentation.cs new file mode 100644 index 00000000..42a7ae7b --- /dev/null +++ b/OpenUtauMobile/Services/SingerPlugins/SingerTypePresentation.cs @@ -0,0 +1,68 @@ +using System; +using System.Globalization; +using System.Collections.Generic; +using Avalonia.Media; +using OpenUtau.Core.Ustx; +using OpenUtauMobile.Plugin.Abstractions; +using OpenUtauMobile.Themes.OpenUtauMobile.Runtime.Resources; +using OpenUtauMobile.Themes.OpenUtauMobile.Runtime; +using ReactiveUI; + +namespace OpenUtauMobile.Services.SingerPlugins +{ + /// 统一查询类型名称与明暗主题颜色。 + public static class SingerTypePresentation + { + private static readonly Dictionary brushes = []; + + static SingerTypePresentation() + { + MessageBus.Current.Listen().Subscribe(_ => + { + foreach (KeyValuePair item in brushes) item.Value.Color = ResolveColor(item.Key); + }); + } + /// 依次使用当前语言、父语言和默认名称。 + public static string Name(USingerType bridge) + { + if (!SingerPluginService.Registry.Snapshot.TypesByBridge.TryGetValue(bridge, out RegisteredSingerType? type)) + return bridge.ToString(); + if (type.Descriptor.LocalizedNames is { } names) + for (CultureInfo culture = CultureInfo.CurrentUICulture; culture != CultureInfo.InvariantCulture; culture = culture.Parent) + if (names.TryGetValue(culture.Name, out string? name)) return name; + return type.Descriptor.DisplayName; + } + + /// 外部类型颜色作为数据颜色使用,缺省沿用未知类型语义色。 + public static IBrush Brush(USingerType bridge) + { + // 内置类型继续使用原有主题画刷,不复制颜色或改动标签前景。 + string? builtinRole = bridge switch + { + USingerType.Classic => "Classic", + USingerType.Enunu => "Enunu", + USingerType.DiffSinger => "DiffSinger", + USingerType.Vogen => "Vogen", + USingerType.Voicevox => "Voicevox", + USingerType.Neutrino => "Neutrino", + _ => null, + }; + if (builtinRole != null) return ThemeResources.GetBrush($"Sem.Color.Singer.{builtinRole}"); + if (!SingerPluginService.Registry.Snapshot.TypesByBridge.TryGetValue(bridge, out RegisteredSingerType? type) || + type.Descriptor.Color == null) return ThemeResources.GetBrush("Sem.Color.Singer.Unknown"); + if (!brushes.TryGetValue(bridge, out SolidColorBrush? brush)) brushes.Add(bridge, brush = new(ResolveColor(bridge))); + return brush; + } + + private static Color ResolveColor(USingerType bridge) + { + if (SingerPluginService.Registry.Snapshot.TypesByBridge.TryGetValue(bridge, out RegisteredSingerType? type) && + type.Descriptor.Color is SingerTypeColor color) + { + uint argb = ThemeResources.IsDarkMode ? color.DarkArgb : color.LightArgb; + return Color.FromUInt32(argb | 0xff000000); + } + return ThemeResources.GetColor("Sem.Color.Singer.Unknown"); + } + } +} diff --git a/OpenUtauMobile/Services/SingerPlugins/UnavailableSinger.cs b/OpenUtauMobile/Services/SingerPlugins/UnavailableSinger.cs new file mode 100644 index 00000000..ccbb2178 --- /dev/null +++ b/OpenUtauMobile/Services/SingerPlugins/UnavailableSinger.cs @@ -0,0 +1,23 @@ +using OpenUtau.Core.Ustx; + +namespace OpenUtauMobile.Services.SingerPlugins +{ + /// 保留无法解析歌手的工程身份,保存工程时不会丢失原 ID。 + internal sealed class UnavailableSinger(string id, string name, USingerType type) : USinger + { + public override string Id => id; + public override string Name => name; + public override USingerType SingerType => type; + + /// 修正 Core 缺失占位对象的空身份,不替换任何已找到歌手。 + internal static void PreserveReferences(UProject project) + { + foreach (UTrack track in project.tracks) + if (track.Singer is { Found: false, Id: null } singer) + { + string? identity = track.singer ?? singer.Name; + if (!string.IsNullOrWhiteSpace(identity)) track.Singer = new UnavailableSinger(identity, singer.Name, singer.SingerType); + } + } + } +} \ No newline at end of file diff --git a/OpenUtauMobile/Services/Tracks/PhonemizationStatus.cs b/OpenUtauMobile/Services/Tracks/PhonemizationStatus.cs new file mode 100644 index 00000000..a8c624ed --- /dev/null +++ b/OpenUtauMobile/Services/Tracks/PhonemizationStatus.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using Avalonia.Threading; +using OpenUtau.Core.Ustx; + +namespace OpenUtauMobile.Services.Tracks; + +/// 只在 UI 观察 Core 已有的音素结果版本,不新增后台队列或改变音素器的串行约束。 +internal sealed class PhonemizationStatus : IDisposable +{ + private readonly Func currentProject; + private readonly Action update; + private readonly DispatcherTimer timer; + private readonly HashSet batch = []; + private readonly Stopwatch elapsed = new(); + private UProject? project; + + internal PhonemizationStatus(Func currentProject, Action update) + { + this.currentProject = currentProject; + this.update = update; + timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(200) }; + timer.Tick += OnTick; + timer.Start(); + } + + /// 等待包括排队、模型初始化和远程调用;真实完成以当前片段结果版本为准。 + private void OnTick(object? sender, EventArgs args) + { + UProject? current = currentProject(); + if (!ReferenceEquals(project, current)) + { + project = current; + batch.Clear(); + elapsed.Reset(); + } + if (current == null) + { + update(0, 0, TimeSpan.Zero); + return; + } + UVoicePart[] pending = [.. current.parts.OfType().Where(part => !part.PhonemesUpToDate)]; + if (pending.Length == 0) + { + batch.Clear(); + elapsed.Reset(); + update(0, 0, TimeSpan.Zero); + return; + } + if (!elapsed.IsRunning) elapsed.Restart(); + HashSet currentParts = [.. current.parts]; + batch.RemoveWhere(part => !currentParts.Contains(part)); + batch.UnionWith(pending); + update(pending.Length, batch.Count, elapsed.Elapsed); + } + + /// 编辑器销毁后停止观察,释放片段引用。 + public void Dispose() + { + timer.Stop(); + timer.Tick -= OnTick; + batch.Clear(); + } +} diff --git a/OpenUtauMobile/Services/Tracks/TrackHeaderService.cs b/OpenUtauMobile/Services/Tracks/TrackHeaderService.cs index 2529f313..37fb5287 100644 --- a/OpenUtauMobile/Services/Tracks/TrackHeaderService.cs +++ b/OpenUtauMobile/Services/Tracks/TrackHeaderService.cs @@ -31,7 +31,8 @@ public static TrackHeaderService Inst public async Task PickSingerAsync(USinger? currentSinger = null) { if (ServiceHub.DesktopSingerPicker != null) return await ServiceHub.DesktopSingerPicker(currentSinger); - return await PopupService.Show(new SingerPickerPopup(), new SingerPickerViewModel()); + using SingerPickerViewModel picker = new(); + return await PopupService.Show(new SingerPickerPopup(), picker); } public Task PickPhonemizerAsync() => PickPhonemizerAsync(null); @@ -41,7 +42,14 @@ public static TrackHeaderService Inst try { PhonemizerPickerResult? result = await PhonemizerPickerService.PickAsync(new(CurrentName: currentName, Anchor: anchor)); - return result?.Factory?.Create(); + if (result?.Factory is not { } factory) return null; + Phonemizer? prepared = null; + await TrackPreparationService.Inst.RunAsync(async loading => + { + loading.SetIndeterminate(L.S("TrackPreparation.Phonemizer")); + prepared = await Task.Run(factory.Create); + }); + return prepared; } catch (System.Exception exception) { diff --git a/OpenUtauMobile/Services/Tracks/TrackImportService.cs b/OpenUtauMobile/Services/Tracks/TrackImportService.cs index c81b16c5..62bb4027 100644 --- a/OpenUtauMobile/Services/Tracks/TrackImportService.cs +++ b/OpenUtauMobile/Services/Tracks/TrackImportService.cs @@ -24,17 +24,20 @@ public static IReadOnlyList ReadFiles(IEnumerable pat { UProject project = Formats.ReadProject([path]) ?? throw new InvalidDataException("Empty project."); NotePhonemizerResolver.Normalize(project); + ExternalSingerPluginService.NormalizeProject(project); if (project.parts.Any(part => part.trackNo < 0 || part.trackNo >= project.tracks.Count)) { throw new InvalidDataException("Invalid source track index."); } // 来源读取在后台执行,等音频加载终止后再展示确认页,避免遗漏晚到的解码失败。 + List missingAudio = []; foreach (UWavePart part in project.parts.OfType()) { try { part.Peaks?.GetAwaiter().GetResult(); } catch (Exception) { /* 片段保留;确认页根据 Peaks 终态显示不可读提示。 */ } + if (!File.Exists(part.FilePath)) missingAudio.Add(part); } - sources.Add(new TrackImportSource(path, project)); + sources.Add(new TrackImportSource(path, project, missingAudio: missingAudio)); } catch (Exception exception) { diff --git a/OpenUtauMobile/Services/Tracks/TrackImportSource.cs b/OpenUtauMobile/Services/Tracks/TrackImportSource.cs index 72c3134f..fc4ebae2 100644 --- a/OpenUtauMobile/Services/Tracks/TrackImportSource.cs +++ b/OpenUtauMobile/Services/Tracks/TrackImportSource.cs @@ -9,17 +9,23 @@ namespace OpenUtauMobile.Services.Tracks; /// 一次读取的来源工程及其诊断;不持有当前编辑工程。 public sealed class TrackImportSource { + private readonly HashSet missingAudio; public string Path { get; } public string Name => System.IO.Path.GetFileName(Path); public UProject? Project { get; } public Exception? Error { get; } - public TrackImportSource(string path, UProject? project, Exception? error = null) + public TrackImportSource(string path, UProject? project, Exception? error = null, + IEnumerable? missingAudio = null) { Path = path; Project = project; Error = error; + this.missingAudio = [.. missingAudio ?? []]; } + + /// 使用来源读取阶段的文件状态,确认行构造时不再访问磁盘。 + public bool IsAudioMissing(UWavePart part) => missingAudio.Contains(part); } /// 确认后的轨道选择,保存来源索引,避免轨道重编号影响选择。 diff --git a/OpenUtauMobile/Services/Tracks/TrackPreparationService.cs b/OpenUtauMobile/Services/Tracks/TrackPreparationService.cs new file mode 100644 index 00000000..11776e71 --- /dev/null +++ b/OpenUtauMobile/Services/Tracks/TrackPreparationService.cs @@ -0,0 +1,127 @@ +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using Avalonia.Threading; +using OpenUtau.Api; +using OpenUtau.Core; +using OpenUtau.Core.Ustx; +using OpenUtau.Core.Util; +using OpenUtauMobile.Helpers; +using OpenUtauMobile.Services.Dialogs; +using OpenUtauMobile.ViewModels; +using ReactiveUI; +using ReactiveUI.Fody.Helpers; +using Serilog; + +namespace OpenUtauMobile.Services.Tracks; + +/// 先展示模态,再准备独立的歌手资源和音素器;活动轨道只在 UI 提交。 +public sealed class TrackPreparationService : ReactiveObject +{ + private static readonly ConditionalWeakTable SingerLocks = new(); + /// 所有轨道准备共享一个模态事务,避免重复打开同一弹窗宿主。 + public static TrackPreparationService Inst { get; } = new(); + + /// 准备及提交期间禁止编辑,后台音素化不占用此状态。 + [Reactive] public bool IsBusy { get; private set; } + + /// 拒绝重复的准备请求,异常在弹窗关闭和编辑解锁后传递。 + public async Task RunAsync(Func operation) + { + Dispatcher.UIThread.VerifyAccess(); + if (IsBusy || DocManager.Inst.HasOpenUndoGroup) return false; + IsBusy = true; + try + { + await LoadingPopupService.RunAsync(L.S("TrackPreparation.Singer"), operation); + return true; + } + finally { IsBusy = false; } + } + + /// 仅装载歌手资源,不在这里调用音素器 SetSinger;后者始终由原有后台队列串行执行。 + internal static async Task EnsureSingerAsync(USinger? singer) + { + if (singer is not { Found: true }) return; + Stopwatch watch = Stopwatch.StartNew(); + await Task.Run(() => + { + lock (SingerLocks.GetValue(singer, _ => new object())) + { + singer.EnsureLoaded(); + if (!singer.Loaded) throw new InvalidOperationException($"Failed to load singer: {singer.Name}"); + } + }); + Log.Information("轨道准备 Singer:{Milliseconds:F2} ms,{Singer}", watch.Elapsed.TotalMilliseconds, singer.Id); + } + + /// 在 UI 读取偏好;耗时构造仅作用于尚未提交的音素器实例。 + internal static async Task PrepareSingerAsync(USinger singer, LoadingPopupViewModel loading) + { + Preferences.Default.SingerPhonemizers.TryGetValue(singer.Id ?? string.Empty, out string? remembered); + await EnsureSingerAsync(singer); + loading.SetIndeterminate(L.S("TrackPreparation.Phonemizer")); + Stopwatch watch = Stopwatch.StartNew(); + Phonemizer? result = await Task.Run(() => + { + Phonemizer? prepared = TryCreate(remembered) ?? TryCreate(singer.DefaultPhonemizer); + if (singer.Found) + { + string renderer = ExternalSingerPluginService.GetDefaultRenderer(singer); + if (!string.IsNullOrEmpty(renderer)) OpenUtau.Core.Render.Renderers.GetOrCreate(renderer); + } + return prepared; + }); + Log.Information("轨道准备 Phonemizer:{Milliseconds:F2} ms", watch.Elapsed.TotalMilliseconds); + return result; + } + + /// 兼容原有默认音素器回退,但记录构造失败。 + private static Phonemizer? TryCreate(string? identifier) + { + if (string.IsNullOrWhiteSpace(identifier)) return null; + try { return PhonemizerFactory.Get(identifier)?.Create(); } + catch (Exception error) + { + Log.Error(error, "无法准备音素器 {Phonemizer}", identifier); + return null; + } + } +} + +/// 捕获会话和轨道配置,防止等待期间重载同一个工程实例后误提交。 +internal sealed class TrackPreparationOwner +{ + private readonly DocManager.SaveCheckpoint session = DocManager.Inst.CaptureSaveCheckpoint(); + private readonly UProject project; + private readonly UTrack track; + private readonly USinger? singer; + private readonly Phonemizer phonemizer; + private readonly URenderSettings settings; + private readonly string? graph; + + internal TrackPreparationOwner(UProject project, UTrack track) + { + this.project = project; + this.track = track; + singer = track.Singer; + phonemizer = track.Phonemizer; + settings = track.RendererSettings.Clone(); + graph = track.ExpressionGraph; + } + + /// 提交后配置已变化,收尾只检查原文档会话。 + internal bool IsSessionCurrent => DocManager.Inst.IsSaveCheckpointCurrent(session); + + /// 派生音素结果可更新;会话、轨道身份及用户选择的配置必须保持一致。 + internal bool IsCurrent => IsSessionCurrent && + ReferenceEquals(project, DocManager.Inst.Project) && project.tracks.Contains(track) && + ReferenceEquals(singer, track.Singer) && ReferenceEquals(phonemizer, track.Phonemizer) && + settings.renderer == track.RendererSettings.renderer && settings.resampler == track.RendererSettings.resampler && + settings.wavtool == track.RendererSettings.wavtool && graph == track.ExpressionGraph; + + /// 目录扫描替换歌手实例后,旧准备结果不再可用。 + internal static bool IsAvailable(USinger singer) => !singer.Found || + SingerManager.Inst.Singers.TryGetValue(singer.Id, out USinger? registered) && ReferenceEquals(singer, registered); +} diff --git a/OpenUtauMobile/Services/Tracks/TrackSettingsService.cs b/OpenUtauMobile/Services/Tracks/TrackSettingsService.cs index 67a61ae5..36d24bf1 100644 --- a/OpenUtauMobile/Services/Tracks/TrackSettingsService.cs +++ b/OpenUtauMobile/Services/Tracks/TrackSettingsService.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Threading.Tasks; -using Avalonia.Threading; using OpenUtau.Api; using OpenUtau.Core; using OpenUtau.Core.Ustx; @@ -23,7 +23,7 @@ private TrackSettingsService() { } public async Task ShowAsync(UTrack track) { - if (sessionOpen || !DocManager.Inst.Project.tracks.Contains(track)) return; + if (sessionOpen || TrackPreparationService.Inst.IsBusy || DocManager.Inst.HasOpenUndoGroup || !DocManager.Inst.Project.tracks.Contains(track)) return; sessionOpen = true; TrackSettingsPopupViewModel? sessionViewModel = null; try @@ -31,13 +31,29 @@ public async Task ShowAsync(UTrack track) TrackSettingsPopupViewModel viewModel = sessionViewModel = new(DocManager.Inst.Project, track); while (true) { + if (viewModel.IsStale) return; TrackSettingsAction action = await PopupService.Show(new TrackSettingsPopup(), viewModel); switch (action) { case TrackSettingsAction.PickSinger: { USinger? singer = await TrackHeaderService.Inst.PickSingerAsync(viewModel.DraftSinger); - if (singer != null) viewModel.SetSinger(singer); + if (singer != null) + { + try + { + await TrackPreparationService.Inst.RunAsync(async loading => + { + Phonemizer? prepared = await TrackPreparationService.PrepareSingerAsync(singer, loading); + if (!viewModel.IsStale && TrackPreparationOwner.IsAvailable(singer)) viewModel.SetSinger(singer, prepared); + }); + } + catch (Exception exception) + { + Serilog.Log.Error(exception, "Failed to prepare track settings singer"); + viewModel.Error = exception.Message; + } + } break; } case TrackSettingsAction.PickPhonemizer: @@ -48,8 +64,14 @@ public async Task ShowAsync(UTrack track) } case TrackSettingsAction.PickRenderer: { - string? renderer = await TrackHeaderService.Inst.PickRendererNameAsync(viewModel.Renderers.ToArray()); - if (renderer != null) viewModel.SetRenderer(renderer); + string? renderer = await TrackHeaderService.Inst.PickRendererNameAsync([.. viewModel.Renderers]); + if (renderer != null) + await TrackPreparationService.Inst.RunAsync(async loading => + { + loading.SetIndeterminate(L.S("TrackPreparation.Applying")); + await Task.Run(() => OpenUtau.Core.Render.Renderers.GetOrCreate(renderer)); + if (!viewModel.IsStale) viewModel.SetRenderer(renderer); + }); break; } case TrackSettingsAction.EditExpressions: @@ -64,7 +86,21 @@ public async Task ShowAsync(UTrack track) case TrackSettingsAction.Apply: { bool singerChanged = false; - bool applied = await Dispatcher.UIThread.InvokeAsync(() => TryApply(viewModel, out singerChanged)); + bool applied = false; + try + { + await TrackPreparationService.Inst.RunAsync(async loading => + { + await viewModel.PrepareApplyAsync(); + loading.SetIndeterminate(L.S("TrackPreparation.Applying")); + applied = TryApply(viewModel, out singerChanged); + }); + } + catch (Exception exception) + { + Serilog.Log.Error(exception, "Failed to prepare mobile track settings"); + viewModel.Error = exception.Message; + } if (applied) { if (singerChanged) @@ -110,10 +146,12 @@ private static bool TryApply(TrackSettingsPopupViewModel viewModel, out bool sin } if (commands.Count == 0) return true; DocManager manager = DocManager.Inst; + Stopwatch commit = Stopwatch.StartNew(); bool ownsUndoGroup = false; try { - manager.StartUndoGroup("TrackSettings.Apply", deferValidate: true); + // 复用 Mobile 的帧合并校验;避免全量校验在 UI 释放刚换下的歌手,令撤销时再次同步加载。 + manager.StartUndoGroup("TrackSettings.Apply"); ownsUndoGroup = true; foreach (UCommand command in commands) manager.ExecuteCmd(command); // 使用最终轨道设置校验图引用,并与设置修改一起撤销。 @@ -136,6 +174,7 @@ private static bool TryApply(TrackSettingsPopupViewModel viewModel, out bool sin ? L.S("TrackSettings.Error.Apply") : exception.Message; return false; } + Serilog.Log.Information("轨道提交 Settings:{Milliseconds:F2} ms", commit.Elapsed.TotalMilliseconds); try { SavePreferences(viewModel, singerChanged, diff --git a/OpenUtauMobile/Services/Tracks/VoiceColorMappingService.cs b/OpenUtauMobile/Services/Tracks/VoiceColorMappingService.cs index 1f0afbc2..6f2a4d19 100644 --- a/OpenUtauMobile/Services/Tracks/VoiceColorMappingService.cs +++ b/OpenUtauMobile/Services/Tracks/VoiceColorMappingService.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Threading.Tasks; +using Avalonia.Threading; using OpenUtau.Core; using OpenUtau.Core.Format; using OpenUtau.Core.Ustx; @@ -27,28 +29,35 @@ public static class VoiceColorMappingService public static async Task ValidateAsync(UProject project, UTrack? requestedTrack = null, bool validate = true) { DocManager manager = DocManager.Inst; - if (isMapping || !ReferenceEquals(manager.Project, project)) return; + if (isMapping || TrackPreparationService.Inst.IsBusy || !ReferenceEquals(manager.Project, project)) return; if (manager.HasOpenUndoGroup) throw new InvalidOperationException("An edit is still active."); - UTrack[] tracks = requestedTrack == null ? project.tracks.ToArray() : [requestedTrack]; + UTrack[] tracks = requestedTrack == null ? [.. project.tracks] : [requestedTrack]; isMapping = true; - manager.StartUndoGroup("VoiceMapping.Undo"); try { foreach (UTrack track in tracks) { if (!IsCurrent(project, track)) break; - string[] oldColors = track.VoiceColorNames.ToArray(); - string[] newColors = track.VoiceColorExp?.options ?? []; - if (!validate || track.ValidateVoiceColor(out oldColors, out newColors)) + TrackPreparationOwner owner = new(project, track); + if (track.Singer is { Found: true, Loaded: false } singer) + { + await TrackPreparationService.Inst.RunAsync(async _ => await TrackPreparationService.EnsureSingerAsync(singer)); + if (!owner.IsCurrent) return; + track.Validate(new ValidateOptions { SkipTiming = true }, project); + } + string[] oldColors = [.. track.VoiceColorNames]; + string[] newColors = [.. track.VoiceColorExp?.options ?? []]; + // 不调用会提前覆盖 VoiceColorNames 的校验方法,取消映射后保留原音色表。 + if (!validate || oldColors.Length > 1 && newColors.Length > 0 && !oldColors.SequenceEqual(newColors)) { - UVoicePart[] parts = project.parts.OfType() - .Where(part => part.trackNo == track.TrackNo && part.notes.Count > 0).ToArray(); + UVoicePart[] parts = [.. project.parts.OfType() + .Where(part => part.trackNo == track.TrackNo && part.notes.Count > 0)]; if (parts.Length > 0 && newColors.Length > 0) { VoiceColorMappingViewModel model = new(oldColors, newColors, track.TrackName); - if (await PopupService.Show(new VoiceColorMappingPopup(), model) && IsCurrent(project, track)) + if (await PopupService.Show(new VoiceColorMappingPopup(), model) && owner.IsCurrent) { - ApplyVoiceColors(project, track, parts, model); + await ApplyVoiceColorsAsync(project, track, parts, model, owner, newColors); } } else if (!validate) @@ -56,85 +65,165 @@ public static async Task ValidateAsync(UProject project, UTrack? requestedTrack ToastService.Enqueue(L.S("VoiceMapping.NoNotes")); } } - if (IsCurrent(project, track)) await RemapVocalModesAsync(project, track); + if (owner.IsCurrent) await RemapVocalModesAsync(project, track, owner); } } finally { - try - { - if (ReferenceEquals(manager.Project, project) && manager.HasOpenUndoGroup) manager.EndUndoGroup(); - } - finally - { - isMapping = false; - } + isMapping = false; } } private static bool IsCurrent(UProject project, UTrack track) => ReferenceEquals(DocManager.Inst.Project, project) && project.tracks.Contains(track); - private static void ApplyVoiceColors(UProject project, UTrack track, IEnumerable parts, - VoiceColorMappingViewModel model) + /// 在模态下分片捕获音素表达式,后台查表,最后只提交一个可撤销命令。 + private static async Task ApplyVoiceColorsAsync(UProject project, UTrack track, UVoicePart[] parts, + VoiceColorMappingViewModel model, TrackPreparationOwner owner, string[] newColors) { - foreach (UVoicePart part in parts) + Dictionary mappings = model.Mappings.ToDictionary(row => (float)row.OldIndex, row => row.SelectedIndex); + await TrackPreparationService.Inst.RunAsync(async loading => { - foreach (UPhoneme phoneme in part.phonemes) + loading.SetIndeterminate(L.S("TrackPreparation.Mapping")); + List<(UVoicePart Part, UPhoneme Phoneme, float Value)> inputs = []; + int work = 0; + foreach (UVoicePart part in parts) { - float oldValue = phoneme.GetExpression(project, track, Ustx.CLR).Item1; - VoiceColorMappingRow? mapping = model.Mappings.FirstOrDefault(row => row.OldIndex == oldValue); - if (mapping != null && mapping.OldIndex == mapping.SelectedIndex) continue; - float? value = mapping == null || mapping.SelectedIndex == DefaultIndex ? null : mapping.SelectedIndex; - DocManager.Inst.ExecuteCmd(new SetPhonemeExpressionCommand(project, track, part, phoneme, Ustx.CLR, value)); + // 后台响应可能替换派生音素列表,分片前先固定本批引用,不持有活动枚举器跨 await。 + UPhoneme[] phonemes = [.. part.phonemes]; + foreach (UPhoneme phoneme in phonemes) + { + if (!owner.IsCurrent) return; + inputs.Add((part, phoneme, phoneme.GetExpression(project, track, Ustx.CLR).Item1)); + if (++work % 128 == 0) await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Background); + } } - } + (int Index, float? Value)[] results = await Task.Run<(int Index, float? Value)[]>(() => [.. inputs.Select((input, index) => + { + bool found = mappings.TryGetValue(input.Value, out int selected); + return (Index: index, Value: found && selected != DefaultIndex ? (float?)selected : null, + Changed: !found || selected != input.Value); + }).Where(result => result.Changed).Select(result => (result.Index, result.Value))]); + if (!owner.IsCurrent) return; + List commands = []; + foreach ((int index, float? value) in results) + { + (UVoicePart part, UPhoneme phoneme, _) = inputs[index]; + if (!project.parts.Contains(part) || phoneme.Parent == null || !part.notes.Contains(phoneme.Parent)) return; + commands.Add(new SetPhonemeExpressionCommand(project, track, part, phoneme, Ustx.CLR, value)); + if (++work % 128 == 0) await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Background); + } + if (!owner.IsCurrent) return; + string[] previousColors = track.VoiceColorNames; + Commit(new VoiceMappingCommand(project, track, + () => { foreach (SetPhonemeExpressionCommand command in commands) command.Execute(); track.VoiceColorNames = newColors; }, + () => { for (int index = commands.Count - 1; index >= 0; index--) commands[index].Unexecute(); track.VoiceColorNames = previousColors; }, + rephonemize: true)); + }); } - private static async Task RemapVocalModesAsync(UProject project, UTrack track) + private static async Task RemapVocalModesAsync(UProject project, UTrack track, TrackPreparationOwner owner) { if (track.Singer?.SingerType != USingerType.DiffSinger) return; - track.Singer.EnsureLoaded(); if (!track.Singer.Loaded) return; - UVoicePart[] parts = project.parts.OfType().Where(part => part.trackNo == track.TrackNo).ToArray(); - string[] modes = parts.SelectMany(part => part.curves) + UVoicePart[] parts = [.. project.parts.OfType().Where(part => part.trackNo == track.TrackNo)]; + string[] modes = [.. parts.SelectMany(part => part.curves) .Where(curve => curve.descriptor != null && IsImportedVocalModeCurve(curve.abbr)) .Select(curve => curve.descriptor.name).Where(name => !string.IsNullOrWhiteSpace(name)) - .Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); + .Distinct(StringComparer.OrdinalIgnoreCase)]; if (modes.Length == 0) return; - string[] colors = track.Singer.Subbanks.Select(subbank => subbank.Color).ToArray(); + string[] colors = [.. track.Singer.Subbanks.Select(subbank => subbank.Color)]; if (colors.Length == 0) return; - VoiceColorMappingViewModel model = new(new[] { string.Empty }.Concat(modes).ToArray(), colors, track.TrackName, true); - if (!await PopupService.Show(new VoiceColorMappingPopup(), model) || !IsCurrent(project, track)) return; - bool changed = false; - foreach (VoiceColorMappingRow mapping in model.Mappings.Where(row => row.OldIndex > DefaultIndex && row.SelectedIndex > DefaultIndex)) + VoiceColorMappingViewModel model = new([string.Empty, .. modes], colors, track.TrackName, true); + if (!await PopupService.Show(new VoiceColorMappingPopup(), model) || !owner.IsCurrent) return; + await TrackPreparationService.Inst.RunAsync(async loading => { - string sourceName = modes[mapping.OldIndex - 1]; - UExpressionDescriptor? sourceDescriptor = project.expressions.Values.FirstOrDefault(descriptor => - descriptor.name.Equals(sourceName, StringComparison.OrdinalIgnoreCase)); - if (sourceDescriptor == null) continue; - string targetAbbr = VoiceCurvePrefix + mapping.SelectedIndex.ToString(VoiceCurveIndexFormat); - if (!project.expressions.TryGetValue(targetAbbr, out UExpressionDescriptor? targetDescriptor)) + loading.SetIndeterminate(L.S("TrackPreparation.Mapping")); + List descriptors = []; + List<(UVoicePart Part, UCurve Curve)> additions = []; + foreach (VoiceColorMappingRow mapping in model.Mappings.Where(row => row.OldIndex > DefaultIndex && row.SelectedIndex > DefaultIndex)) { - targetDescriptor = new UExpressionDescriptor($"voice color {colors[mapping.SelectedIndex]}", - targetAbbr, DefaultIndex, PercentMaximum, DefaultIndex) { type = UExpressionType.Curve }; - project.RegisterExpression(targetDescriptor); - } - foreach (UVoicePart part in parts) - { - UCurve? source = part.curves.FirstOrDefault(curve => curve.abbr == sourceDescriptor.abbr); - if (source == null || part.curves.Any(curve => curve.abbr == targetAbbr)) continue; - // 与桌面保持一致:复制曲线、归一化数值,不覆盖既有目标曲线。 - part.curves.Add(new UCurve(targetDescriptor) + string sourceName = modes[mapping.OldIndex - 1]; + UExpressionDescriptor? sourceDescriptor = project.expressions.Values.FirstOrDefault(descriptor => + descriptor.name.Equals(sourceName, StringComparison.OrdinalIgnoreCase)); + if (sourceDescriptor == null) continue; + string targetAbbr = VoiceCurvePrefix + mapping.SelectedIndex.ToString(VoiceCurveIndexFormat); + UExpressionDescriptor? targetDescriptor = descriptors.FirstOrDefault(descriptor => descriptor.abbr == targetAbbr); + if (targetDescriptor == null && !project.expressions.TryGetValue(targetAbbr, out targetDescriptor)) + { + targetDescriptor = new UExpressionDescriptor($"voice color {colors[mapping.SelectedIndex]}", + targetAbbr, DefaultIndex, PercentMaximum, DefaultIndex) { type = UExpressionType.Curve }; + descriptors.Add(targetDescriptor); + } + foreach (UVoicePart part in parts) { - xs = source.xs.ToList(), - ys = source.ys.Select(value => Math.Clamp(value <= NormalizedMaximum - ? value * PercentMaximum : value, DefaultIndex, PercentMaximum)).ToList(), - }); - changed = true; + UCurve? source = part.curves.FirstOrDefault(curve => curve.abbr == sourceDescriptor.abbr); + if (source == null || part.curves.Any(curve => curve.abbr == targetAbbr) || + additions.Any(addition => ReferenceEquals(addition.Part, part) && addition.Curve.abbr == targetAbbr)) continue; + // UI 只捕获数值快照,后台复制、归一化,不覆盖既有目标曲线。 + int[] xs = [.. source.xs]; + int[] ys = [.. source.ys]; + UCurve prepared = await Task.Run(() => new UCurve(targetDescriptor) + { + xs = [.. xs], + ys = [.. ys.Select(value => Math.Clamp(value <= NormalizedMaximum + ? value * PercentMaximum : value, DefaultIndex, PercentMaximum))], + }); + if (!owner.IsCurrent || !project.parts.Contains(part)) return; + additions.Add((part, prepared)); + } } + if (!owner.IsCurrent || additions.Count == 0) return; + Commit(new VoiceMappingCommand(project, track, + () => + { + foreach (UExpressionDescriptor descriptor in descriptors) project.RegisterExpression(descriptor); + foreach ((UVoicePart part, UCurve curve) in additions) part.curves.Add(curve); + }, + () => + { + foreach ((UVoicePart part, UCurve curve) in additions) part.curves.Remove(curve); + foreach (UExpressionDescriptor descriptor in descriptors) project.expressions.Remove(descriptor.abbr); + }, rephonemize: false)); + }); + } + + /// 等待弹窗和计算期间没有开放撤销组,提交后只触发一次合并校验。 + private static void Commit(VoiceMappingCommand command) + { + DocManager manager = DocManager.Inst; + if (manager.HasOpenUndoGroup) return; + Stopwatch commit = Stopwatch.StartNew(); + manager.StartUndoGroup("VoiceMapping.Undo"); + try { manager.ExecuteCmd(command); } + catch { manager.RollBackUndoGroup(); throw; } + finally + { + try { if (manager.HasOpenUndoGroup) manager.EndUndoGroup(); } + finally { Serilog.Log.Information("轨道提交 Mapping:{Milliseconds:F2} ms", commit.Elapsed.TotalMilliseconds); } } - if (changed) DocManager.Inst.ExecuteCmd(new ValidateProjectNotification()); + } + + /// 仅在 UI 原子地应用已准备的映射,撤销不重新运行映射计算。 + private sealed class VoiceMappingCommand : TrackCommand + { + private readonly Action apply; + private readonly Action undo; + private readonly bool rephonemize; + + internal VoiceMappingCommand(UProject project, UTrack track, Action apply, Action undo, bool rephonemize) + { + this.project = project; + this.track = track; + this.apply = apply; + this.undo = undo; + this.rephonemize = rephonemize; + } + + public override ValidateOptions ValidateOptions => new() { SkipTiming = true, SkipPhonemizer = !rephonemize }; + public override void Execute() => apply(); + public override void Unexecute() => undo(); + public override string ToString() => "Map track voice colors"; } private static bool IsImportedVocalModeCurve(string abbreviation) diff --git a/OpenUtauMobile/Themes/OpenUtauMobile/Controls/ControlThemes.axaml b/OpenUtauMobile/Themes/OpenUtauMobile/Controls/ControlThemes.axaml index b08b9fde..0155670c 100644 --- a/OpenUtauMobile/Themes/OpenUtauMobile/Controls/ControlThemes.axaml +++ b/OpenUtauMobile/Themes/OpenUtauMobile/Controls/ControlThemes.axaml @@ -60,6 +60,7 @@ + diff --git a/OpenUtauMobile/Themes/OpenUtauMobile/Controls/FloatingToolbar.axaml b/OpenUtauMobile/Themes/OpenUtauMobile/Controls/FloatingToolbar.axaml new file mode 100644 index 00000000..571e95f8 --- /dev/null +++ b/OpenUtauMobile/Themes/OpenUtauMobile/Controls/FloatingToolbar.axaml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenUtauMobile/Themes/OpenUtauMobile/Controls/FloatingToolbar.cs b/OpenUtauMobile/Themes/OpenUtauMobile/Controls/FloatingToolbar.cs new file mode 100644 index 00000000..107a3862 --- /dev/null +++ b/OpenUtauMobile/Themes/OpenUtauMobile/Controls/FloatingToolbar.cs @@ -0,0 +1,564 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Avalonia; +using Avalonia.Automation; +using Avalonia.Controls; +using Avalonia.Controls.Primitives; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Layout; +using Avalonia.Media; +using Avalonia.Styling; +using Avalonia.VisualTree; +using IconPacks.Avalonia.PhosphorIcons; +using OpenUtauMobile.Themes.OpenUtauMobile.Tokens.Components; +using OpenUtauMobile.Themes.OpenUtauMobile.Tokens.Semantic; + +namespace OpenUtauMobile.Themes.OpenUtauMobile.Controls; + +/// +/// 页内浮动操作栏。放入有限尺寸的覆盖层并拉伸至整个宿主,锚点使用宿主坐标。 +/// 操作按集合顺序排列;主面板放不下的尾部操作及固定收纳项进入溢出面板。 +/// +public sealed class FloatingToolbar : TemplatedControl +{ + /// 沿用基础按钮外观,仅为带长按命令的操作排除松手后的普通点击。 + private sealed class HoldActionButton : Button + { + private readonly FloatingToolbarAction _action; + private bool _holdTriggered; + + /// 启用平台长按识别,同时支持触屏与鼠标。 + public HoldActionButton(FloatingToolbarAction action) + { + _action = action; + SetValue(IsHoldingEnabledProperty, true); + SetValue(IsHoldWithMouseEnabledProperty, true); + Holding += OnActionHolding; + } + + protected override Type StyleKeyOverride => typeof(Button); + + protected override void OnPointerPressed(PointerPressedEventArgs e) + { + _holdTriggered = false; + // 长按开关不继承到模板或图标;捕获到按钮,确保框架在正确的目标上识别鼠标长按。 + if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) + { + e.Pointer.Capture(this); + } + base.OnPointerPressed(e); + } + + /// 长按到达阈值即执行次操作,先标记以防命令同步重建工具栏。 + private void OnActionHolding(object? sender, HoldingRoutedEventArgs e) + { + if (e.HoldingState != HoldingState.Started || !IsPressed || !IsEffectivelyEnabled || + _action.HoldCommand?.CanExecute(CommandParameter) != true) return; + _holdTriggered = true; + e.Handled = true; + _action.HoldCommand.Execute(CommandParameter); + } + + /// 一次长按只执行长按命令,普通点击继续使用 Button 的命令及状态机。 + protected override void OnClick() + { + if (_holdTriggered) + { + _holdTriggered = false; + return; + } + base.OnClick(); + } + } + + /// 按优先顺序排列的操作;替换集合以更新工具栏。 + public static readonly StyledProperty> ActionsProperty = + AvaloniaProperty.Register>(nameof(Actions), []); + + /// 需要避让的选区或目标在宿主中的矩形。 + public static readonly StyledProperty AnchorRectProperty = + AvaloniaProperty.Register(nameof(AnchorRect)); + + /// 锚点布局中的水平对齐方式,默认居中,长目标可使用左对齐贴近起点。 + public static readonly StyledProperty AnchorHorizontalAlignmentProperty = + AvaloniaProperty.Register(nameof(AnchorHorizontalAlignment), HorizontalAlignment.Center); + + /// 主面板是否只显示图标;固定纵向布局的溢出面板也遵循此设置。 + public static readonly StyledProperty IconOnlyProperty = + AvaloniaProperty.Register(nameof(IconOnly)); + + /// 使用可从顶部入口拖拽、松手贴边的纵向布局,初始位于宿主右上角。 + public static readonly StyledProperty IsFixedVerticalProperty = + AvaloniaProperty.Register(nameof(IsFixedVertical)); + + /// 纵向工具栏的独立入口,同时作为拖拽手柄。 + public static readonly StyledProperty LeadingContentProperty = + AvaloniaProperty.Register(nameof(LeadingContent)); + + /// 溢出面板的展开状态。 + public static readonly StyledProperty IsOverflowOpenProperty = + AvaloniaProperty.Register(nameof(IsOverflowOpen)); + + /// 由使用者或主题资源提供的本地化更多按钮名称。 + public static readonly StyledProperty MoreTextProperty = + AvaloniaProperty.Register(nameof(MoreText), string.Empty); + + /// 按优先顺序排列的操作。 + public IReadOnlyList Actions + { + get => GetValue(ActionsProperty); + set => SetValue(ActionsProperty, value); + } + + /// 目标在覆盖层中的矩形;位置更新不关闭已展开的面板。 + public Rect AnchorRect + { + get => GetValue(AnchorRectProperty); + set => SetValue(AnchorRectProperty, value); + } + + /// 主面板相对锚点的水平对齐方式,不影响固定纵向工具栏。 + public HorizontalAlignment AnchorHorizontalAlignment + { + get => GetValue(AnchorHorizontalAlignmentProperty); + set => SetValue(AnchorHorizontalAlignmentProperty, value); + } + + /// 主面板只显示图标。 + public bool IconOnly + { + get => GetValue(IconOnlyProperty); + set => SetValue(IconOnlyProperty, value); + } + + /// 使用可贴边拖拽的纵向布局,保留锚点布局作为默认行为。 + public bool IsFixedVertical + { + get => GetValue(IsFixedVerticalProperty); + set => SetValue(IsFixedVerticalProperty, value); + } + + /// 独立于上下文操作集合的固定入口。 + public Control? LeadingContent + { + get => GetValue(LeadingContentProperty); + set => SetValue(LeadingContentProperty, value); + } + + /// 展开或收起溢出面板。 + public bool IsOverflowOpen + { + get => GetValue(IsOverflowOpenProperty); + set => SetValue(IsOverflowOpenProperty, value); + } + + /// 更多按钮的提示与无障碍名称。 + public string MoreText + { + get => GetValue(MoreTextProperty); + set => SetValue(MoreTextProperty, value); + } + + private Border? _mainPanel; + private Border _leadingPanel = null!; + private StackPanel _mainLayout = null!; + private Border _overflowPanel = null!; + private StackPanel _mainItems = null!; + private StackPanel _overflowItems = null!; + private ToggleButton _more = null!; + private TopLevel? _inputRoot; + private bool _expandUp; + private readonly double _verticalInset = FloatingToolbarTokens.ViewportInset; + private bool _dockLeft; + private double _headTop = FloatingToolbarTokens.ViewportInset; + private IPointer? _dragPointer; + private Point _pressPosition; + private Point _pressHead; + private Point _dragHead; + private bool _isDragging; + + /// 在隧道路由中识别顶部入口拖拽,未超过阈值时保留子按钮的点击。 + public FloatingToolbar() + { + AddHandler(PointerPressedEvent, OnHeadPointerPressed, RoutingStrategies.Tunnel, true); + AddHandler(PointerMovedEvent, OnHeadPointerMoved, RoutingStrategies.Tunnel, true); + AddHandler(PointerReleasedEvent, OnHeadPointerReleased, RoutingStrategies.Tunnel, true); + } + + /// 只允许从顶部入口开始移动,操作面板不参与拖拽。 + private void OnHeadPointerPressed(object? sender, PointerPressedEventArgs e) + { + if (!IsFixedVertical || !_leadingPanel.IsVisible || _dragPointer != null || + !e.GetCurrentPoint(this).Properties.IsLeftButtonPressed || + e.Source is not Visual source || !source.GetSelfAndVisualAncestors().Contains(_leadingPanel)) return; + _dragPointer = e.Pointer; + _pressPosition = e.GetPosition(this); + _pressHead = GetLeadingPosition(Bounds.Size); + } + + /// 超过点击容差后接管捕获,坐标始终限制在当前编辑区内。 + private void OnHeadPointerMoved(object? sender, PointerEventArgs e) + { + if (_dragPointer != e.Pointer) return; + Vector delta = e.GetPosition(this) - _pressPosition; + if (!_isDragging && Math.Abs(delta.X) < 4 && Math.Abs(delta.Y) < 4) return; + if (!_isDragging) + { + _isDragging = true; + e.Pointer.Capture(this); + SetCurrentValue(IsOverflowOpenProperty, false); + } + _dragHead = ClampLeadingPosition(_pressHead + delta, Bounds.Size); + _headTop = _dragHead.Y; + InvalidateMeasure(); + e.Handled = true; + } + + /// 释放时吸附到最近的左右边缘;普通点击继续交给模式入口。 + private void OnHeadPointerReleased(object? sender, PointerReleasedEventArgs e) + { + if (_dragPointer != e.Pointer) return; + bool dragged = _isDragging; + FinishHeadDrag(); + if (dragged) e.Handled = true; + } + + /// 中断和正常释放共用贴边收尾,先清理状态以避免捕获丢失重入。 + private void FinishHeadDrag() + { + IPointer? pointer = _dragPointer; + if (_isDragging) + { + _dockLeft = _dragHead.X + _leadingPanel.DesiredSize.Width / 2 < Bounds.Width / 2; + _headTop = _dragHead.Y; + } + _dragPointer = null; + _isDragging = false; + if (pointer != null && ReferenceEquals(pointer.Captured, this)) pointer.Capture(null); + InvalidateMeasure(); + } + + /// 系统取消捕获时结束拖拽,避免工具栏继续跟随已经结束的手势。 + protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e) + { + base.OnPointerCaptureLost(e); + if (_dragPointer == e.Pointer && !ReferenceEquals(e.Pointer.Captured, this)) FinishHeadDrag(); + } + + /// 顶部入口单独约束,保证面板可根据上下剩余空间反向展开。 + private Point ClampLeadingPosition(Point position, Size viewport) + { + const double inset = FloatingToolbarTokens.ViewportInset; + return new Point( + Math.Clamp(position.X, inset, Math.Max(inset, viewport.Width - inset - _leadingPanel.DesiredSize.Width)), + Math.Clamp(position.Y, _verticalInset, + Math.Max(_verticalInset, viewport.Height - _verticalInset - _leadingPanel.DesiredSize.Height))); + } + + /// 拖拽时自由移动,其他时候保持左右标准间距。 + private Point GetLeadingPosition(Size viewport) + { + return ClampLeadingPosition(_isDragging ? _dragHead : new Point( + _dockLeft ? FloatingToolbarTokens.ViewportInset : viewport.Width - + FloatingToolbarTokens.ViewportInset - _leadingPanel.DesiredSize.Width, _headTop), viewport); + } + + /// 绑定模板中的两个面板,具体交互状态由基础按钮主题负责。 + protected override void OnApplyTemplate(TemplateAppliedEventArgs e) + { + base.OnApplyTemplate(e); + _mainPanel = e.NameScope.Get("PART_MainPanel"); + _leadingPanel = e.NameScope.Get("PART_LeadingPanel"); + _mainLayout = e.NameScope.Get("PART_MainLayout"); + _overflowPanel = e.NameScope.Get("PART_OverflowPanel"); + _mainItems = e.NameScope.Get("PART_MainItems"); + _overflowItems = e.NameScope.Get("PART_OverflowItems"); + _more = e.NameScope.Get("PART_More"); + RebuildActions(); + } + + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) + { + base.OnPropertyChanged(change); + if (_mainPanel == null) return; + if (change.Property == ActionsProperty || change.Property == IconOnlyProperty || change.Property == IsFixedVerticalProperty) + { + SetCurrentValue(IsOverflowOpenProperty, false); + RebuildActions(); + } + if (change.Property == AnchorRectProperty || change.Property == AnchorHorizontalAlignmentProperty || + change.Property == IsOverflowOpenProperty || change.Property == LeadingContentProperty) + { + InvalidateMeasure(); + } + if (change.Property == IsVisibleProperty && !IsVisible) + { + FinishHeadDrag(); + SetCurrentValue(IsOverflowOpenProperty, false); + } + } + + /// 生成主面板和溢出面板共用命令的按钮,随后由测量分配可见项。 + private void RebuildActions() + { + _mainLayout.Orientation = _mainItems.Orientation = IsFixedVertical ? Orientation.Vertical : Orientation.Horizontal; + _mainItems.Children.Clear(); + _overflowItems.Children.Clear(); + foreach (FloatingToolbarAction action in Actions) + { + _mainItems.Children.Add(CreateActionButton(action, false)); + _overflowItems.Children.Add(CreateActionButton(action, true)); + } + InvalidateMeasure(); + } + + /// 按钮直接使用 ICommand,因此两个面板同步响应 CanExecute。 + private Button CreateActionButton(FloatingToolbarAction action, bool overflow) + { + Control symbol = action.Label is { } label ? new TextBlock + { + Text = label, + FontSize = TypographyTokens.LabelSSize, + FontWeight = FontWeight.SemiBold, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center + } : new PackIconPhosphorIcons + { + Kind = action.Icon, + VerticalAlignment = VerticalAlignment.Center + }; + Button button = action.HoldCommand == null ? new Button() : new HoldActionButton(action); + button.Command = action.Command; + button.CommandParameter = action.CommandParameter; + button.Theme = (ControlTheme)this.FindResource(overflow && !IsFixedVertical + ? "OpumFloatingToolbarOverflowAction" : "OpumFloatingToolbarAction")!; + if (action.IsDanger) button.Classes.Add("danger"); + if (IconOnly && (!overflow || IsFixedVertical)) + { + button.Classes.Add("toolbarIcon"); + button.Content = symbol; + } + else + { + Grid content = new() + { + ColumnDefinitions = [new ColumnDefinition(GridLength.Auto), new ColumnDefinition(GridLength.Star)], + ColumnSpacing = overflow ? 16 : 12 + }; + TextBlock text = new() + { + Text = action.Text, + TextWrapping = TextWrapping.Wrap, + VerticalAlignment = VerticalAlignment.Center + }; + Grid.SetColumn(text, 1); + content.Children.Add(symbol); + content.Children.Add(text); + button.Content = content; + } + ToolTip.SetTip(button, action.Text); + AutomationProperties.SetName(button, action.Text); + button.Click += OnActionClick; + return button; + } + + /// 执行操作后收起溢出面板,保持选区及主面板由业务方控制。 + private void OnActionClick(object? sender, RoutedEventArgs e) + { + bool restoreFocus = IsOverflowOpen; + SetCurrentValue(IsOverflowOpenProperty, false); + if (restoreFocus) _more.Focus(); + } + + /// 按排列方向的可用长度分配操作;预留更多按钮后收纳尾部操作。 + protected override Size MeasureOverride(Size availableSize) + { + if (_mainPanel == null) return base.MeasureOverride(availableSize); + double width = Math.Max(0, availableSize.Width - FloatingToolbarTokens.ViewportInset * 2); + _leadingPanel.IsVisible = IsFixedVertical && LeadingContent != null; + _leadingPanel.Measure(availableSize); + double leadingHeight = _leadingPanel.IsVisible + ? _leadingPanel.DesiredSize.Height + _verticalInset : 0; + double height = Math.Max(0, availableSize.Height - _verticalInset * 2 - leadingHeight); + if (IsFixedVertical && _leadingPanel.IsVisible) + { + Point head = GetLeadingPosition(availableSize); + double above = Math.Max(0, head.Y - _verticalInset * 2); + double below = Math.Max(0, availableSize.Height - head.Y - leadingHeight - _verticalInset); + _expandUp = above > below; + height = _expandUp ? above : below; + } + double availableLength = IsFixedVertical ? height : width; + double requestedLength = 0; + bool hasOverflow = false; + for (int i = 0; i < Actions.Count; i++) + { + Control button = _mainItems.Children[i]; + button.IsVisible = true; + button.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); + if (Actions[i].AlwaysInOverflow) hasOverflow = true; + else requestedLength += IsFixedVertical ? button.DesiredSize.Height : button.DesiredSize.Width; + } + hasOverflow |= requestedLength > availableLength; + if (!hasOverflow) SetCurrentValue(IsOverflowOpenProperty, false); + double remaining = availableLength - (hasOverflow ? FloatingToolbarTokens.ItemSize : 0); + bool tailOverflow = false; + for (int i = 0; i < Actions.Count; i++) + { + Control button = _mainItems.Children[i]; + double length = IsFixedVertical ? button.DesiredSize.Height : button.DesiredSize.Width; + bool show = !Actions[i].AlwaysInOverflow && !tailOverflow && length <= remaining; + if (show) remaining -= length; + else if (!Actions[i].AlwaysInOverflow) tailOverflow = true; + button.IsVisible = show; + _overflowItems.Children[i].IsVisible = !show; + } + _more.IsVisible = hasOverflow; + _mainPanel.IsVisible = Actions.Count > 0; + _mainPanel.MaxWidth = width; + _mainPanel.MaxHeight = IsFixedVertical ? height : double.PositiveInfinity; + _mainPanel.Measure(availableSize); + _overflowPanel.IsVisible = hasOverflow && IsOverflowOpen; + if (_overflowPanel.IsVisible) + { + if (IsFixedVertical) + { + _overflowPanel.Width = Math.Min(width, FloatingToolbarTokens.ItemSize); + _overflowPanel.MaxHeight = Math.Max(0, availableSize.Height - FloatingToolbarTokens.ViewportInset * 2); + } + else + { + double menuWidth = Math.Min(width, FloatingToolbarTokens.OverflowMaxWidth); + _overflowItems.Measure(new Size(menuWidth, double.PositiveInfinity)); + _overflowPanel.Width = Math.Min(menuWidth, + Math.Max(FloatingToolbarTokens.OverflowMinWidth, _overflowItems.DesiredSize.Width)); + Point main = GetMainPosition(availableSize); + double above = Math.Max(0, main.Y - FloatingToolbarTokens.AnchorGap - FloatingToolbarTokens.ViewportInset); + double below = Math.Max(0, availableSize.Height - FloatingToolbarTokens.ViewportInset - + main.Y - _mainPanel.DesiredSize.Height - FloatingToolbarTokens.AnchorGap); + double requestedHeight = _overflowItems.DesiredSize.Height; + _expandUp = above >= requestedHeight || above > below; + _overflowPanel.MaxHeight = _expandUp ? above : below; + } + } + base.MeasureOverride(availableSize); + // 覆盖层本身不向父容器请求额外空间,由宿主拉伸到编辑页大小。 + return default; + } + + /// 优先放在锚点上方,不足时移至下方,最后限制在整个宿主视口内。 + private Point GetMainPosition(Size viewport) + { + Size panel = _mainPanel!.DesiredSize; + const double inset = FloatingToolbarTokens.ViewportInset; + if (IsFixedVertical) + { + Point head = GetLeadingPosition(viewport); + if (!_leadingPanel.IsVisible) return new Point(head.X, _verticalInset); + return new Point(head.X, _expandUp + ? head.Y - _verticalInset - panel.Height + : head.Y + _leadingPanel.DesiredSize.Height + _verticalInset); + } + double x = AnchorHorizontalAlignment switch + { + HorizontalAlignment.Left => AnchorRect.Left, + HorizontalAlignment.Right => AnchorRect.Right - panel.Width, + _ => AnchorRect.Center.X - panel.Width / 2 + }; + double y = AnchorRect.Top - FloatingToolbarTokens.AnchorGap - panel.Height; + if (y < inset) y = AnchorRect.Bottom + FloatingToolbarTokens.AnchorGap; + return new Point( + Math.Clamp(x, inset, Math.Max(inset, viewport.Width - inset - panel.Width)), + Math.Clamp(y, inset, Math.Max(inset, viewport.Height - inset - panel.Height))); + } + + /// 两个面板在同一个页内覆盖层中排布,不建立平台窗口或原生弹出层。 + protected override Size ArrangeOverride(Size finalSize) + { + if (_mainPanel == null) return base.ArrangeOverride(finalSize); + Point main = GetMainPosition(finalSize); + Point head = GetLeadingPosition(finalSize); + Canvas.SetLeft(_leadingPanel, head.X); + Canvas.SetTop(_leadingPanel, head.Y); + Canvas.SetLeft(_mainPanel, main.X); + Canvas.SetTop(_mainPanel, main.Y); + if (!_overflowPanel.IsVisible) return base.ArrangeOverride(finalSize); + if (IsFixedVertical) + { + bool openRight = main.X + _mainPanel.DesiredSize.Width / 2 < finalSize.Width / 2; + double overflowX = openRight ? main.X + _mainPanel.DesiredSize.Width + FloatingToolbarTokens.AnchorGap + : main.X - FloatingToolbarTokens.AnchorGap - _overflowPanel.DesiredSize.Width; + Canvas.SetLeft(_overflowPanel, Math.Clamp(overflowX, FloatingToolbarTokens.ViewportInset, + Math.Max(FloatingToolbarTokens.ViewportInset, finalSize.Width - FloatingToolbarTokens.ViewportInset - _overflowPanel.DesiredSize.Width))); + double overflowY = _expandUp ? main.Y + _mainPanel.DesiredSize.Height - _overflowPanel.DesiredSize.Height : main.Y; + Canvas.SetTop(_overflowPanel, Math.Clamp(overflowY, FloatingToolbarTokens.ViewportInset, + Math.Max(FloatingToolbarTokens.ViewportInset, finalSize.Height - FloatingToolbarTokens.ViewportInset - _overflowPanel.DesiredSize.Height))); + return base.ArrangeOverride(finalSize); + } + double x = main.X + _mainPanel.DesiredSize.Width - _overflowPanel.DesiredSize.Width; + Canvas.SetLeft(_overflowPanel, Math.Clamp(x, FloatingToolbarTokens.ViewportInset, + Math.Max(FloatingToolbarTokens.ViewportInset, finalSize.Width - + FloatingToolbarTokens.ViewportInset - _overflowPanel.DesiredSize.Width))); + Canvas.SetTop(_overflowPanel, _expandUp + ? main.Y - FloatingToolbarTokens.AnchorGap - _overflowPanel.DesiredSize.Height + : main.Y + _mainPanel.DesiredSize.Height + FloatingToolbarTokens.AnchorGap); + return base.ArrangeOverride(finalSize); + } + + protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) + { + base.OnAttachedToVisualTree(e); + _inputRoot = TopLevel.GetTopLevel(this)!; + _inputRoot.AddHandler(PointerPressedEvent, OnRootPointerPressed, RoutingStrategies.Tunnel, true); + _inputRoot.AddHandler(KeyDownEvent, OnRootKeyDown, RoutingStrategies.Tunnel, true); + } + + protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e) + { + FinishHeadDrag(); + _inputRoot!.RemoveHandler(PointerPressedEvent, OnRootPointerPressed); + _inputRoot.RemoveHandler(KeyDownEvent, OnRootKeyDown); + _inputRoot = null; + SetCurrentValue(IsOverflowOpenProperty, false); + base.OnDetachedFromVisualTree(e); + } + + /// 外部按下只收起溢出面板,不拦截原有编辑手势。 + private void OnRootPointerPressed(object? sender, PointerPressedEventArgs e) + { + if (IsOverflowOpen && e.Source is Visual source && + (!source.GetSelfAndVisualAncestors().Contains(this) || source.GetSelfAndVisualAncestors().Contains(_leadingPanel))) + { + SetCurrentValue(IsOverflowOpenProperty, false); + } + } + + /// Escape 收起菜单并将焦点还给更多按钮。 + private void OnRootKeyDown(object? sender, KeyEventArgs e) + { + if (e.Key != Key.Escape || !IsOverflowOpen) return; + SetCurrentValue(IsOverflowOpenProperty, false); + _more.Focus(); + e.Handled = true; + } + + /// 方向键在当前面板的可用操作间移动,Tab 沿用框架的焦点导航。 + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + if (e.Handled || e.Key is not (Key.Left or Key.Right or Key.Up or Key.Down)) return; + Button[] buttons = IsOverflowOpen + ? [.. _overflowItems.Children.OfType