80 コミット
作成者 SHA1 メッセージ 日付
routersys 8f18cce506 Gitea Actions のワークフローを直す 2026-11-08 13:06:41 +09:00
routersys 7e356579c3 Gitea Actions のワークフローを直す 2026-11-08 10:15:55 +09:00
routersys 7670dbbae2 過去のタグ用ワークフローを消す 2026-11-08 09:48:55 +09:00
routersys d06490303b Gitea Actions のワークフローを直す 2026-11-08 09:48:55 +09:00
routersys c07c17d027 Gitea Actions の過去のタグ用ワークフローを足す 2026-11-08 09:31:56 +09:00
routersys 0d4d110e87 Gitea Actions の過去のタグ用ワークフローを足す 2026-11-08 09:19:27 +09:00
routersys 41612b118a 過去のタグ用ワークフローを消す 2026-11-08 03:58:16 +09:00
routersys 6bb3b139f4 Gitea Actions のワークフローを直す 2026-11-08 03:56:24 +09:00
routersys fb9e1d80c8 Gitea Actions の過去のタグ用ワークフローを足す 2026-11-08 01:35:07 +09:00
routersys cd8d030173 Gitea Actions の過去のタグ用ワークフローを足す 2026-11-08 01:07:38 +09:00
routersys e0577ff7ea Gitea Actions の過去のタグ用ワークフローを足す 2026-11-07 22:36:50 +09:00
routersys 0dc17d4e6c Gitea Actions のワークフローを直す 2026-11-07 22:08:48 +09:00
routersys 157fea2578 Gitea Actions のワークフローを足す 2026-11-07 19:53:53 +09:00
routersys fd2769fba5 画像の参照先をGiteaへ移す 2026-11-07 18:22:26 +09:00
routersys 2fdb096629 サブモジュールの参照先をGiteaへ移す 2026-11-07 18:19:41 +09:00
routersys 2177b5cb38 不具合の報告の説明を送信の上限と項目と再送へ合わせる 2026-11-02 11:35:47 +09:00
routersys 11f87a31f7 READMEの数式をLaTeXで書く 2026-10-20 19:08:06 +09:00
routersys b52a7f1571 バージョンをv1.7.5へ上げる
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.7.5 のコミットから作成しました
2026-10-08 20:39:03 +09:00
routersys beaf39f6bc WorldNetをv1.2.1へ上げる 2026-10-08 20:39:03 +09:00
routersys c101cc83a7 エディターのコード規則を追加する 2026-09-26 00:36:35 +09:00
routersys 894214cd04 プルリクエストのテンプレートを追加する 2026-09-23 14:05:08 +09:00
routersys 90d3883dab Issueのテンプレートを追加する 2026-09-23 14:05:08 +09:00
routersys f398f0161f スポンサーの設定を追加する 2026-09-23 14:05:07 +09:00
routersys 446f47d1ed 貢献の手引きを追加する 2026-09-23 14:05:07 +09:00
routersys 6e6a8558f0 セキュリティポリシーを追加する 2026-09-23 14:05:06 +09:00
routersys e1c114d54b 行動規範を追加する 2026-09-23 14:05:06 +09:00
routersys 82aba9781c 送信内容の記載を実装へ合わせる 2026-09-07 15:14:59 +09:00
routersys 114bd6e6ee バージョンをv1.7.4へ上げる
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.7.4 のコミットから作成しました
2026-09-07 14:49:20 +09:00
routersys bdb843f2df 説明書を報告の範囲へ合わせる 2026-09-07 14:47:44 +09:00
routersys 1941a9c168 報告の窓口を作り取りこぼしを塞ぐ 2026-09-07 14:47:43 +09:00
routersys a55a3849f9 説明書へ不具合の報告の内容を書く 2026-09-07 14:33:09 +09:00
routersys 3ae158b1a4 不具合の報告にTelemetryを取り込む 2026-09-07 14:33:08 +09:00
routersys 50e36725a9 バージョンをv1.7.3へ上げる
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.7.3 のコミットから作成しました
2026-09-07 12:47:05 +09:00
routersys e6064d3d37 説明書へNAudioの同梱を書く 2026-09-07 12:47:05 +09:00
routersys 8078ca06b1 NAudioを同梱してYMM4の版から切り離す 2026-09-07 12:47:05 +09:00
routersys e5188f19c1 バージョンをv1.7.2へ上げる
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.7.2 のコミットから作成しました
2026-09-07 10:17:29 +09:00
routersys 7d574632f3 音声の読み取りをNAudio3系へ合わせる 2026-09-07 10:04:25 +09:00
routersys 537c0de969 バージョンをv1.7.1へ上げる
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.7.1 のコミットから作成しました
2026-08-26 12:10:57 +09:00
routersys 551e8d4620 コンテンツIDを登録 2026-08-26 12:10:10 +09:00
routersys a81e0b94b2 下方向の切り詰めを試験で固める 2026-08-23 17:43:58 +09:00
routersys 92e8aace30 別のアイテムへ貼り付けられることを固める
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.7.0 のコミットから作成しました
2026-08-23 17:21:02 +09:00
routersys 767ac2d9de 右押しの品書きに絵記号を付ける 2026-08-23 17:14:03 +09:00
routersys 7e6e78cd82 OpenUtauの表示を足し発声時間の取消を固める 2026-08-23 16:33:23 +09:00
routersys 66abdacb91 タグと版番号の食い違いでリリースを止める 2026-08-23 14:53:52 +09:00
routersys 779b6b8b0d 新しい編集操作を説明書へ書く 2026-08-23 14:53:51 +09:00
routersys 53461b59f4 バージョンをv1.7.0へ上げる 2026-08-23 14:14:02 +09:00
routersys 0fc1456b3e 選択順に依存しないことを試験で固める 2026-08-23 13:17:36 +09:00
routersys 294d3475de ノート再同期の取りこぼしと競合を塞ぐ 2026-08-23 13:17:35 +09:00
routersys 3971c60295 ノートの増減を取り消した時に編集画面を合わせる 2026-08-23 13:17:35 +09:00
routersys 7e3715d423 ノート編集を別ウィンドウへ切り離す 2026-08-23 13:17:34 +09:00
routersys d7b4bfe431 歌詞をまとめて編集する窓を足す 2026-08-23 13:17:33 +09:00
routersys 1d7644de97 ノートの右押しに一括操作の品書きを足す 2026-08-22 23:32:36 +09:00
routersys 9030fe55a8 編集面をUserControlへ切り出す 2026-08-22 23:26:56 +09:00
routersys 3fbfeaa514 選択したノートへの一括操作を足す 2026-08-22 23:21:01 +09:00
routersys 4bea943cf3 歌詞をノートへ割り当てる分割器を足す 2026-08-22 23:13:35 +09:00
routersys 1824f9faaf バージョンをv1.6.2へ合わせる
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.6.2 のコミットから作成しました
2026-08-22 19:42:23 +09:00
routersys 41b813e2bb 音程の伸ばしを句の切れ目で決める 2026-08-22 19:29:49 +09:00
routersys e1fa384f83 音程曲線の先頭の伸ばしと1点の制御点を直す 2026-08-22 19:12:16 +09:00
routersys d455ed4659 音程を句全体の曲線として組み立てる 2026-08-22 18:37:08 +09:00
routersys eb90cfd9c6 バージョンをv1.6.1へ合わせる
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.6.1 のコミットから作成しました
2026-08-22 13:40:45 +09:00
github-actions[bot] eaaebb43fe バージョンをv1.6.0へ合わせる 2026-08-22 04:36:14 +00:00
routersys 2baedff12c 先行発声を縮めた分だけ音源を読み飛ばす
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.6.0 のコミットから作成しました
2026-08-22 13:16:15 +09:00
routersys 9e114cc414 子音部を縮めず原音の速さで鳴らす 2026-08-22 12:48:35 +09:00
routersys 316b4fe1b6 音符ごとに峰値を揃える自動利得を加える 2026-08-22 12:18:36 +09:00
routersys 0a2a9a2bf6 重ね合わせの重みを振幅として掛ける 2026-08-22 11:49:53 +09:00
routersys fa1758de0d 先行発声の制限規則を規則ごとに試験する 2026-08-22 11:23:56 +09:00
routersys fe5801cefe 子音速度を先行発声と重なりへ反映する 2026-08-22 10:57:02 +09:00
routersys 63198039dc 音符の繋ぎの先行発声をUTAUの制限規則へ合わせる 2026-08-22 10:51:04 +09:00
routersys ba001e1d23 USTの短すぎる音符で拍の誤差が積み重なるのを直す 2026-08-22 10:00:25 +09:00
routersys 26d3f2007e USTの長すぎる音符で以降の拍がずれるのを直す 2026-08-22 09:56:48 +09:00
routersys 5328d1efe3 USTのDeltaとDurationの判定を1つへ揃える 2026-08-22 09:47:56 +09:00
routersys 6dc3b7f4f7 サムネイル画像の追加 2026-08-21 14:25:21 +09:00
routersys 36169bc285 説明書の見出しを内容へ合わせる 2026-08-21 14:14:40 +09:00
routersys b997849ece 訂正コミットの文言が欠けるのを直す 2026-08-21 11:03:04 +09:00
github-actions[bot] fbf5745ff7 バージョンを 2026-08-21 02:00:21 +00:00
routersys 9b9b922164 タグと版の記載が食い違うときは訂正してから発行する
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.5.0 のコミットから作成しました
2026-08-21 10:55:45 +09:00
routersys 703bb6b3a4 工具列の文言を送って全文を読めるようにする 2026-08-21 10:42:13 +09:00
routersys 5b599a7f25 説明書の版をタグから書き込む 2026-08-21 09:44:47 +09:00
routersys b4455e3252 区間の鍵を位置によらない形にする 2026-08-21 08:48:20 +09:00
routersys aca86e31b7 区間ごとの合成を並列に行う 2026-08-21 07:36:12 +09:00
83個のファイルの変更、6960行の追加、986行の削除

検索条件に一致するファイルはありません

+77
ファイルの表示
@@ -0,0 +1,77 @@
root = true
[*]
indent_style = space
indent_size = 4
tab_width = 4
end_of_line = crlf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.{json,yml,yaml}]
indent_size = 2
[*.{csproj,props,targets,vcxproj,filters,slnx,resx,xml}]
charset = unset
indent_style = unset
indent_size = unset
[*.md]
trim_trailing_whitespace = false
[*.cs]
dotnet_separate_import_directive_groups = false
dotnet_sort_system_directives_first = true
dotnet_style_qualification_for_field = false:error
dotnet_style_qualification_for_property = false:error
dotnet_style_qualification_for_method = false:error
dotnet_style_qualification_for_event = false:error
dotnet_style_predefined_type_for_locals_parameters_members = true:error
dotnet_style_predefined_type_for_member_access = true:error
dotnet_style_readonly_field = true:warning
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_object_initializer = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning
dotnet_style_operator_placement_when_wrapping = beginning_of_line
dotnet_code_quality_unused_parameters = all:warning
csharp_style_namespace_declarations = file_scoped:error
csharp_using_directive_placement = outside_namespace:error
csharp_prefer_braces = when_multiline:silent
csharp_style_var_for_built_in_types = true:silent
csharp_style_var_when_type_is_apparent = true:silent
csharp_style_var_elsewhere = true:silent
csharp_style_expression_bodied_methods = when_on_single_line:silent
csharp_style_expression_bodied_properties = true:silent
csharp_style_expression_bodied_accessors = true:silent
csharp_style_prefer_pattern_matching = true:suggestion
csharp_style_prefer_not_pattern = true:suggestion
csharp_style_prefer_switch_expression = true:suggestion
csharp_style_prefer_readonly_struct = true:warning
csharp_style_prefer_readonly_struct_member = true:warning
csharp_prefer_static_local_function = true:warning
csharp_style_prefer_primary_constructors = true:silent
csharp_new_line_before_open_brace = all
csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
dotnet_diagnostic.IDE0005.severity = warning
dotnet_diagnostic.IDE0055.severity = warning
dotnet_diagnostic.IDE0161.severity = error
[{YMM4-GitHubUpdateNotifier,YMM4-Telemetry,YukkuriMovieMaker.Generator}/**]
dotnet_diagnostic.IDE0005.severity = none
dotnet_diagnostic.IDE0055.severity = none
dotnet_diagnostic.IDE0161.severity = none
[*.{g.cs,designer.cs}]
generated_code = true
dotnet_diagnostic.IDE0005.severity = none
dotnet_diagnostic.IDE0055.severity = none
dotnet_diagnostic.IDE0161.severity = none
+483
ファイルの表示
@@ -0,0 +1,483 @@
name: リリース
on:
push:
tags:
- 'v*'
workflow_dispatch:
inputs:
tag:
description: リリースするタグ
required: true
permissions:
contents: write
jobs:
build-and-release:
runs-on: windows-latest
steps:
- name: ソースコードのチェックアウト
uses: actions/checkout@v4
env:
GIT_CONFIG_COUNT: "2"
GIT_CONFIG_KEY_0: url.https://git.routersys.com/routersys/.insteadOf
GIT_CONFIG_VALUE_0: https://github.com/routersys/
GIT_CONFIG_KEY_1: url.https://git.routersys.com/manju-summoner/YukkuriMovieMaker.Generator.insteadOf
GIT_CONFIG_VALUE_1: https://github.com/manju-summoner/YukkuriMovieMaker.Generator
with:
ref: ${{ inputs.tag || github.ref_name }}
submodules: recursive
fetch-depth: 0
- name: YMM4 最新リリースの取得と解凍
id: ymm4
shell: pwsh
run: |
$list = 'C:\runner\cache\ymm4\releases.json'
New-Item -ItemType Directory -Force -Path (Split-Path $list) | Out-Null
if (-not (Test-Path $list) -or (Get-Item $list).Length -lt 1000 -or ((Get-Date) - (Get-Item $list).LastWriteTime).TotalHours -gt 6) {
$fetched = $null
for ($attempt = 1; $attempt -le 6 -and -not $fetched; $attempt++) {
try {
$fetched = Invoke-RestMethod -Uri "https://api.github.com/repos/manju-summoner/YukkuriMovieMaker4/releases?per_page=100" `
-Headers @{ "User-Agent" = "UTAU-CI" } -ErrorAction Stop
}
catch {
$message = $_.Exception.Message
Write-Host "リリース一覧の取得に失敗しました($attempt 回目): $($message.Substring(0, [Math]::Min(80, $message.Length)))"
Start-Sleep -Seconds (5 * $attempt)
}
}
if (@($fetched).Count -gt 0) {
$fetched | Select-Object tag_name, published_at, prerelease, draft, assets |
ConvertTo-Json -Depth 6 | Set-Content -Path $list -Encoding UTF8
}
elseif (-not (Test-Path $list)) { throw 'the list of releases could not be fetched' }
else { Write-Host '保存済みのリリース一覧を使います' }
}
$when = [DateTimeOffset](git log -1 --format=%cI)
$releases = @(Get-Content -Raw -Path $list | ConvertFrom-Json | Where-Object { -not $_.draft -and -not $_.prerelease })
$release = $releases | Where-Object { [DateTimeOffset]$_.published_at -le $when } | Select-Object -First 1
if (-not $release) { $release = $releases | Select-Object -Last 1 }
Write-Host "最後のコミット $when に合わせた YMM4: $($release.tag_name)"
$asset = $release.assets | Where-Object { $_.name -like "*_Lite.zip" } | Select-Object -First 1
if (-not $asset) {
$asset = $release.assets | Where-Object { $_.name -like "*.zip" } | Select-Object -First 1
}
Write-Host "ダウンロード対象: $($asset.name)"
$cache = Join-Path 'C:\runner\cache\ymm4' $asset.name
$extracted = "$cache.extracted"
$lock = New-Object System.Threading.Mutex($false, 'Global\ci-ymm4-cache')
[void]$lock.WaitOne()
try {
if (-not (Test-Path "$extracted\.complete")) {
New-Item -ItemType Directory -Force -Path (Split-Path $cache) | Out-Null
Invoke-WebRequest -Uri $asset.browser_download_url -OutFile $cache
Remove-Item -Recurse -Force $extracted -ErrorAction SilentlyContinue
Expand-Archive -Path $cache -DestinationPath $extracted -Force
New-Item -ItemType File -Path "$extracted\.complete" | Out-Null
}
else {
Write-Host "保存済みの YMM4 を使います: $extracted"
}
}
finally {
$lock.ReleaseMutex()
}
$ymm4Dir = (Get-ChildItem -Path $extracted -Recurse -Filter "YukkuriMovieMaker.dll" |
Select-Object -First 1).DirectoryName
Write-Host "YMM4 DLL ディレクトリ: $ymm4Dir"
echo "YMM4_DIR=$ymm4Dir\" >> $env:GITHUB_OUTPUT
- name: タグ名からバージョンを取得
id: version
shell: pwsh
run: |
$tag = "${{ inputs.tag || github.ref_name }}"
echo "TAG=$tag" >> $env:GITHUB_OUTPUT
echo "VERSION=$($tag.TrimStart('v'))" >> $env:GITHUB_OUTPUT
- name: バージョン記載の照合
shell: pwsh
run: |
$tag = "${{ steps.version.outputs.TAG }}"
$version = "${{ steps.version.outputs.VERSION }}"
$problems = @()
$csprojPath = "UTAU/UTAU.csproj"
$csproj = Get-Content $csprojPath -Raw
if (-not $csproj.Contains("<Version>$version</Version>")) {
$current = if ($csproj -match '<Version>([^<]*)</Version>') { $Matches[1] } else { "記載なし" }
$problems += "$csprojPath の <Version> が $current です。$version にしてください。"
}
$readmePath = ".github/Plugin_Readme.txt"
$readme = Get-Content $readmePath -Raw
if (-not $readme.Contains(" UTAU for YMM4 $tag")) {
$current = if ($readme -match '(?m)^ UTAU for YMM4 (\S+)') { $Matches[1] } else { "記載なし" }
$problems += "$readmePath の見出しが $current です。$tag にしてください。"
}
if ($problems.Count -eq 0) {
Write-Host "バージョン記載は $tag と一致しています"
exit 0
}
foreach ($problem in $problems) {
Write-Host "::error::$problem"
}
Write-Host "::error::リリースの対象は $tag が指すコミットです。タグを付けた後で main へ訂正を積んでも、その訂正はリリースに入りません。タグを削除し、記載を直したコミットを積んでから付け直してください。"
exit 1
- name: resx ファイルの生成(初回ビルド)
shell: pwsh
run: |
$proj = "UTAU/UTAU.csproj"
dotnet build "$proj" `
-c Release `
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
-p:SkipPluginDeploy=true
- name: プロジェクトのビルド
shell: pwsh
run: |
$proj = "UTAU/UTAU.csproj"
dotnet build "$proj" `
-c Release `
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
-p:SkipPluginDeploy=true
- name: パッケージの作成
id: package
shell: pwsh
run: |
$version = "${{ steps.version.outputs.TAG }}"
$outDir = "UTAU/bin/Release/net10.0-windows10.0.19041.0"
$stageRoot = "stage/UTAU"
$pkgName = "UTAU_$version.ymme"
New-Item -ItemType Directory -Path $stageRoot -Force | Out-Null
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
foreach ($path in @("$outDir/plugin/UTAU.dll", "$outDir/WorldNet.dll")) {
$name = Split-Path $path -Leaf
if (-not (Test-Path $path)) {
Write-Error "ビルド結果に $name が見つかりませんでした: $path"
exit 1
}
Copy-Item $path "$stageRoot/"
}
foreach ($lang in @("ar-sa", "en-us", "es-es", "id-id", "ko-kr", "zh-cn", "zh-tw")) {
$src = "$outDir/$lang"
if (Test-Path $src) {
New-Item -ItemType Directory -Path "$stageRoot/$lang" -Force | Out-Null
Copy-Item "$src/*.dll" "$stageRoot/$lang/"
}
}
Copy-Item ".github/LICENSE/*.txt" "$stageRoot/LICENSE/"
Copy-Item ".github/Plugin_Readme.txt" "$stageRoot/Readme.txt"
$readme = Get-Content "$stageRoot/Readme.txt" -Raw
if (-not $readme.Contains(" UTAU for YMM4 $version")) {
Write-Error "同梱する Readme.txt の見出しが $version と一致しません"
exit 1
}
Compress-Archive -Path "stage/*" -DestinationPath $pkgName -CompressionLevel Optimal
echo "PKG_NAME=$pkgName" >> $env:GITHUB_OUTPUT
- name: 変更履歴の作成
id: changelog
shell: pwsh
env:
GITEA_TOKEN: ${{ github.token }}
TAG: ${{ steps.version.outputs.TAG }}
REPOSITORY: ${{ github.repository }}
SERVER_URL: ${{ github.server_url }}
PACKAGE: ${{ steps.package.outputs.PKG_NAME }}
run: |
$tag = $env:TAG
$repository = $env:REPOSITORY
$server = $env:SERVER_URL
$code = [char]0x60
$fence = [string]::new($code, 3)
$unit = [char]0x1f
$previous = ""
$candidates = @(git tag --list "v*" --merged $tag --sort=-creatordate | Where-Object { $_ -ne $tag })
if ($candidates.Count -gt 0) {
$previous = $candidates[0]
}
Write-Host "直前のタグ: $previous"
$range = if ($previous) { "$previous..$tag" } else { $tag }
$log = @(git log "--format=%H%x1f%s%x1f%an%x1f%ad" --date=short $range)
$commits = @()
foreach ($line in $log) {
if (-not $line) { continue }
$fields = $line -split $unit
if ($fields.Count -lt 4) { continue }
$commits += [pscustomobject]@{
Sha = $fields[0]
Subject = $fields[1]
Name = $fields[2]
Date = $fields[3]
Login = ""
Avatar = ""
}
}
Write-Host "コミット数: $($commits.Count)"
$pending = [System.Collections.Generic.HashSet[string]]::new()
foreach ($commit in $commits) {
[void]$pending.Add($commit.Sha)
}
$headers = @{ Authorization = "token $env:GITEA_TOKEN" }
$accounts = @{}
$page = 1
while ($pending.Count -gt 0 -and $page -le 20) {
$rows = @()
try {
$rows = @(Invoke-RestMethod -Uri "$server/api/v1/repos/$repository/commits?sha=$tag&limit=50&page=$page&stat=false&verification=false&files=false" -Headers $headers)
}
catch {
Write-Host "コミットの作者を取得できませんでした: $($_.Exception.Message)"
break
}
if ($rows.Count -eq 0) { break }
foreach ($row in $rows) {
if ($pending.Remove($row.sha)) {
$login = ""
$avatar = ""
if ($row.author) {
$login = [string]$row.author.login
$avatar = [string]$row.author.avatar_url
}
$accounts[$row.sha] = @{ Login = $login; Avatar = $avatar }
}
}
if ($rows.Count -lt 50) { break }
$page++
}
foreach ($commit in $commits) {
if ($accounts.ContainsKey($commit.Sha)) {
$commit.Login = $accounts[$commit.Sha].Login
$commit.Avatar = $accounts[$commit.Sha].Avatar
}
}
$emptyTree = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
$base = if ($previous) { $previous } else { $emptyTree }
$shortstat = (@(git diff --shortstat $base $tag) -join " ")
$changedFiles = 0
$insertions = 0
$deletions = 0
if ($shortstat -match "(\d+) file") { $changedFiles = [int]$Matches[1] }
if ($shortstat -match "(\d+) insertion") { $insertions = [int]$Matches[1] }
if ($shortstat -match "(\d+) deletion") { $deletions = [int]$Matches[1] }
$diffStat = @(git diff --stat $base $tag)
$tagDate = (git log -1 "--format=%ad" --date=short $tag)
$contributors = @($commits |
Group-Object -Property { if ($_.Login) { $_.Login } else { $_.Name } } |
Sort-Object -Property Count -Descending)
function Get-Icon($avatar, $login, $size) {
if (-not $avatar) { return "" }
$sized = if ($avatar.Contains("?")) { "$avatar&s=$($size * 2)" } else { "$avatar" + "?s=$($size * 2)" }
return "<img src=""$sized"" width=""$size"" height=""$size"" alt=""$login""> "
}
$package = Get-Item $env:PACKAGE
$size = [math]::Round($package.Length / 1MB, 2)
$body = [System.Collections.Generic.List[string]]::new()
$body.Add("## 概要")
$body.Add("")
$body.Add("| 項目 | 内容 |")
$body.Add("|---|---|")
$body.Add("| タグ | [$tag]($server/$repository/tree/$tag) |")
$body.Add("| 公開日 | $tagDate |")
if ($previous) {
$body.Add("| 直前のリリース | [$previous]($server/$repository/releases/tag/$previous) |")
}
$body.Add("| コミット数 | $($commits.Count) |")
$body.Add("| 貢献者 | $($contributors.Count) 名 |")
$body.Add("| 変更されたファイル | $changedFiles |")
$body.Add("| 追加された行 | $insertions |")
$body.Add("| 削除された行 | $deletions |")
$body.Add("")
$body.Add("## ダウンロード")
$body.Add("")
$body.Add("| ファイル | サイズ |")
$body.Add("|---|---|")
$body.Add("| $($package.Name) | $size MB |")
$body.Add("")
$body.Add("## 貢献者")
$body.Add("")
$body.Add("| 貢献者 | コミット数 |")
$body.Add("|---|---|")
foreach ($contributor in $contributors) {
$first = $contributor.Group[0]
if ($first.Login) {
$name = (Get-Icon $first.Avatar $first.Login 40) + "[@$($first.Login)]($server/$($first.Login))"
}
else {
$name = $first.Name
}
$body.Add("| $name | $($contributor.Count) |")
}
$body.Add("")
$body.Add("## 変更履歴")
$body.Add("")
$body.Add("| コミット | 内容 | 貢献者 | 日付 |")
$body.Add("|---|---|---|---|")
$maximumCommits = 300
$listed = 0
foreach ($commit in $commits) {
if ($listed -ge $maximumCommits) { break }
$short = $commit.Sha.Substring(0, 7)
$subject = $commit.Subject -replace '\|', '\|'
if ($commit.Login) {
$author = (Get-Icon $commit.Avatar $commit.Login 20) + "[@$($commit.Login)]($server/$($commit.Login))"
}
else {
$author = $commit.Name
}
$body.Add("| [$code$short$code]($server/$repository/commit/$($commit.Sha)) | $subject | $author | $($commit.Date) |")
$listed++
}
if ($commits.Count -gt $maximumCommits) {
$body.Add("")
$body.Add("残り $($commits.Count - $maximumCommits) 件のコミットは省略しました。")
}
if ($diffStat.Count -gt 0) {
$body.Add("")
$body.Add("## 変更されたファイル")
$body.Add("")
$body.Add("<details>")
$body.Add("<summary>差分の統計</summary>")
$body.Add("")
$body.Add($fence)
$maximumStatLines = 200
$shown = 0
foreach ($line in $diffStat) {
if ($shown -ge $maximumStatLines) { break }
$body.Add($line)
$shown++
}
if ($diffStat.Count -gt $maximumStatLines) {
$body.Add("... 残り $($diffStat.Count - $maximumStatLines) 行は省略しました。")
}
$body.Add($fence)
$body.Add("")
$body.Add("</details>")
}
if ($previous) {
$body.Add("")
$body.Add("## 全ての変更")
$body.Add("")
$body.Add("$server/$repository/compare/$previous...$tag")
}
$path = "release-body.md"
Set-Content -Path $path -Value ($body -join "`n") -Encoding utf8NoBOM
if (-not (Test-Path $path)) {
throw "変更履歴を作成できませんでした。"
}
Write-Host "変更履歴の行数: $($body.Count)"
$global:LASTEXITCODE = 0
- name: Gitea リリースの作成
shell: pwsh
env:
GITEA_TOKEN: ${{ github.token }}
REPOSITORY: ${{ github.repository }}
SERVER_URL: ${{ github.server_url }}
EVENT_NAME: ${{ github.event_name }}
WORKFLOW_NAME: ${{ github.workflow }}
JOB_NAME: ${{ github.job }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}
RELEASE_TAG: ${{ inputs.tag || github.ref_name }}
RELEASE_NAME: ${{ steps.version.outputs.TAG }}
RELEASE_BODY: ''
RELEASE_BODY_PATH: release-body.md
RELEASE_DRAFT: false
RELEASE_PRERELEASE: false
RELEASE_FILES: |
${{ steps.package.outputs.PKG_NAME }}
run: |
$headers = @{ Authorization = "token $env:GITEA_TOKEN" }
$api = "$env:SERVER_URL/api/v1/repos/$env:REPOSITORY"
$tag = $env:RELEASE_TAG
$body = $env:RELEASE_BODY
if ($env:RELEASE_BODY_PATH -and (Test-Path $env:RELEASE_BODY_PATH)) {
$body = Get-Content $env:RELEASE_BODY_PATH -Raw -Encoding utf8
}
$files = @()
foreach ($pattern in ($env:RELEASE_FILES -split "[`r`n,]+" | Where-Object { $_.Trim() })) {
$found = @(Get-ChildItem -Path $pattern.Trim() -File -ErrorAction SilentlyContinue)
if ($found.Count -eq 0) { throw "リリースに付けるファイルが見つかりません: $pattern" }
$files += $found
}
$payload = @{
tag_name = $tag
name = $env:RELEASE_NAME
body = [string]$body
draft = ($env:RELEASE_DRAFT -eq 'true')
prerelease = ($env:RELEASE_PRERELEASE -eq 'true')
} | ConvertTo-Json
$bytes = [System.Text.Encoding]::UTF8.GetBytes($payload)
$existing = $null
try { $existing = Invoke-RestMethod -Uri "$api/releases/tags/$([System.Uri]::EscapeDataString($tag))" -Headers $headers } catch { }
if ($existing) {
$release = Invoke-RestMethod -Method Patch -Uri "$api/releases/$($existing.id)" -Headers $headers -ContentType "application/json; charset=utf-8" -Body $bytes
foreach ($asset in @($existing.assets)) {
Invoke-RestMethod -Method Delete -Uri "$api/releases/$($existing.id)/assets/$($asset.id)" -Headers $headers | Out-Null
}
} else {
$release = Invoke-RestMethod -Method Post -Uri "$api/releases" -Headers $headers -ContentType "application/json; charset=utf-8" -Body $bytes
}
foreach ($file in $files) {
$name = [System.Uri]::EscapeDataString($file.Name)
Invoke-RestMethod -Method Post -Uri "$api/releases/$($release.id)/assets?name=$name" -Headers $headers -Form @{ attachment = Get-Item $file.FullName } | Out-Null
Write-Host "添付しました: $($file.Name)"
}
Write-Host "リリースを作成しました: $($release.html_url)"
if ($env:EVENT_NAME -eq 'workflow_dispatch') {
try {
$sha = (git rev-parse HEAD).Trim()
$status = @{
state = 'success'
context = "$env:WORKFLOW_NAME / $env:JOB_NAME (workflow_dispatch)"
description = "Actions がタグ $tag のコミットから作成しました"
target_url = $env:RUN_URL
} | ConvertTo-Json
Invoke-RestMethod -Method Post -Uri "$api/statuses/$sha" -Headers $headers -ContentType "application/json; charset=utf-8" -Body ([System.Text.Encoding]::UTF8.GetBytes($status)) | Out-Null
Write-Host "タグのコミット $sha に成功の状態を付けました"
}
catch {
Write-Warning "タグのコミットに状態を付けられませんでした: $($_.Exception.Message)"
}
}
+1
ファイルの表示
@@ -0,0 +1 @@
github: routersys
+102
ファイルの表示
@@ -0,0 +1,102 @@
name: 不具合の報告
description: エラーが出る、強制終了する、出力が乱れる、README と違う動きをする、といった不具合を報告します。
title: "[Bug] "
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
脆弱性はここに書かず、リポジトリのセキュリティポリシーに従って非公開で報告してください。
README と実際の動きが違い、文書のほうが誤りだと考えるときは、文書の不備を使ってください。
- type: input
id: plugin-version
attributes:
label: プラグインのバージョン
description: GitHub のリリースか、配布パッケージの Readme.txt の見出しで確かめられます。
placeholder: v1.0.0
validations:
required: true
- type: input
id: ymm4-version
attributes:
label: YukkuriMovieMaker4 のバージョン
description: YukkuriMovieMaker4 のメインウィンドウのタイトルに表示されるバージョンを、そのまま書いてください。
placeholder: v4.56.1.0 Lite
validations:
required: true
- type: input
id: os
attributes:
label: Windows のバージョン
description: winver を実行し、ビルド番号まで書いてください。
placeholder: Windows 11 24H2, 26100.2605
validations:
required: true
- type: input
id: gpu
attributes:
label: GPU とドライバー
description: 描画や GPU に関わる不具合では必ず書いてください。デバイスマネージャーか dxdiag に表示される GPU の名前と、ドライバーのバージョンです。
- type: textarea
id: expected
attributes:
label: 期待した動き
description: 何が起きると考えたか。README に根拠があれば、その箇所も書いてください。
validations:
required: true
- type: textarea
id: actual
attributes:
label: 実際の動き
description: 実際に起きたこと。エラー画面が出たときは、その内容を省略せずに貼ってください。
validations:
required: true
- type: textarea
id: steps
attributes:
label: 再現の手順
description: |
新しいプロジェクトから不具合が起きるまでの操作を、番号を付けて書いてください。変えた設定の項目と値も書いてください。
プロジェクトファイルや素材は、zip に圧縮して添付できます。添付したファイルは誰でも見られます。プロジェクトファイルには素材を置いたフォルダーのパスが記録されるので、公開できない情報が無いかを確かめてください。
placeholder: |
1. 新しいプロジェクトを作る
2. アイテムを置き、本プラグインを使う
3. 設定を変える
4. 不具合が起きる
validations:
required: true
- type: dropdown
id: frequency
attributes:
label: 起きる頻度
description: ときどき起きるときは、何回試して何回起きたかを、下の「その他」の欄に書いてください。
options:
- 毎回起きる
- ときどき起きる
- 一度だけ起きた
validations:
required: true
- type: textarea
id: context
attributes:
label: その他
description: 一緒に使っているほかのプラグインや、関係すると思われることを書いてください。
- type: checkboxes
id: checks
attributes:
label: 報告の前に
options:
- label: 最新のリリースを使っています。
required: true
- label: 既存の Issue を検索し、同じ報告が無いことを確かめました。
required: true
+5
ファイルの表示
@@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: YukkuriMovieMaker4 本体の不具合
url: https://manjubox.net/contact/
about: 本体に原因がある不具合は、YukkuriMovieMaker4 の「ヘルプ」の「フィードバックを送信」か、公式サイトのお問い合わせから報告してください。
+63
ファイルの表示
@@ -0,0 +1,63 @@
name: 文書の不備
description: 誤り、書き漏れ、実際の動きとの食い違いがある文書を報告します。
title: "[Docs] "
labels: ["documentation"]
body:
- type: markdown
attributes:
value: |
実際の動きと文書が食い違うときは、ここで報告して構いません。動きのほうが誤りだと考えるときは、不具合の報告を使ってください。
- type: dropdown
id: location
attributes:
label: 文書
options:
- README
- 配布パッケージの Readme.txt
- 設定の項目の名前や説明
- 貢献の手引き、セキュリティポリシー、行動規範
- その他
validations:
required: true
- type: input
id: reference
attributes:
label: 文書の中の位置
description: 見出し、行番号、設定の項目の名前のどれかを書いてください。
placeholder: README の「制限事項」の 2 つ目の項目
validations:
required: true
- type: textarea
id: says
attributes:
label: 今の記述
description: そのまま引用してください。元の文書を開かずに検討できるようにするためです。
validations:
required: true
- type: textarea
id: problem
attributes:
label: どこが問題か
description: |
誤り、書き漏れ、曖昧さのどれに当たるかを書いてください。それによって読む人が何を取り違えるかも書いてください。
実際の動きと食い違っているときは、文書と動きのどちらを直すべきと考えるかも書いてください。
validations:
required: true
- type: textarea
id: suggestion
attributes:
label: 提案する文面
description: 具体的な文面があると、早く直せます。
- type: checkboxes
id: checks
attributes:
label: 報告の前に
options:
- label: 最新のリリースか、既定のブランチの最新の文書で確かめました。
required: true
+42
ファイルの表示
@@ -0,0 +1,42 @@
name: 機能の提案
description: 新しい機能や設定の項目、既存の動きの変更を提案します。
title: "[Proposal] "
labels: ["enhancement"]
body:
- type: textarea
id: problem
attributes:
label: 困っていること
description: 今のプラグインでできないことや、手間がかかることを、利用者の立場で書いてください。
validations:
required: true
- type: textarea
id: workaround
attributes:
label: 今はどうしているか
description: 今の回避策と、それにかかる手間を書いてください。回避策が無ければ、その旨を書いてください。
validations:
required: true
- type: textarea
id: proposal
attributes:
label: 提案する動き
description: どう動いてほしいかを書いてください。設定の項目を増やす提案では、項目の名前、範囲、既定値の案も書いてください。
- type: textarea
id: alternatives
attributes:
label: 検討したほかの方法
description: ほかに考えた方法があれば、それでは足りない理由と一緒に書いてください。
- type: checkboxes
id: checks
attributes:
label: 提案の前に
options:
- label: 既存の Issue を検索し、同じ提案が無いことを確かめました。
required: true
- label: 最新のリリースに同じ機能が無いことを確かめました。
required: true
+49
ファイルの表示
@@ -0,0 +1,49 @@
name: 使い方の質問
description: 使い方や、実際の動きが仕様どおりかを尋ねます。
title: "[Question] "
labels: ["question"]
body:
- type: markdown
attributes:
value: |
プラグインの不具合だと分かっているときは、不具合の報告を使ってください。
- type: textarea
id: question
attributes:
label: 質問
description: 背景を書く前に、質問を 1 文か 2 文で書いてください。
validations:
required: true
- type: textarea
id: goal
attributes:
label: 何をしようとしているか
description: つまずいている操作だけでなく、最終的に何を作りたいかを書いてください。
validations:
required: true
- type: textarea
id: tried
attributes:
label: 試したこと
description: 試した設定と、そのとき実際に起きたことを書いてください。
- type: input
id: plugin-version
attributes:
label: プラグインのバージョン
placeholder: v1.0.0
validations:
required: true
- type: checkboxes
id: checks
attributes:
label: 質問の前に
options:
- label: README の該当する節を読みました。
required: true
- label: 既存の Issue を検索し、同じ質問が無いことを確かめました。
required: true
+24
ファイルの表示
@@ -0,0 +1,24 @@
NAudio
MIT License
Copyright © Mark Heath & Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+21
ファイルの表示
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 StAkira
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+79 -6
ファイルの表示
@@ -1,5 +1,5 @@
========================================
UTAU for YMM4 v1.2.0
UTAU for YMM4 v1.7.5
========================================
YukkuriMovieMaker4(YMM4)上で動作する、UTAU 音源から歌声を合成する
音声合成プラグインです。
@@ -40,8 +40,12 @@ WorldNet で分析して合成し直します。
複数のアイテムへ分けて並べられます。分けて置くと、編集のたびに合成し直す
範囲が狭くなります。フレーズの中の音は分ける前と変わりません。
- 合成した音は区間ごとに覚えておき、直したノートを含む区間だけを合成し直します。
区間は休符で切れる塊です。表現の帯で曲線を引いているときは行いません。
- 合成は休符で切れる区間ごとに複数のコアで並列に行います。区間は互いに独立して
いるため、並列にしても結果は変わりません。
- 合成した音は区間ごとに覚えておきます。音程や音量のように位置が動かない編集
では、直したノートを含む区間だけを合成し直します。区間は休符で切れる塊です。
表現の帯で曲線を引いているときは行いません。
- 歌詞は、かなのほか a か のような連続音の形とローマ字でも書けます。歌詞の
最後の空白より後ろをかなへ戻して照合するため、連続音の譜面を単独音の音源で
@@ -52,6 +56,22 @@ WorldNet で分析して合成し直します。
- アイテムの編集画面の「ノートを編集」から、音程・長さ・ビブラート・
ポルタメント・表現曲線を編集できます。
- ノートエディターでノートを右で押すと品書きが出ます。選んだノートすべての
オクターブ上げ下げ、長さを吸着に合わせる操作、音程曲線・ビブラート・
発声タイミング・ノート全体を既定へ戻す操作、ノートのコピーと貼り付けを
行えます。オクターブの上げ下げでノートどうしの音程差は変わりません。
- 品書きの「歌詞をまとめて編集」で、選んだノートの歌詞を別の窓で一度に
書き換えられます。空白と改行で区切り、漢字とかなは 1 文字ずつ、引用符で
囲んだ部分はまとめて 1 つのノートになります。歌詞の数がノートの数より
多いときは余りを捨て、少ないときは残りのノートをそのままにします。
- 品書きの「別ウィンドウで編集」で、編集画面をそのまま別の窓へ移せます。
窓を閉じると元の位置へ戻り、編集した内容はそのまま残ります。
- ノートエディターの工具列に出る文言が幅に収まらないときは、2 秒おいてから
端まで送り、2 秒おいて戻ります。収まっているときは動きません。
--------------------------------------------------------------------------------
■ 対応フォーマット
--------------------------------------------------------------------------------
@@ -78,8 +98,8 @@ WorldNet で分析して合成し直します。
キャッシュするため、2 回目以降は速くなります。上限は既定で 512MB で、
64MB から 4096MB まで設定画面から変更できます。
- 合成は 1 件ずつ順に行います。休符を挟まずに続く区間が長すぎると
合成できません。文を分けてください。
- 合成の要求は 1 件ずつ順に処理します。1 件の中では区間ごとに並列に合成します。
休符を挟まずに続く区間が長すぎると合成できません。文を分けてください。
- UST の Flags と旧式の音程には対応していません。UST の書き出しにも
対応していません。
@@ -89,6 +109,54 @@ WorldNet で分析して合成し直します。
- 本プラグインを使用する前に、YMM4 プロジェクトファイルのバックアップを
作成することを推奨します。
--------------------------------------------------------------------------------
■ 不具合の報告
--------------------------------------------------------------------------------
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で
送信します。同意は求めません。止める設定もありません。
送信する数には上限があります。YMM4 の 1 回の起動で送る報告は、
YMM4-Telemetry で報告する別のプラグインと合わせて 20 件までです。
例外の型と発生位置が同じ報告は 3 件までです。上限を超えた報告と、
送信先から待つよう求められている間に起きた報告は、送信も退避もしません。
送信する情報は次のとおりです。
例外 : 型の完全名、メッセージ、スタックトレース
発生位置 : モジュール名、関数名、ファイル名、行番号、
プラグイン自身のコードかどうか
プラグイン : アセンブリ名、バージョン
実行環境 : OS の名前とバージョン、.NET のバージョン、
CPU のアーキテクチャ、論理プロセッサ数
識別子 : YMM4 の起動ごとに決まるセッション識別子、報告ごとの識別子
時刻 : 報告を作った時刻(UTC)
利用者の名前、プロジェクトの名前、音源の名前、歌詞、音声ファイルの中身は
送信しません。継続して個人を追跡する識別子も持ちません。セッション識別子は
YMM4 を起動し直すと別の値になります。メッセージとファイル名に含まれる
利用者名などの文字列は、送信の前に置き換えます。送信元の IP アドレスは
受信側へ渡す手前で取り除いています。
送信するのは想定していない例外だけです。本プラグインが例外を握り潰す箇所と、
YMM4 へ処理を返す境界の両方で報告します。画面の操作やバックグラウンドの
処理で未処理になった例外も報告しますが、本プラグインのコードが関わる例外に
限ります。YMM4 本体やほかのプラグインで起きた例外は送信しません。
次の例外は送信しません。
利用者へ知らせるための失敗 : エイリアスが見つからない、合成できるノートが
ない、セリフが空
更新の確認の通信の失敗 : GitHub へ接続できない
探索と設定ファイルの読み取りで想定している失敗 : フォルダーを開く権限が
ない、文字コードを判別できない、パスが長すぎる
音源の音声ファイルを読み込めなかった場合は送信します。読み込みの不具合を
見つけるためです。
送信できなかった報告は YMM4 のユーザーフォルダーへ退避します。
次に YMM4 を起動したあと、本プラグインを読み込むか、
同じく YMM4-Telemetry で報告する別のプラグインが動き始めると、
退避した報告を 1 回の起動で 10 件まで送り直します。
送信も再送も非同期に行うため、起動と合成が遅くなることは
ありません。
--------------------------------------------------------------------------------
■ 免責事項
--------------------------------------------------------------------------------
@@ -105,10 +173,15 @@ WorldNet で分析して合成し直します。
本プラグインは音声の分析と合成に WorldNet(MIT License)を同梱しています。
WorldNet は M. Morise 氏の WORLD(修正 BSD License)を C# へ移植した物で、
高速フーリエ変換には Takuya OOURA 氏の FFT パッケージを用いています。
ライセンスの全文は同梱の LICENSE フォルダー(WorldNet.txt)に収録しています。
音声ファイルの読み書きには NAudio(MIT License)を同梱しています。
歌詞をまとめて編集するときの区切り方は OpenUtau(MIT License)の規約に
合わせています。
ライセンスの全文は同梱の LICENSE フォルダーに収録しています。
WorldNet : Copyright (c) 2026 routersys
NAudio : Copyright (c) Mark Heath & Contributors
WORLD : Copyright (c) 2010 M. Morise
Ooura FFT : Copyright Takuya OOURA, 1996-2001
OpenUtau : Copyright (c) 2014 StAkira
--------------------------------------------------------------------------------
■ ライセンス
--------------------------------------------------------------------------------
+87
ファイルの表示
@@ -0,0 +1,87 @@
<!--
当てはまらない節は消してください。「関連する Issue」と「動きの変更」の節は残し、該当しないときは「なし」と書いてください。
-->
## 概要
<!--
何をどう変えたか。なぜその変更が必要か。
-->
## 関連する Issue
<!--
新しい機能、設定の項目や既定値の変更、大きめの不具合の修正、意図して出力を変える変更、互換性を損なう変更、コードの構成を大きく変える変更は、先に Issue で合意してください。
Issue が無い変更では、下の行を「なし」に書き換えてください。
-->
Closes #
## 変更の種類
<!-- 当てはまるものを残してください。 -->
- 不具合の修正
- 機能の追加
- 動きの変更
- 性能の改善
- テストの追加
- 依存関係の更新
- 文書
- ビルド、リリース
## 動きの変更
<!--
利用者から見て何が変わるか。設定の項目、既定値、出力の結果、エラーの出方の変化も含みます。
保存済みのプロジェクトの結果が変わるなら、必ず書いてください。
-->
## 検証
<!--
手元で実際に確かめた結果を書いてください。
- ビルドの結果と、テストのプロジェクトがあればテストの結果
- YukkuriMovieMaker4 で実際に動かして確かめたこと
- 実行できなかったテストと、その理由
実際に動かして観察したこと、コードを読んで判断したこと、推測したことを分けて書いてください。
-->
使った YukkuriMovieMaker4 のバージョン:
GPU に関わる変更では、使った GPU とドライバー:
## 確認
<!-- テストのプロジェクトが無いリポジトリでは、実装とテストを分ける項目を消してください。 -->
- [ ] 1 つの目的の変更だけを含み、関係の無い整理や整形を含めていない。
- [ ] どのコミットも、それ単独でビルドが通る。
- [ ] 実装の変更と、それを確かめるテストを、別のコミットに分けた。
- [ ] コミットの件名は日本語で書き、50 文字以内に収め、「〜する」の形で終えた。日本語で書けない場合は、その旨を「レビューで見てほしい点」に書いた。
- [ ] コミットの本文は、リリースノートでの変更の分類を指定する行を求められたときだけ書いた。
- [ ] 変更する箇所で既に使われている実装のパターンに従った。
- [ ] 新しく書いたコードにコメントを入れず、コメントアウトしたコードも残していない。既存のコメントとドキュメントコメントは残した。
- [ ] 自分の変更で増えたビルドの警告を直した。
- [ ] 出力を変えるつもりの無い変更では、変更前と変更後で出力が一致することを確かめた。
- [ ] この変更と関係の無い依存関係の更新を含めていない。
- [ ] 動きを変えた場合、README を直した。`.github/Plugin_Readme.txt` があるリポジトリでは、それも直した。
- [ ] バージョンを上げる変更を含めていない。
## 性能の改善を主張する場合
<!-- それ以外の場合は、この節ごと消してください。 -->
- [ ] 同じ機材、ドライバー、設定、電源の条件で、変更前と変更後のビルドを交互に繰り返し測った。
- [ ] 測定の間を空け、ほかのプロセスが GPU を使っていない状態で測った。
- [ ] 正しさの確認と性能の測定を、別々に実行した。
<!--
測定の条件と、測定値。
-->
## レビューで見てほしい点
<!--
判断に迷った点、意見を聞きたい点、意図して外した部分とその理由。
-->
+40 -2
ファイルの表示
@@ -50,6 +50,38 @@ jobs:
echo "TAG=$tag" >> $env:GITHUB_OUTPUT
echo "VERSION=$($tag.TrimStart('v'))" >> $env:GITHUB_OUTPUT
- name: バージョン記載の照合
shell: pwsh
run: |
$tag = "${{ steps.version.outputs.TAG }}"
$version = "${{ steps.version.outputs.VERSION }}"
$problems = @()
$csprojPath = "UTAU/UTAU.csproj"
$csproj = Get-Content $csprojPath -Raw
if (-not $csproj.Contains("<Version>$version</Version>")) {
$current = if ($csproj -match '<Version>([^<]*)</Version>') { $Matches[1] } else { "記載なし" }
$problems += "$csprojPath の <Version> が $current です。$version にしてください。"
}
$readmePath = ".github/Plugin_Readme.txt"
$readme = Get-Content $readmePath -Raw
if (-not $readme.Contains(" UTAU for YMM4 $tag")) {
$current = if ($readme -match '(?m)^ UTAU for YMM4 (\S+)') { $Matches[1] } else { "記載なし" }
$problems += "$readmePath の見出しが $current です。$tag にしてください。"
}
if ($problems.Count -eq 0) {
Write-Host "バージョン記載は $tag と一致しています"
exit 0
}
foreach ($problem in $problems) {
Write-Host "::error::$problem"
}
Write-Host "::error::リリースの対象は $tag が指すコミットです。タグを付けた後で main へ訂正を積んでも、その訂正はリリースに入りません。タグを削除し、記載を直したコミットを積んでから付け直してください。"
exit 1
- name: resx ファイルの生成(初回ビルド)
shell: pwsh
run: |
@@ -80,8 +112,8 @@ jobs:
New-Item -ItemType Directory -Path $stageRoot -Force | Out-Null
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
foreach ($name in @("UTAU.dll", "WorldNet.dll")) {
$path = "$outDir/$name"
foreach ($path in @("$outDir/plugin/UTAU.dll", "$outDir/WorldNet.dll")) {
$name = Split-Path $path -Leaf
if (-not (Test-Path $path)) {
Write-Error "ビルド結果に $name が見つかりませんでした: $path"
exit 1
@@ -100,6 +132,12 @@ jobs:
Copy-Item ".github/LICENSE/*.txt" "$stageRoot/LICENSE/"
Copy-Item ".github/Plugin_Readme.txt" "$stageRoot/Readme.txt"
$readme = Get-Content "$stageRoot/Readme.txt" -Raw
if (-not $readme.Contains(" UTAU for YMM4 $version")) {
Write-Error "同梱する Readme.txt の見出しが $version と一致しません"
exit 1
}
Compress-Archive -Path "stage/*" -DestinationPath $pkgName -CompressionLevel Optimal
echo "PKG_NAME=$pkgName" >> $env:GITHUB_OUTPUT
+5 -2
ファイルの表示
@@ -1,6 +1,9 @@
[submodule "YukkuriMovieMaker.Generator"]
path = YukkuriMovieMaker.Generator
url = https://github.com/manju-summoner/YukkuriMovieMaker.Generator
url = https://git.routersys.com/manju-summoner/YukkuriMovieMaker.Generator
[submodule "YMM4-GitHubUpdateNotifier"]
path = YMM4-GitHubUpdateNotifier
url = https://github.com/routersys/YMM4-GitHubUpdateNotifier.git
url = https://git.routersys.com/routersys/YMM4-GitHubUpdateNotifier.git
[submodule "YMM4-Telemetry"]
path = YMM4-Telemetry
url = https://git.routersys.com/routersys/YMM4-Telemetry.git
+81
ファイルの表示
@@ -0,0 +1,81 @@
# Contributor Covenant 行動規範
## 私たちの約束
メンバー、貢献者、リーダーである私たちは、年齢、体格、目に見える障害と目に見えない障害、民族、性的特徴、性自認と性表現、経験の程度、教育、社会経済的地位、国籍、外見、人種、宗教、性的アイデンティティと性的指向を問わず、コミュニティへの参加を誰にとっても嫌がらせの無いものにすることを誓います。
私たちは、開かれていて誰もが歓迎される、多様で包摂的な、健全なコミュニティを作るように行動し、交流することを誓います。
## 私たちの基準
コミュニティのよい環境を作る行動の例は、次のとおりです。
- ほかの人に共感と思いやりを示す
- 異なる意見、視点、経験を尊重する
- 建設的な意見を伝え、また快く受け入れる
- 自分たちの誤りに責任を持ち、影響を受けた人に謝り、その経験から学ぶ
- 自分個人にとってだけでなく、コミュニティ全体にとって最善のことを考える
受け入れられない行動の例は、次のとおりです。
- 性的な言葉や画像を使うこと、どのような形であれ、相手に性的な関心を向けることや言い寄ること
- 荒らし、侮辱的または軽蔑的な発言、個人攻撃や政治的な攻撃
- 公の場か私的な場かを問わない嫌がらせ
- 住所やメールアドレスなど、ほかの人の個人情報を明示の許可なく公開すること
- 仕事の場で不適切と合理的に考えられるその他の行為
## 執行の責任
コミュニティリーダーは、受け入れられる行動の基準を明確にし、それを守らせる責任を負います。不適切、脅迫的、攻撃的、または有害と判断した行動には、適切で公正な是正措置をとります。
コミュニティリーダーは、この行動規範に沿わないコメント、コミット、コード、Wiki の編集、Issue、その他の貢献を削除、編集、または却下する権利と責任を持ちます。モデレーションの判断については、適切な場合に理由を伝えます。
## 適用範囲
この行動規範は、コミュニティのあらゆる場で適用されます。個人が公の場でコミュニティを公式に代表しているときにも適用されます。コミュニティを代表しているときとは、たとえば、公式のメールアドレスを使うとき、公式のソーシャルメディアのアカウントから投稿するとき、オンラインやオフラインのイベントで任命された代表として行動するときです。
## 執行
虐待的な言動、嫌がらせ、その他の受け入れられない行動は、執行を担当するコミュニティリーダーへ github.routersys@gmail.com で報告できます。コミュニティリーダーは、すべての苦情を速やかかつ公正に確認し、調査します。
すべてのコミュニティリーダーは、事案を報告した人のプライバシーと安全を尊重する義務を負います。
## 執行のガイドライン
コミュニティリーダーは、この行動規範に違反すると判断した行動への処置を決めるとき、次に示すコミュニティへの影響に応じたガイドラインに従います。
### 1. 是正
コミュニティへの影響: 不適切な言葉づかいや、コミュニティの中で、仕事の場にふさわしくない、または歓迎されないと判断されるその他の行動。
処置: コミュニティリーダーが、非公開の書面による警告を送ります。違反の内容を明らかにし、その行動がなぜ不適切だったかを説明します。公の場での謝罪を求めることがあります。
### 2. 警告
コミュニティへの影響: 1 回の出来事、または一連の行動による違反。
処置: 行動が続いた場合の処置を示した警告を送ります。警告を受けた人は、定められた期間、関係する人々とやり取りしてはいけません。行動規範を執行する人々へ、求められていないのに接触することも、これに含まれます。コミュニティの場だけでなく、ソーシャルメディアなど外部の場でのやり取りも避けなければなりません。これらの条件に違反すると、一時的または永久的な参加禁止につながることがあります。
### 3. 一時的な参加禁止
コミュニティへの影響: 不適切な行動を続けることを含む、コミュニティの基準への重大な違反。
処置: 定められた期間、コミュニティとのあらゆるやり取りと、コミュニティに向けた公の発信を禁止します。この期間中は、公の場か私的な場かを問わず、関係する人々とのやり取りを認めません。行動規範を執行する人々へ、求められていないのに接触することも、これに含まれます。これらの条件に違反すると、永久的な参加禁止につながることがあります。
### 4. 永久的な参加禁止
コミュニティへの影響: コミュニティの基準に繰り返し違反すること。不適切な行動を続けること、個人への嫌がらせ、特定の属性を持つ人々への攻撃や中傷も、これに当たります。
処置: コミュニティの中でのあらゆる公のやり取りを、永久に禁止します。
## 出典
この行動規範は、[Contributor Covenant][homepage] のバージョン 2.0 を基にしています。原文は https://www.contributor-covenant.org/version/2/0/code_of_conduct.html にあります。日本語の文は、公式の日本語訳 https://www.contributor-covenant.org/ja/version/2/0/code_of_conduct/ を基に、原文と照らし合わせて改めたものです。
Contributor Covenant は、[クリエイティブ・コモンズ 表示 4.0 国際 ライセンス](https://creativecommons.org/licenses/by/4.0/deed.ja)のもとで提供されています。
コミュニティへの影響に応じたガイドラインは、[Mozilla の行動規範の執行の段階](https://github.com/mozilla/diversity)に着想を得ています。
[homepage]: https://www.contributor-covenant.org
この行動規範についてのよくある質問と回答は、https://www.contributor-covenant.org/faq にあります。ほかの言語の訳は、https://www.contributor-covenant.org/translations にあります。
+168
ファイルの表示
@@ -0,0 +1,168 @@
# 貢献の手引き
本プラグインへの貢献に関心を持っていただき、ありがとうございます。この手引きは、Issue の立て方、プルリクエストの作り方、変更の確かめ方、コードとコミットの書き方を定めます。
本プラグインでできることとできないことは、[README](README.md) に書いてあります。まず README を読んでください。
---
## 目次
1. [貢献の進め方](#貢献の進め方)
2. [開発環境](#開発環境)
3. [Issue](#issue)
4. [プルリクエスト](#プルリクエスト)
5. [検証](#検証)
6. [コードの規約](#コードの規約)
7. [コミットの規約](#コミットの規約)
8. [行動規範](#行動規範)
---
## 貢献の進め方
誤字の修正、文書の修正、軽微な不具合の修正は、そのままプルリクエストを送ってください。
新しい機能、設定の項目や既定値の変更、大きめの不具合の修正、意図して出力を変える変更、互換性を損なう変更、コードの構成を大きく変える変更は、先に Issue を立ててください。実装を始める前に、意図する動きと変更の範囲について合意するためです。どちらに当たるか迷ったときも、Issue を立ててください。
脆弱性は Issue に書かず、[セキュリティポリシー](SECURITY.md)に従って非公開で報告してください。
Issue とプルリクエストは、日本語か英語で書いてください。
---
## 開発環境
| 項目 | 要件 |
|---|---|
| OS | Windows 10 バージョン 2004 以降の 64bit 版 |
| SDK | .NET 10 |
| YukkuriMovieMaker4 | ビルドがインストール先の DLL を参照するため、手元に入れておく |
| シェーダーのビルド | HLSL をビルドのときにコンパイルするリポジトリでは Windows SDK が要る。シェーダーを `.vcxproj` でビルドするリポジトリでは、Visual Studio 2026 の「C++ によるデスクトップ開発」も要る |
### 取得
リポジトリをフォークし、自分のフォークをクローンしてください。リポジトリはサブモジュールを含むことがあるので、`--recursive` を付けます。
```console
git clone --recursive https://github.com/<自分のアカウント>/<リポジトリ名>.git
```
`--recursive` を付けずにクローンしたときは、後から次のコマンドでサブモジュールを取得できます。
```console
git submodule update --init --recursive
```
作業は `main` から切ったブランチで行ってください。
### YukkuriMovieMaker4 の場所
YukkuriMovieMaker4 のインストール先は、MSBuild のプロパティ `YMM4DirPath` で渡します。値の末尾には `\` を付けてください。
- コマンドラインでは、`-p:YMM4DirPath="<インストール先>\"` を付けてビルドします。PowerShell 7 以降で実行してください。Windows PowerShell 5.1 と cmd では、末尾の `\"` が正しく渡らないため、末尾を `\\"` と書いてください。
- Visual Studio でビルドするときは、プラグインのプロジェクトのフォルダーか、その上のフォルダーに `Directory.Build.props` があれば、その `YMM4DirPath` を手元で書き換えます。無ければ、環境変数 `YMM4DirPath` を設定します。書き換えた `Directory.Build.props` はコミットに含めないでください。サブモジュールの中にある `Directory.Build.props` は書き換えないでください。
### ビルド
ソリューションを開き、Release でビルドしてください。
シェーダーを `.vcxproj` でビルドするリポジトリでは、コマンドラインのビルドに Visual Studio の MSBuild を使ってください。.NET SDK の `dotnet` コマンドは `.vcxproj` を扱えません。テストは、`dotnet test <名前>.Tests\<名前>.Tests.csproj` のようにテストのプロジェクトのファイルを指定して実行してください。ビルドの手順は、`.github/workflows/release.yml` があればそこに書いてあります。
多くのリポジトリでは、ビルドの後にプラグインが YukkuriMovieMaker4 の `user\plugin` フォルダーへ自動でコピーされます。
- YukkuriMovieMaker4 を起動したままだと、コピーの段階で失敗します。ビルドの前に終了してください。
- 配布版のプラグインを入れているときは、同じ名前のファイルが上書きされます。
- コマンドラインでソリューションをビルドしたときはコピーしないリポジトリがあります。その場合は、プラグインのプロジェクトを指定してビルドしてください。
- `.csproj` に `SkipPluginDeploy` の条件があるリポジトリでは、`-p:SkipPluginDeploy=true` を付けるとコピーせずにビルドできます。
---
## Issue
Issue はテンプレートから立ててください。不具合の報告、文書の不備、機能の提案、使い方の質問の 4 つがあります。
不具合の報告には、次の内容を書いてください。
- 期待した動きと、実際の動き
- 再現の手順。できれば、問題が起きる最小のプロジェクトファイルや素材
- プラグインのバージョン、YukkuriMovieMaker4 のバージョン、Windows のバージョン
- 描画や GPU に関わる不具合では、GPU の名前とドライバーのバージョン
- エラー画面に出た内容。省略せずに貼ってください
ときどきしか起きない不具合も、確実な再現の手順が無いまま報告して構いません。何回試して何回起きたかと、どの操作の後に起きたかを書いてください。
コードを読んで見つけた不具合を報告するときは、実際に再現を確かめたかどうかも書いてください。
Issue に添付したファイルは、誰でも見られます。プロジェクトファイルには、素材を置いたフォルダーのパスが記録されています。パスにユーザー名が含まれることがあるので、公開できない情報が無いかを確かめてから添付してください。
不具合の情報を自動で送信するプラグインでも、Issue での報告には意味があります。自動で送られるのは、例外の内容と実行環境の一部です。そこに至った操作、YukkuriMovieMaker4 のバージョン、GPU、例外を伴わない描画の乱れは届きません。
---
## プルリクエスト
1 つのプルリクエストには、1 つの目的の変更だけを含めてください。関係の無い整理、整形、依存関係の更新を含めないでください。依存関係を更新するのは、必要な機能を使うため、不具合やセキュリティの問題を直すため、互換性を保つためなど、具体的な理由があるときだけにしてください。
特に注意が要るのは、次の箇所です。
- 設定の項目と、その既定値と範囲。保存済みのプロジェクトの結果が変わるおそれがある
- 出力の結果。変えるつもりの無い変更で、映像や音が変わっていないか
- GPU のリソース、ファイル、ハンドルの寿命
- 破棄の処理と、失敗したときの処理
- YukkuriMovieMaker4 の内部に手を入れるプラグインでは、YukkuriMovieMaker4 のバージョンによる違い
動きを変えたときは、同じプルリクエストで README を直してください。`.github/Plugin_Readme.txt` があるリポジトリでは、それも直してください。`Plugin_Readme.txt` は配布パッケージに `Readme.txt` として入り、利用者の手元に残ります。
バージョンを上げる変更は、プルリクエストに含めないでください。バージョンの更新とリリースは、開発者が行います。
レビューを受けて直すときは、コミットを目的ごとのまとまりに保つため、ブランチの履歴を組み直して強制プッシュして構いません。
プルリクエストを送った時点で、その貢献をリポジトリと同じライセンスで提供することに同意したものとみなします。リポジトリのライセンスは、リポジトリの直下にあるライセンスのファイルに書いてあります。
---
## 検証
プルリクエストには、手元で実際に確かめた結果を書いてください。
- ビルドの結果と、テストのプロジェクトがあればテストの結果
- YukkuriMovieMaker4 で実際に動かして確かめたこと。使った YukkuriMovieMaker4 のバージョンを添え、GPU に関わる変更では GPU の名前とドライバーのバージョンも添えてください
- 実行できなかったテストと、その理由
実際に動かして観察したこと、コードを読んで判断したこと、推測したことを分けて書いてください。
出力を変えるつもりの無い変更では、変更前と変更後で出力が一致することを確かめてください。`--golden` と `--verify` を持つハーネスのプロジェクトがあるリポジトリでは、それで描画を比べられます。基準値は、手元の環境で変更前のコミットから作り直し、作り直した基準値はコミットに含めないでください。そのようなハーネスが無いリポジトリでは、変更前と変更後の出力を比べてください。サブモジュールの中にあるハーネスは、この確認には使いません。
性能の改善を主張するときは、1 回の測定で判断しないでください。
- 同じ機材、ドライバー、設定、電源の条件で、変更前と変更後のビルドを交互に繰り返し測ってください。
- GPU と CPU の温度で値が変わるため、測定の間を空けてください。
- ほかのプロセスが GPU を使っていない状態で測ってください。
- 正しさの確認と性能の測定は、別々に実行してください。確認のための処理が、測定値を変えるためです。
---
## コードの規約
変更する箇所で既に使われている実装のパターンと書き方に従ってください。既存の実装どうしが食い違っているときは、どちらかを機械的にまねず、README とテストに照らして意図された動きを確かめ、それに合うほうへ揃えてください。
自分の変更で増えたビルドの警告は、放置せず原因を直してください。
新しく書くコードには、コメントを入れず、コメントアウトしたコードも残さないでください。既存のコードにあるコメントとドキュメントコメントは残してください。
---
## コミットの規約
- 1 つのコミットは、目的ごとのまとまりを保てる範囲で、できるだけ小さくしてください。どのコミットも、それ単独でビルドが通るようにしてください。
- 実装の変更と、それを確かめるテストは、別のコミットに分けてください。
- 件名は日本語で書き、50 文字以内に収め、「〜する」の形で終えてください。「〜を追加する」「〜を直す」はよい例です。「〜の追加」「〜を修正」のように名詞で終える形は使いません。
- 件名を日本語で書けないときは、プルリクエストにその旨を書いてください。
- 本文は書かないでください。例外は、リリースノートでの変更の分類を指定する行だけです。この行が要るときは、書き方をレビューで伝えます。
---
## 行動規範
貢献するすべての人に、[行動規範](CODE_OF_CONDUCT.md)に従うことを求めます。
+65 -10
ファイルの表示
@@ -11,6 +11,8 @@ YukkuriMovieMaker4(YMM4)上で動作する、UTAU 音源から歌声を合
単独音・連続音・CVVC のいずれの音源にも対応し、UST ファイルの読み込みにも対応します。
セリフのかなから組み立てたノートは、ピアノロールのノートエディターで編集できます。
![Image](https://git.routersys.com/routersys/YMM4-UTAU/raw/branch/main/docs/UTAU.png)
---
## 目次
@@ -24,7 +26,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、UTAU 音源から歌声を合
- [3. UST ファイルの読み込み](#3-ust-ファイルの読み込み)
- [4. ノートエディター](#4-ノートエディター)
- [5. WORLD による合成](#5-world-による合成)
- [6. 解析キャッシュ](#6-解析キャッシュ)
- [6. 解析と合成の再利用](#6-解析と合成の再利用)
5. [音程記法](#音程記法)
6. [パラメータ一覧](#パラメータ一覧)
7. [ノートの項目一覧](#ノートの項目一覧)
@@ -32,9 +34,10 @@ YukkuriMovieMaker4(YMM4)上で動作する、UTAU 音源から歌声を合
9. [対応フォーマット](#対応フォーマット)
10. [制限事項](#制限事項)
11. [注意事項](#注意事項)
12. [免責事項](#免責事項)
13. [サードパーティライセンス](#サードパーティライセンス)
14. [ライセンス](#ライセンス)
12. [不具合の報告](#不具合の報告)
13. [免責事項](#免責事項)
14. [サードパーティライセンス](#サードパーティライセンス)
15. [ライセンス](#ライセンス)
---
@@ -46,7 +49,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、UTAU 音源から歌声を合
セリフに書いたかなからノート列を組み立てるほか、UST ファイルのパスを書くとその譜面をそのまま読み込みます。組み立てたノートはノートエディターで編集でき、音程・長さ・ビブラート・ポルタメント・表現曲線を調整できます。
音声ファイルの分析結果と、合成した音を区間ごとにメモリへ保持するため、2 回目以降の合成が速くなります。1 つのノートを直したときは、そのノートを含む区間だけを合成し直します。
音声ファイルの分析結果と、合成した音を区間ごとにメモリへ保持するため、2 回目以降の合成が速くなります。1 つのノートを直したときは、その周りの区間だけを合成し直します。
画面の表示は日本語のほか、英語、簡体字と繁体字の中国語、韓国語、スペイン語、アラビア語、インドネシア語に対応します。
@@ -120,8 +123,15 @@ YukkuriMovieMaker4(YMM4)上で動作する、UTAU 音源から歌声を合
- ノートを 2 回押すと音程の制御点を追加し、制御点を引くと動かし、右で押すと削除します。制御点の間の曲線は S 字・直線・R 字・J 字から選べます。
- 下の帯では、子音速度・音量・モジュレーションをノートごとの棒として、フォルマントと息の量を曲線として引いて編集できます。
- 休符の挿入、ノートの削除、すべてのノートの選択、表示範囲に合わせる操作をボタンから行えます。
- ノートを右で押すと品書きが出ます。押したノートが選択に入っていないときは、そのノートだけを選び直します。選択の中を押したときは選択をそのまま保ちます。
- 品書きからは、選んだノートすべてに対してオクターブ上げとオクターブ下げ、長さを吸着に合わせる操作を行えます。オクターブの上げ下げは、端に当たるノートがあるときは選択全体の移動量を縮めるため、ノートどうしの音程差は変わりません。長さを吸着に合わせる操作は、吸着なしのときは行いません。
- 品書きの「戻す」からは、選んだノートすべての音程曲線・ビブラート・発声タイミング・ノート全体を既定へ戻せます。歌詞と音程と長さは残ります。
- 品書きからノートをコピーして貼り付けられます。貼り付けたノートは選択の後ろに入り、そのまま選択されます。コピーした内容は別のアイテムの編集画面へも貼り付けられます。
- 品書きの「歌詞をまとめて編集」では、選んだノートの歌詞を別の窓で一度に書き換えられます。空白と改行で区切り、漢字とかなは 1 文字ずつ、引用符で囲んだ部分はまとめて 1 つのノートになります。歌詞の数とノートの数を窓に表示し、歌詞の方が多いときは余りを捨て、ノートの方が多いときは残りのノートをそのままにします。
- 品書きの「別ウィンドウで編集」では、編集画面をそのまま別の窓へ移せます。窓を閉じると元の位置へ戻り、編集した内容はそのまま残ります。窓を開いている間は「ノートを編集」のボタンを押せません。
- ノートは隙間なく並びます。間を空けるときは休符を挿入します。
- 原音設定に見つからなかった歌詞があるときは、工具列の右端に警告として並びます。ノートエディターを開いたままでも、合成をやり直すたびに書き換わります。
- 工具列の文言が幅に収まらないときは、2 秒おいてから端まで送り、2 秒おいて戻ります。収まっているときは動きません。
- 編集内容は YMM4 の取り消しとやり直しに対応します。合成の結果として作られる情報は取り消しの対象になりません。
### 5. WORLD による合成
@@ -130,15 +140,17 @@ YukkuriMovieMaker4(YMM4)上で動作する、UTAU 音源から歌声を合
分析は 5 ミリ秒間隔で行い、基本周波数は 55Hz から 1100Hz の範囲で求めます。基本周波数の推定は Harvest と Dio から選べます。Dio を選んだときは StoneMask で補正します。伸ばす区間の扱いは、折り返して繰り返すループと、一様に引き伸ばすストレッチから選べます。
子音の長さはノートの子音速度で決まり、倍率は 2^((100-値)/100) です。フォルマントはスペクトル包絡を半音単位で周波数方向へ移し、高域の強調はナイキスト周波数における利得を dB で指定して周波数特性を傾け、息の量は非周期性指標を強めます。モジュレーションは原音の音程の揺れをどれだけ残すかを決めます。
子音の長さはノートの子音速度で決まり、倍率は $2^{(100 - \text{値})/100}$ です。フォルマントはスペクトル包絡を半音単位で周波数方向へ移し、高域の強調はナイキスト周波数における利得を dB で指定して周波数特性を傾け、息の量は非周期性指標を強めます。モジュレーションは原音の音程の揺れをどれだけ残すかを決めます。
出力は 16 ビットのモノラル WAV です。ノートの母音から口パクに使う情報も作ります。
### 6. 解析キャッシュ
### 6. 解析と合成の再利用
分析結果は、音声ファイルの場所と更新日時と読み込む範囲と推定方法を鍵にしてメモリへ保持します。2 回目以降の合成では分析をやり直しません。上限は既定で 512MB で、64MB から 4096MB まで設定できます。上限を超えると古い物から捨てます。設定画面から破棄することもできます。複数の音声ファイルの分析は複数のコアで並列に行います。
合成した音そのものも区間ごとに保持します。区間は休符で切れる塊で、50 ミリ秒より離れたノートの間で分かれます。鍵には、その区間の合成に使う値をすべて入れます。原音の場所と切り出す範囲、ノートの音程・長さ・子音速度・音量・モジュレーション・ビブラート・音程曲線、合成の設定、区間の位置と長さです。1 つのノートを直すと、そのノートを含む区間だけを合成し直し、残りはそのまま使います。上限は既定で 256MB で、64MB から 4096MB まで設定できます。超えると古い物から捨てます。設定画面の破棄は分析と区間の両方を消します。表現の帯でフォルマントか息の量の曲線を引いているときは、曲線が時刻ごとに変わるため区間の再利用を行いません。
区間ごとの合成は複数のコアで並列に行います。区間は互いに独立しているため、並列にしても結果は変わりません。同時に使うコアの数は、区間の大きさから必要な作業領域を見積もり、合計が 768MB に収まる範囲で決めます。
合成した音そのものも区間ごとに保持します。区間は休符で切れる塊で、50 ミリ秒より離れたノートの間で分かれます。鍵には、その区間の合成に使う値をすべて入れます。原音の場所と切り出す範囲、ノートの音程・長さ・子音速度・音量・モジュレーション・ビブラート・音程曲線、合成の設定、区間の位置と長さです。鍵は区間の中での相対的な位置で作るため、後ろのノートが前後へ動いただけの区間はそのまま使います。音程や音量のように位置が動かない編集では、直したノートを含む区間だけを合成し直します。ノートの長さを変えたときは、区間の切れ目がフレームの丸めでずれる分だけ、いくつかの区間を合成し直します。上限は既定で 256MB で、64MB から 4096MB まで設定できます。超えると古い物から捨てます。設定画面の破棄は分析と区間の両方を消します。表現の帯でフォルマントか息の量の曲線を引いているときは、曲線が時刻ごとに変わるため区間の再利用を行いません。
---
@@ -188,7 +200,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、UTAU 音源から歌声を合
| 基本 | 音程 | C4 | C1 〜 C7 | C-1 〜 G9 | 一覧からは C1 から C7 を選べます。ピアノロールで引くとそれ以外の音程にも動かせます。 |
| 基本 | 長さ | 240tick | 15 〜 1920 | 15 〜 30720 | 480 ティックが四分音符です。テンポと話速から実際の長さが決まります。 |
| 基本 | テンポ | 0BPM | 0 〜 400 | 0 〜 400 | 0 でこの譜面のテンポに従います。0 より大きい値はこのノートから先に効き、20 から 400 の範囲へ収めます。 |
| 表現 | 子音速度 | 100 | 0 〜 200 | 0 〜 200 | 子音の長さの倍率です。100 が原音のままで、倍率は 2^((100-値)/100) になります。 |
| 表現 | 子音速度 | 100 | 0 〜 200 | 0 〜 200 | 子音の長さの倍率です。100 が原音のままで、倍率は $2^{(100 - \text{値})/100}$ になります。 |
| 表現 | 音量 | 100% | 0 〜 200 | 0 〜 200 | ノートごとの音量です。 |
| 表現 | モジュレーション | 0% | -200 〜 200 | -200 〜 200 | 原音の音程の揺れをどれだけ残すかです。 |
| 時間 | 先行発声 | 0ms | 0 〜 500 | 0 〜 5000 | 0 のときは原音設定の値を使います。 |
@@ -258,6 +270,47 @@ YMM4 の設定画面の「音声」に「UTAU」として表示されます。
---
## 不具合の報告
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で送信します。同意は求めません。止める設定もありません。
送信する数には上限があります。YMM4 の 1 回の起動で送る報告は、YMM4-Telemetry で報告する別のプラグインと合わせて 20 件までです。例外の型と発生位置が同じ報告は 3 件までです。上限を超えた報告と、送信先から待つよう求められている間に起きた報告は、送信も退避もしません。
送信する情報は次のとおりです。
| 種類 | 内容 |
|---|---|
| 例外 | 型の完全名、メッセージ、スタックトレース |
| 発生位置 | モジュール名、関数名、ファイル名、行番号、プラグイン自身のコードかどうか |
| プラグイン | アセンブリ名、バージョン |
| 実行環境 | OS の名前とバージョン、.NET のバージョン、CPU のアーキテクチャ、論理プロセッサ数 |
| 識別子 | YMM4 の起動ごとに決まるセッション識別子、報告ごとの識別子 |
| 時刻 | 報告を作った時刻(UTC) |
メッセージとファイル名は、送信の前に置き換えを通します。置き換えるのは、Windows のユーザー名、ユーザーフォルダー、AppData のパス、マシン名、ドメイン名、メールアドレス、IPv4 アドレスです。送信元の IP アドレスは受信側へ渡す手前で取り除いています。
音声ファイルの中身は送信しません。継続して個人を追跡する識別子も持ちません。セッション識別子は YMM4 を起動し直すと別の値になります。
置き換えの対象は上に挙げた文字列だけです。例外のメッセージにファイルのパスが含まれる場合、音源のフォルダーの名前と音声ファイルの名前はそのまま残ります。音声ファイルを読み込めなかった報告には、その音声ファイルのパスが含まれます。音源を利用者フォルダーの外へ置いている場合、パスは置き換えを受けずにそのまま残ります。
送信するのは想定していない例外だけです。本プラグインが例外を握り潰す箇所と、YMM4 へ処理を返す境界の両方で報告します。画面の操作やバックグラウンドの処理で未処理になった例外も報告しますが、本プラグインのコードが関わる例外に限ります。YMM4 本体やほかのプラグインで起きた例外は送信しません。
次の例外は送信しません。
| 種類 | 例 |
|---|---|
| 利用者へ知らせるための失敗 | エイリアスが見つからない、合成できるノートがない、セリフが空 |
| 更新の確認の通信の失敗 | GitHub へ接続できない |
| 探索と設定ファイルの読み取りで想定している失敗 | フォルダーを開く権限がない、文字コードを判別できない、パスが長すぎる |
音源の音声ファイルを読み込めなかった場合は送信します。読み込みの不具合を見つけるためです。
送信できなかった報告は YMM4 のユーザーフォルダーへ退避します。次に YMM4 を起動したあと、本プラグインを読み込むか、同じく YMM4-Telemetry で報告する別のプラグインが動き始めると、退避した報告を 1 回の起動で 10 件まで送り直します。送信も再送も非同期に行うため、起動と合成が遅くなることはありません。
実装は [YMM4-Telemetry](https://github.com/routersys/YMM4-Telemetry) をサブモジュールとして取り込んでいます。
---
## 免責事項
本プラグインは MIT ライセンスのもとで公開されています。
@@ -271,13 +324,15 @@ YMM4 の設定画面の「音声」に「UTAU」として表示されます。
## サードパーティライセンス
本プラグインは音声の分析と合成に以下のサードパーティソフトウェアを同梱・使用しています。ライセンスの全文は、リポジトリの [`.github/LICENSE/WorldNet.txt`](.github/LICENSE/WorldNet.txt) と、配布パッケージの `LICENSE` フォルダーに収録しています。
本プラグインは以下のサードパーティソフトウェアを同梱・使用しています。ライセンスの全文は、リポジトリの [`.github/LICENSE`](.github/LICENSE) と、配布パッケージの `LICENSE` フォルダーに収録しています。
| ソフトウェア | 用途 | ライセンス | 著作権表示 |
|---|---|---|---|
| [WorldNet](https://github.com/routersys/WorldNet) | 音声の分析と合成 | MIT License | Copyright (c) 2026 routersys |
| [NAudio](https://github.com/naudio/NAudio) | 音声ファイルの読み書き | MIT License | Copyright (c) Mark Heath & Contributors |
| [WORLD](https://github.com/mmorise/World) | WorldNet が移植した音声分析合成システム | 修正 BSD License | Copyright (c) 2010 M. Morise |
| [Ooura FFT](https://www.kurims.kyoto-u.ac.jp/~ooura/fft.html) | WORLD が使う高速フーリエ変換 | 作者が定める条件 | Copyright Takuya OOURA, 1996-2001 |
| [OpenUtau](https://github.com/stakira/OpenUtau) | 歌詞の区切り方の規約。試験には参照実装として原実装を転写しています | MIT License | Copyright (c) 2014 StAkira |
---
+46
ファイルの表示
@@ -0,0 +1,46 @@
# セキュリティポリシー
## サポートするバージョン
セキュリティの修正は、最新のリリースだけを対象にします。
| バージョン | サポート |
|---|---|
| 最新のリリース | 対象 |
| それより前のリリース | 対象外 |
修正は、最新のリリースの次のバージョンとして公開します。報告する前に、最新のリリースでも問題が起きるかを確かめてください。
## 対象とする問題
本プラグインのコードと配布パッケージに原因がある問題を対象にします。たとえば次のようなものです。
- 細工したプロジェクトファイルや素材を開くと、意図しない処理が実行される
- 更新の確認などで行う通信の内容を、第三者が書き換えられる
- 不具合の情報を自動で送信するプラグインで、個人を特定できる情報が伏せられないまま送信される
配布パッケージに同梱したライブラリの脆弱性は、本プラグインを通じて悪用できる場合に対象にします。
YukkuriMovieMaker4 本体や、ほかのプラグインに原因がある問題は対象外です。それぞれの開発者へ報告してください。
## 報告の方法
脆弱性は、公開の Issue に書かないでください。修正を公開する前に悪用されるおそれがあります。
1. リポジトリの URL の末尾に `/security` を付けたページを開き、「Report a vulnerability」から非公開で報告してください。報告の内容を見られるのは、開発者と報告した人、開発者が招いた人だけです。
2. この方法が使えないときは、github.routersys@gmail.com へメールで報告してください。
報告には、次の内容を書いてください。分からない項目は書かなくて構いません。
| 項目 | 内容 |
|---|---|
| バージョン | 問題を確かめたプラグインのバージョンと、YukkuriMovieMaker4 のバージョン |
| 再現の手順 | 問題を起こす操作と、使ったプロジェクトファイルや素材 |
| 影響 | 問題によって何ができてしまうか |
| 回避策 | 分かっていれば、修正までの間に被害を避ける方法 |
## 報告の後
開発者は、報告を受け取ったら内容を確かめ、修正の見込みを返信します。
報告した人は、修正を含むバージョンが出るまで、報告の内容を明かさないでください。問題の詳細は、修正版の公開後に開発者が公表します。
+4 -6
ファイルの表示
@@ -4,7 +4,6 @@ using System.Windows.Media;
using UTAU.Notes;
using UTAU.ViewModels;
using UTAU.Views;
using YukkuriMovieMaker.Controls;
namespace UTAU.Tests;
@@ -37,12 +36,11 @@ public sealed class ExpressionStripAlignmentTests
return result;
}
static (NoteEditor Editor, NoteEditorViewModel ViewModel, Border Host) Build(int noteCount)
static (NoteEditorSurface Editor, NoteEditorViewModel ViewModel, Border Host) Build(int noteCount)
{
var editor = new NoteEditor();
var button = (PopupButton)editor.Content;
var root = (Grid)button.PopupContent!;
button.PopupContent = null;
var editor = new NoteEditorSurface();
var root = (Grid)editor.Content!;
editor.Content = null;
var pronounce = new UTAUVoicePronounce();
for (var index = 0; index < noteCount; index++)
+1 -3
ファイルの表示
@@ -5,7 +5,6 @@ using UTAU.Notes;
using UTAU.Phonemes;
using UTAU.Synthesis;
using UTAU.ViewModels;
using WorldNet;
namespace UTAU.Tests;
@@ -457,9 +456,8 @@ public sealed class CurveRenderingTests : IDisposable
{
var notes = NoteSequenceBuilder.Build("<!C4:1/4>あ", NoteBuildOptions.Create(60));
var units = Phonemizer.Phonemize(bank, TempoMap.Create(notes, TimeBase.Default), null, PhonemizeOptions.Default);
using var arena = new WorldArena();
var settings = RenderSettings.Default with { Estimator = F0Estimator.Dio };
return new UtauRenderer(settings, curves, cache, new SegmentCache(SegmentCache.DefaultBudgetBytes)).Render(units, arena).Samples;
return new UtauRenderer(settings, curves, cache, new SegmentCache(SegmentCache.DefaultBudgetBytes)).Render(units).Samples;
}
[Fact]
+251
ファイルの表示
@@ -0,0 +1,251 @@
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using UTAU.Notes;
namespace UTAU.Tests;
public sealed class LyricSplitterTests
{
static class Reference
{
static readonly Regex whitespace = new(@"\s");
static readonly Regex standalone = new(
@"\p{IsCJKUnifiedIdeographs}|\p{IsHiragana}|\p{IsKatakana}|\p{IsHangulSyllables}");
static readonly Regex contracted = new(@"[ゃゅょぁぃぅぇぉャュョァィゥェォ]");
public static List<string> Split(string? text)
{
if (text == null)
{
return new List<string>();
}
var lyrics = new List<string>();
var builder = new StringBuilder();
var etor = StringInfo.GetTextElementEnumerator(text);
while (etor.MoveNext())
{
string ele = etor.GetTextElement();
if (whitespace.IsMatch(ele))
{
if (builder.Length > 0)
{
lyrics.Add(builder.ToString());
builder.Clear();
}
}
else if (contracted.IsMatch(ele))
{
builder.Append(ele);
lyrics.Add(builder.ToString());
builder.Clear();
}
else if (standalone.IsMatch(ele))
{
if (builder.Length > 0)
{
lyrics.Add(builder.ToString());
builder.Clear();
}
builder.Append(ele);
}
else if (ele == "\"")
{
while (etor.MoveNext())
{
string ele1 = etor.GetTextElement();
if (ele1 == "\"")
{
lyrics.Add(builder.ToString());
builder.Clear();
break;
}
else
{
builder.Append(ele1);
}
}
}
else
{
if (builder.Length > 0 && standalone.IsMatch(builder.ToString()))
{
lyrics.Add(builder.ToString());
builder.Clear();
}
builder.Append(ele);
}
}
if (builder.Length > 0)
{
lyrics.Add(builder.ToString());
builder.Clear();
}
return lyrics;
}
public static string Join(IEnumerable<string> lyrics)
{
var builder = new StringBuilder();
foreach (string lyric in lyrics)
{
if (builder.Length != 0)
{
builder.Append(" ");
}
if (lyric.Length == 0)
{
builder.Append("\"\"");
}
else if (whitespace.IsMatch(lyric))
{
builder.Append($"\"{lyric}\"");
}
else if (standalone.IsMatch(lyric))
{
if (lyric.Length == 1)
{
builder.Append(lyric);
}
else if (lyric.Length == 2 && contracted.IsMatch(lyric.Substring(1)))
{
builder.Append(lyric);
}
else
{
builder.Append($"\"{lyric}\"");
}
}
else
{
builder.Append(lyric);
}
}
return builder.ToString();
}
}
static readonly string[] Alphabet =
[
"a", "b", "z", "R", "-", "+", "_", "1", "#", "[", "]",
" ", "\t", "\n", "\r", " ", "\"",
"あ", "か", "し", "ん", "ゃ", "ゅ", "ょ", "ぁ",
"ア", "カ", "ャ", "ヴ", "ー",
"中", "文", "русский", "가", "각", "𠮷", "é",
];
static string RandomText(Random random)
{
var builder = new StringBuilder();
var length = random.Next(0, 12);
for (var index = 0; index < length; index++)
builder.Append(Alphabet[random.Next(Alphabet.Length)]);
return builder.ToString();
}
[Fact]
public void SplittingSeparatesWordsAndStandaloneCharacters()
{
Assert.Equal(
["a", "word", "中", "文", "русский", "가", "각", "갂", "ひ", "ら", "が", "な", "がな", "", "two words"],
LyricSplitter.Split("a word中文русский가각갂ひらがな \"がな\" \"\" \"two words\""));
}
[Fact]
public void JoiningQuotesOnlyWhatSplittingWouldNotRecover()
{
Assert.Equal(
"a word 中 文 русский 가 각 갂 ひ ら が な \"がな\" \"\" \"two words\"",
LyricSplitter.Join(["a", "word", "中", "文", "русский", "가", "각", "갂", "ひ", "ら", "が", "な", "がな", "", "two words"]));
}
[Fact]
public void ASmallKanaStaysWithTheKanaBeforeIt()
{
Assert.Equal(["きゃ", "ら", "ば", "ん"], LyricSplitter.Split("きゃらばん"));
}
[Fact]
public void ASmallKanaAfterALatinWordKeepsThatWord()
{
Assert.Equal(["aゃ"], LyricSplitter.Split("aゃ"));
}
[Fact]
public void AnUnclosedQuoteSwallowsTheRest()
{
Assert.Equal(["ab"], LyricSplitter.Split("\"ab"));
}
[Fact]
public void AQuoteAfterLatinCharactersKeepsThemInTheSameLyric()
{
Assert.Equal(["abcdef"], LyricSplitter.Split("abc\"def\""));
}
[Fact]
public void EveryKindOfWhitespaceSeparates()
{
Assert.Equal(["a", "b", "c", "d", "e"], LyricSplitter.Split("a b\tc\nd\re"));
}
[Fact]
public void SplittingNothingGivesNothing()
{
Assert.Empty(LyricSplitter.Split(null));
Assert.Empty(LyricSplitter.Split(string.Empty));
Assert.Empty(LyricSplitter.Split(" "));
}
[Fact]
public void JoiningAndSplittingRestoresEveryLyric()
{
string[] lyrics =
[
"a", "word", "中", "文", "中文", " ", " ", "-", "12 3# $%^",
"中русский", "русский", "ひ", "ら", "が", "な", "がな", "two words", "가", "각", "갂", "갃간",
];
Assert.Equal(lyrics, LyricSplitter.Split(LyricSplitter.Join(lyrics)));
}
[Fact]
public void SplittingMatchesTheOpenUtauImplementation()
{
var random = new Random(20260822);
var mismatch = 0;
var first = string.Empty;
for (var trial = 0; trial < 100000; trial++)
{
var text = RandomText(random);
if (LyricSplitter.Split(text).SequenceEqual(Reference.Split(text)))
continue;
if (mismatch == 0)
first = text;
mismatch++;
}
Assert.True(mismatch == 0, $"mismatch={mismatch} first={first}");
}
[Fact]
public void JoiningMatchesTheOpenUtauImplementation()
{
var random = new Random(20260823);
var mismatch = 0;
var first = string.Empty;
for (var trial = 0; trial < 100000; trial++)
{
var lyrics = Reference.Split(RandomText(random));
if (LyricSplitter.Join(lyrics) == Reference.Join(lyrics))
continue;
if (mismatch == 0)
first = string.Join("|", lyrics);
mismatch++;
}
Assert.True(mismatch == 0, $"mismatch={mismatch} first={first}");
}
}
+161
ファイルの表示
@@ -0,0 +1,161 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using UTAU.ViewModels;
using UTAU.Views;
namespace UTAU.Tests;
[Collection("Wpf")]
public sealed class LyricsBulkEditLayoutTests
{
const double RowHeight = 26.0;
static T RunSta<T>(Func<T> action)
{
var result = default(T)!;
Exception? error = null;
var thread = new Thread(() =>
{
try
{
result = action();
}
catch (Exception exception)
{
error = exception;
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
if (error is not null)
throw new InvalidOperationException(error.Message, error);
return result;
}
static IEnumerable<DependencyObject> Descend(DependencyObject root)
{
var count = VisualTreeHelper.GetChildrenCount(root);
for (var index = 0; index < count; index++)
{
var child = VisualTreeHelper.GetChild(root, index);
yield return child;
foreach (var descendant in Descend(child))
yield return descendant;
}
}
sealed record Placed(string Name, double Left, double Top, double Width, double Height)
{
public double Right => Left + Width;
public double Bottom => Top + Height;
}
static (Placed[] Buttons, Placed Box, double Width, double Height) Measure(double width, double height)
=> RunSta(() =>
{
var view = new LyricsBulkEditView { DataContext = new LyricsBulkEditViewModel("あ い う", 3) };
var host = new Border { Width = width, Height = height, Child = view };
for (var pass = 0; pass < 3; pass++)
{
host.Measure(new Size(width, height));
host.Arrange(new Rect(0.0, 0.0, width, height));
host.UpdateLayout();
}
Placed Place(FrameworkElement element, string name)
{
var origin = element.TranslatePoint(new Point(0.0, 0.0), host);
return new Placed(name, origin.X, origin.Y, element.ActualWidth, element.ActualHeight);
}
var buttons = Descend(host)
.OfType<Button>()
.Select(x => Place(x, (string)x.Content))
.OrderBy(x => x.Left)
.ToArray();
var box = Place((TextBox)view.FindName("LyricBox")!, "LyricBox");
return (buttons, box, width, height);
});
[Fact]
public void TheButtonsAreNotCutOffAtTheBottom()
{
var placed = Measure(560.0, 280.0);
Assert.NotEmpty(placed.Buttons);
foreach (var button in placed.Buttons)
Assert.True(button.Bottom <= placed.Height, $"{button.Name} bottom={button.Bottom} host={placed.Height}");
Assert.Equal(placed.Height, placed.Buttons.Max(x => x.Bottom), 6);
}
[Fact]
public void TheButtonsFillTheRowWithoutAGapAboveOrBelow()
{
var placed = Measure(560.0, 280.0);
foreach (var button in placed.Buttons)
{
Assert.Equal(RowHeight, button.Height, 6);
Assert.Equal(placed.Height - RowHeight, button.Top, 6);
}
}
[Fact]
public void TheButtonsSitAgainstEachOtherWithNoGap()
{
var placed = Measure(560.0, 280.0);
for (var index = 1; index < placed.Buttons.Length; index++)
Assert.Equal(placed.Buttons[index - 1].Right, placed.Buttons[index].Left, 6);
}
[Fact]
public void TheLastButtonReachesTheRightEdge()
{
var placed = Measure(560.0, 280.0);
Assert.Equal(placed.Width, placed.Buttons[^1].Right, 6);
}
[Fact]
public void TheTextBoxFillsEverythingAboveTheButtons()
{
var placed = Measure(560.0, 280.0);
Assert.Equal(0.0, placed.Box.Left, 6);
Assert.Equal(0.0, placed.Box.Top, 6);
Assert.Equal(placed.Width, placed.Box.Width, 6);
Assert.Equal(placed.Height - RowHeight, placed.Box.Height, 6);
}
[Fact]
public void NothingIsCutOffAtTheSmallestAllowedSize()
{
var placed = Measure(360.0, 220.0);
foreach (var button in placed.Buttons)
{
Assert.True(button.Bottom <= placed.Height, $"{button.Name} bottom={button.Bottom}");
Assert.Equal(RowHeight, button.Height, 6);
}
Assert.Equal(placed.Width, placed.Buttons[^1].Right, 6);
Assert.True(placed.Box.Height > 0.0);
}
[Fact]
public void TheHintIsCarriedByTheTextBoxRatherThanTakingUpARow()
{
var tip = RunSta(() =>
{
var view = new LyricsBulkEditView { DataContext = new LyricsBulkEditViewModel("あ", 1) };
return ((TextBox)view.FindName("LyricBox")!).ToolTip;
});
Assert.Equal(Texts.LyricsBulkEditHint, tip);
}
}
+338
ファイルの表示
@@ -0,0 +1,338 @@
using System.Windows;
using System.Windows.Controls;
using UTAU.Notes;
using UTAU.ViewModels;
using UTAU.Views;
using YukkuriMovieMaker.UndoRedo;
namespace UTAU.Tests;
[Collection("Wpf")]
public sealed class LyricsBulkEditTests
{
sealed class Recorder
{
readonly List<IUndoRedoCommand> commands = [];
public Recorder(UTAUVoicePronounce pronounce)
=> pronounce.UndoRedoCommandCreated += (_, e) =>
{
if (e.Command is IUndoRedoCommand command)
commands.Add(command);
};
public int Recorded => commands.Count(x => !x.IsEmpty);
public void UndoAll()
{
for (var index = commands.Count - 1; index >= 0; index--)
{
if (!commands[index].IsEmpty)
commands[index].Undo();
}
}
}
static NoteEditorViewModel CreateViewModel(UTAUVoicePronounce pronounce, params string[] lyrics)
{
foreach (var lyric in lyrics)
pronounce.Notes.Add(new UTAUNote { Lyric = lyric, Tone = 60, LengthTicks = UTAUNote.DefaultLengthTicks });
return new NoteEditorViewModel(pronounce);
}
static NoteEditorViewModel CreateViewModel(params string[] lyrics)
=> CreateViewModel(new UTAUVoicePronounce(), lyrics);
static T RunSta<T>(Func<T> action)
{
var result = default(T)!;
Exception? error = null;
var thread = new Thread(() =>
{
try
{
result = action();
}
catch (Exception exception)
{
error = exception;
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
if (error is not null)
throw new InvalidOperationException(error.Message, error);
return result;
}
[Fact]
public void TheSelectedLyricsComeOutInNoteOrder()
{
var viewModel = CreateViewModel("あ", "り", "が", "と");
viewModel.Select(viewModel.Notes[3]);
viewModel.ToggleSelection(viewModel.Notes[1]);
Assert.Equal("り と", viewModel.ReadSelectedLyrics());
}
[Fact]
public void ALyricThatWouldNotSurviveSplittingComesOutQuoted()
{
var viewModel = CreateViewModel("あい", "R");
viewModel.SelectAll();
Assert.Equal("\"あい\" R", viewModel.ReadSelectedLyrics());
}
[Fact]
public void ApplyingReplacesTheLyricsOfTheSelectionInOrder()
{
var viewModel = CreateViewModel("あ", "あ", "あ");
viewModel.SelectAll();
var applied = viewModel.ApplyLyrics(LyricSplitter.Split("かきく"));
Assert.Equal(3, applied);
Assert.Equal(["か", "き", "く"], viewModel.Notes.Select(x => x.Note.Lyric));
}
[Fact]
public void ApplyingFollowsScoreOrderNotTheOrderTheNotesWereClicked()
{
var viewModel = CreateViewModel("あ", "い", "う");
viewModel.Select(viewModel.Notes[2]);
viewModel.ToggleSelection(viewModel.Notes[0]);
viewModel.ApplyLyrics(LyricSplitter.Split("かき"));
Assert.Equal(["か", "い", "き"], viewModel.Notes.Select(x => x.Note.Lyric));
}
[Fact]
public void ReadingAndApplyingAgreeOnTheOrderOfAScatteredSelection()
{
var viewModel = CreateViewModel("あ", "い", "う", "え");
viewModel.Select(viewModel.Notes[3]);
viewModel.ToggleSelection(viewModel.Notes[0]);
viewModel.ToggleSelection(viewModel.Notes[2]);
viewModel.ApplyLyrics(LyricSplitter.Split(viewModel.ReadSelectedLyrics()));
Assert.Equal(["あ", "い", "う", "え"], viewModel.Notes.Select(x => x.Note.Lyric));
}
[Fact]
public void ApplyingLeavesTheNotesOutsideTheSelectionAlone()
{
var viewModel = CreateViewModel("あ", "い", "う");
viewModel.Select(viewModel.Notes[1]);
viewModel.ApplyLyrics(LyricSplitter.Split("か"));
Assert.Equal(["あ", "か", "う"], viewModel.Notes.Select(x => x.Note.Lyric));
}
[Fact]
public void ExtraLyricsBeyondTheSelectionAreDropped()
{
var viewModel = CreateViewModel("あ", "い");
viewModel.SelectAll();
var applied = viewModel.ApplyLyrics(LyricSplitter.Split("かきくけこ"));
Assert.Equal(2, applied);
Assert.Equal(["か", "き"], viewModel.Notes.Select(x => x.Note.Lyric));
}
[Fact]
public void NotesBeyondTheLyricsKeepWhatTheyHad()
{
var viewModel = CreateViewModel("あ", "い", "う", "え");
viewModel.SelectAll();
var applied = viewModel.ApplyLyrics(LyricSplitter.Split("かき"));
Assert.Equal(2, applied);
Assert.Equal(["か", "き", "う", "え"], viewModel.Notes.Select(x => x.Note.Lyric));
}
[Fact]
public void ApplyingNothingChangesNothing()
{
var viewModel = CreateViewModel("あ", "い");
viewModel.SelectAll();
var applied = viewModel.ApplyLyrics(LyricSplitter.Split(" "));
Assert.Equal(0, applied);
Assert.Equal(["あ", "い"], viewModel.Notes.Select(x => x.Note.Lyric));
}
[Fact]
public void AQuotedRunBecomesOneLyric()
{
var viewModel = CreateViewModel("あ", "い");
viewModel.SelectAll();
viewModel.ApplyLyrics(LyricSplitter.Split("\"a あ\" \"\""));
Assert.Equal(["a あ", ""], viewModel.Notes.Select(x => x.Note.Lyric));
}
[Fact]
public void TheLyricsSurviveAReadAndAWriteRoundTrip()
{
var viewModel = CreateViewModel("あ", "きゃ", "two words", "", "R", "-", "中");
viewModel.SelectAll();
var text = viewModel.ReadSelectedLyrics();
viewModel.ApplyLyrics(LyricSplitter.Split(text));
Assert.Equal(["あ", "きゃ", "two words", "", "R", "-", "中"], viewModel.Notes.Select(x => x.Note.Lyric));
}
[Fact]
public void UndoingBringsEveryLyricBack()
{
var pronounce = new UTAUVoicePronounce();
var viewModel = CreateViewModel(pronounce, "あ", "い", "う");
viewModel.SelectAll();
var recorder = new Recorder(pronounce);
viewModel.ApplyLyrics(LyricSplitter.Split("かきく"));
Assert.Equal(3, recorder.Recorded);
recorder.UndoAll();
Assert.Equal(["あ", "い", "う"], viewModel.Notes.Select(x => x.Note.Lyric));
}
[Fact]
public void AnUnchangedLyricIsNotRecorded()
{
var pronounce = new UTAUVoicePronounce();
var viewModel = CreateViewModel(pronounce, "あ", "い", "う");
viewModel.SelectAll();
var recorder = new Recorder(pronounce);
viewModel.ApplyLyrics(LyricSplitter.Split("あ い く"));
Assert.Equal(1, recorder.Recorded);
}
[Fact]
public void EditingTheLyricsNeedsASelection()
{
var viewModel = CreateViewModel("あ");
viewModel.Select(null);
Assert.False(viewModel.EditLyricsCommand.CanExecute(null));
}
[Fact]
public void TheCommandAsksTheViewToOpenTheWindow()
{
var viewModel = CreateViewModel("あ", "い");
viewModel.SelectAll();
var asked = 0;
viewModel.LyricsEditRequested += (_, _) => asked++;
viewModel.EditLyricsCommand.Execute(null);
Assert.Equal(1, asked);
}
[Fact]
public void TheDialogCountsTheLyricsAgainstTheNotes()
{
var dialog = new LyricsBulkEditViewModel("あ い う", 3);
Assert.Equal(3, dialog.LyricCount);
Assert.Equal(3, dialog.NoteCount);
Assert.False(dialog.HasMismatch);
Assert.Equal(string.Format(Texts.LyricCountFormat, 3, 3), dialog.CountText);
}
[Fact]
public void TheDialogReportsAMismatchAsTheTextChanges()
{
var dialog = new LyricsBulkEditViewModel("あ い う", 3);
dialog.Text = "かき";
Assert.Equal(2, dialog.LyricCount);
Assert.True(dialog.HasMismatch);
Assert.Equal(string.Format(Texts.LyricCountFormat, 2, 3), dialog.CountText);
}
[Fact]
public void TheDialogPutsTheTextBackWhenReverted()
{
var dialog = new LyricsBulkEditViewModel("あ い う", 3);
dialog.Text = "かき";
Assert.True(dialog.ResetCommand.CanExecute(null));
dialog.ResetCommand.Execute(null);
Assert.Equal("あ い う", dialog.Text);
Assert.False(dialog.ResetCommand.CanExecute(null));
}
[Fact]
public void TheDialogRaisesItsCountAsTheTextChanges()
{
var dialog = new LyricsBulkEditViewModel("あ", 1);
var raised = new List<string>();
dialog.PropertyChanged += (_, e) => raised.Add(e.PropertyName ?? string.Empty);
dialog.Text = "あ い";
Assert.Contains(nameof(LyricsBulkEditViewModel.Text), raised);
Assert.Contains(nameof(LyricsBulkEditViewModel.LyricCount), raised);
Assert.Contains(nameof(LyricsBulkEditViewModel.CountText), raised);
Assert.Contains(nameof(LyricsBulkEditViewModel.HasMismatch), raised);
}
[Fact]
public void TheWindowShowsTheViewAndTakesItsViewModel()
{
var hosted = RunSta(() =>
{
var dialog = new LyricsBulkEditViewModel("あ い", 2);
var window = new LyricsBulkEditWindow(dialog);
return (window.Content, ReferenceEquals(window.DataContext, dialog), window.Title);
});
Assert.IsType<LyricsBulkEditView>(hosted.Content);
Assert.True(hosted.Item2);
Assert.Equal(Texts.EditLyrics, hosted.Title);
}
[Fact]
public void TheWindowFollowsTheThemeOfTheHost()
{
var basedOn = RunSta(() =>
{
var window = new LyricsBulkEditWindow(new LyricsBulkEditViewModel("あ", 1));
return window.Style?.BasedOn?.TargetType;
});
Assert.Equal(typeof(Window), basedOn);
}
[Fact]
public void TheApplyButtonTellsTheWindowToClose()
{
var applied = RunSta(() =>
{
var view = new LyricsBulkEditView { DataContext = new LyricsBulkEditViewModel("あ", 1) };
var count = 0;
view.Applied += (_, _) => count++;
var button = (Button)view.FindName("ApplyButton")!;
button.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent, button));
return count;
});
Assert.Equal(1, applied);
}
}
+565
ファイルの表示
@@ -0,0 +1,565 @@
using UTAU;
using UTAU.Notes;
using UTAU.ViewModels;
using YukkuriMovieMaker.UndoRedo;
namespace UTAU.Tests;
[Collection("NoteClipboard")]
public sealed class NoteBatchEditTests
{
sealed class Recorder
{
readonly List<IUndoRedoCommand> commands = [];
public Recorder(UTAUVoicePronounce pronounce)
=> pronounce.UndoRedoCommandCreated += (_, e) =>
{
if (e.Command is IUndoRedoCommand command)
commands.Add(command);
};
public int Recorded => commands.Count(x => !x.IsEmpty);
public void UndoAll()
{
for (var index = commands.Count - 1; index >= 0; index--)
{
if (!commands[index].IsEmpty)
commands[index].Undo();
}
}
}
static NoteEditorViewModel CreateViewModel(UTAUVoicePronounce pronounce, params int[] tones)
{
foreach (var tone in tones)
pronounce.Notes.Add(new UTAUNote { Lyric = "あ", Tone = tone, LengthTicks = UTAUNote.DefaultLengthTicks });
return new NoteEditorViewModel(pronounce);
}
static NoteEditorViewModel CreateViewModel(params int[] tones)
=> CreateViewModel(new UTAUVoicePronounce(), tones);
static void SelectAllOf(NoteEditorViewModel viewModel) => viewModel.SelectAll();
[Fact]
public void RaisingAnOctaveAddsTwelveSemitonesToEverySelectedNote()
{
var viewModel = CreateViewModel(60, 62, 64);
SelectAllOf(viewModel);
viewModel.OctaveUpCommand.Execute(null);
Assert.Equal([72, 74, 76], viewModel.Notes.Select(x => x.Note.Tone));
}
[Fact]
public void LoweringAnOctaveSubtractsTwelveSemitonesFromEverySelectedNote()
{
var viewModel = CreateViewModel(60, 62, 64);
SelectAllOf(viewModel);
viewModel.OctaveDownCommand.Execute(null);
Assert.Equal([48, 50, 52], viewModel.Notes.Select(x => x.Note.Tone));
}
[Fact]
public void OnlyTheSelectedNotesMove()
{
var viewModel = CreateViewModel(60, 62, 64);
viewModel.Select(viewModel.Notes[1]);
viewModel.OctaveUpCommand.Execute(null);
Assert.Equal([60, 74, 64], viewModel.Notes.Select(x => x.Note.Tone));
}
[Fact]
public void TheWholeShiftShrinksSoThatTheIntervalsSurvive()
{
var viewModel = CreateViewModel(100, 118);
SelectAllOf(viewModel);
viewModel.OctaveUpCommand.Execute(null);
Assert.Equal([109, 127], viewModel.Notes.Select(x => x.Note.Tone));
Assert.Equal(18, viewModel.Notes[1].Note.Tone - viewModel.Notes[0].Note.Tone);
}
[Fact]
public void ANoteAlreadyAtTheTopOfTheRangeStopsTheWholeSelection()
{
var viewModel = CreateViewModel(60, 127);
SelectAllOf(viewModel);
viewModel.OctaveUpCommand.Execute(null);
Assert.Equal([60, 127], viewModel.Notes.Select(x => x.Note.Tone));
}
[Fact]
public void TheWholeShiftShrinksDownwardsAsWell()
{
var viewModel = CreateViewModel(9, 27);
SelectAllOf(viewModel);
viewModel.OctaveDownCommand.Execute(null);
Assert.Equal([0, 18], viewModel.Notes.Select(x => x.Note.Tone));
Assert.Equal(18, viewModel.Notes[1].Note.Tone - viewModel.Notes[0].Note.Tone);
}
[Fact]
public void ANoteAlreadyAtTheBottomOfTheRangeStopsTheWholeSelection()
{
var viewModel = CreateViewModel(0, 60);
SelectAllOf(viewModel);
viewModel.OctaveDownCommand.Execute(null);
Assert.Equal([0, 60], viewModel.Notes.Select(x => x.Note.Tone));
}
[Fact]
public void UndoingAnOctaveBringsEveryToneBack()
{
var pronounce = new UTAUVoicePronounce();
var viewModel = CreateViewModel(pronounce, 60, 62, 64);
SelectAllOf(viewModel);
var recorder = new Recorder(pronounce);
viewModel.OctaveUpCommand.Execute(null);
Assert.Equal(3, recorder.Recorded);
recorder.UndoAll();
Assert.Equal([60, 62, 64], viewModel.Notes.Select(x => x.Note.Tone));
}
[Fact]
public void QuantizingRoundsEveryLengthToTheSnapDivision()
{
var viewModel = CreateViewModel(60, 62, 64);
viewModel.SnapDivision = new NoteDivision(16);
viewModel.Notes[0].Note.LengthTicks = 130;
viewModel.Notes[1].Note.LengthTicks = 180;
viewModel.Notes[2].Note.LengthTicks = 470;
SelectAllOf(viewModel);
viewModel.QuantizeLengthCommand.Execute(null);
Assert.Equal([120, 240, 480], viewModel.Notes.Select(x => x.Note.LengthTicks));
}
[Fact]
public void QuantizingNeverProducesANoteShorterThanTheMinimum()
{
var viewModel = CreateViewModel(60);
viewModel.SnapDivision = new NoteDivision(16);
viewModel.Notes[0].Note.LengthTicks = 40;
SelectAllOf(viewModel);
viewModel.QuantizeLengthCommand.Execute(null);
Assert.Equal(UTAUNote.MinimumLengthTicks, viewModel.Notes[0].Note.LengthTicks);
}
[Fact]
public void QuantizingDoesNothingWhileTheSnapIsFree()
{
var viewModel = CreateViewModel(60);
viewModel.SnapDivision = NoteDivision.Free;
viewModel.Notes[0].Note.LengthTicks = 130;
SelectAllOf(viewModel);
Assert.False(viewModel.QuantizeLengthCommand.CanExecute(null));
viewModel.QuantizeLengthCommand.Execute(null);
Assert.Equal(130, viewModel.Notes[0].Note.LengthTicks);
}
[Fact]
public void TheFreeSnapLeavesEveryValidLengthWhereItIs()
{
var viewModel = CreateViewModel(60);
viewModel.SnapDivision = NoteDivision.Free;
foreach (var length in new[]
{
UTAUNote.MinimumLengthTicks, 16, 47, 130, 479, 480, 481, 1919, UTAUNote.MaximumLengthTicks,
})
{
Assert.Equal(length, viewModel.SnapLength(length));
}
}
[Fact]
public void UndoingAQuantizeBringsEveryLengthBack()
{
var pronounce = new UTAUVoicePronounce();
var viewModel = CreateViewModel(pronounce, 60, 62);
viewModel.SnapDivision = new NoteDivision(16);
viewModel.Notes[0].Note.LengthTicks = 130;
viewModel.Notes[1].Note.LengthTicks = 180;
SelectAllOf(viewModel);
var recorder = new Recorder(pronounce);
viewModel.QuantizeLengthCommand.Execute(null);
recorder.UndoAll();
Assert.Equal([130, 180], viewModel.Notes.Select(x => x.Note.LengthTicks));
}
[Fact]
public void ResettingTheVibratoRestoresEveryField()
{
var viewModel = CreateViewModel(60, 62);
var vibrato = viewModel.Notes[0].Note.Vibrato;
vibrato.LengthPercent = 60.0;
vibrato.PeriodMilliseconds = 300.0;
vibrato.DepthCents = 90.0;
vibrato.FadeInPercent = 40.0;
vibrato.FadeOutPercent = 50.0;
vibrato.PhasePercent = -30.0;
vibrato.OffsetPercent = 20.0;
SelectAllOf(viewModel);
viewModel.ResetVibratoCommand.Execute(null);
Assert.Equal(0.0, vibrato.LengthPercent);
Assert.Equal(175.0, vibrato.PeriodMilliseconds);
Assert.Equal(25.0, vibrato.DepthCents);
Assert.Equal(20.0, vibrato.FadeInPercent);
Assert.Equal(20.0, vibrato.FadeOutPercent);
Assert.Equal(0.0, vibrato.PhasePercent);
Assert.Equal(0.0, vibrato.OffsetPercent);
Assert.False(vibrato.IsEnabled);
}
[Fact]
public void UndoingAVibratoResetBringsEveryFieldBack()
{
var pronounce = new UTAUVoicePronounce();
var viewModel = CreateViewModel(pronounce, 60);
var vibrato = viewModel.Notes[0].Note.Vibrato;
vibrato.LengthPercent = 60.0;
vibrato.DepthCents = 90.0;
SelectAllOf(viewModel);
var recorder = new Recorder(pronounce);
viewModel.ResetVibratoCommand.Execute(null);
recorder.UndoAll();
Assert.Equal(60.0, vibrato.LengthPercent);
Assert.Equal(90.0, vibrato.DepthCents);
}
[Fact]
public void ResettingTheTimingRestoresTheOverridesAndTheFades()
{
var viewModel = CreateViewModel(60);
var note = viewModel.Notes[0].Note;
note.PreutteranceOverride = 120.0;
note.OverlapOverride = 60.0;
note.StartPointMilliseconds = 30.0;
note.FadeInMilliseconds = 90.0;
note.FadeOutMilliseconds = 90.0;
SelectAllOf(viewModel);
viewModel.ResetTimingCommand.Execute(null);
Assert.Equal(UTAUNote.FollowOtoValue, note.PreutteranceOverride);
Assert.Equal(UTAUNote.FollowOtoValue, note.OverlapOverride);
Assert.Equal(UTAUNote.DefaultStartPointMilliseconds, note.StartPointMilliseconds);
Assert.Equal(UTAUNote.DefaultFadeInMilliseconds, note.FadeInMilliseconds);
Assert.Equal(UTAUNote.DefaultFadeOutMilliseconds, note.FadeOutMilliseconds);
}
[Fact]
public void UndoingATimingResetBringsEveryValueBack()
{
var pronounce = new UTAUVoicePronounce();
var viewModel = CreateViewModel(pronounce, 60);
var note = viewModel.Notes[0].Note;
note.PreutteranceOverride = 120.0;
note.OverlapOverride = 60.0;
note.StartPointMilliseconds = 30.0;
note.FadeInMilliseconds = 90.0;
note.FadeOutMilliseconds = 90.0;
SelectAllOf(viewModel);
var recorder = new Recorder(pronounce);
viewModel.ResetTimingCommand.Execute(null);
Assert.Equal(5, recorder.Recorded);
recorder.UndoAll();
Assert.Equal(120.0, note.PreutteranceOverride);
Assert.Equal(60.0, note.OverlapOverride);
Assert.Equal(30.0, note.StartPointMilliseconds);
Assert.Equal(90.0, note.FadeInMilliseconds);
Assert.Equal(90.0, note.FadeOutMilliseconds);
}
[Fact]
public void ResettingTheTimingLeavesTheLyricAndTheToneAndTheLength()
{
var viewModel = CreateViewModel(64);
var note = viewModel.Notes[0].Note;
note.LengthTicks = 321;
note.PreutteranceOverride = 120.0;
SelectAllOf(viewModel);
viewModel.ResetTimingCommand.Execute(null);
Assert.Equal("あ", note.Lyric);
Assert.Equal(64, note.Tone);
Assert.Equal(321, note.LengthTicks);
}
[Fact]
public void ResettingANoteClearsEveryParameterAndEveryPitchPoint()
{
var viewModel = CreateViewModel(64);
var note = viewModel.Notes[0].Note;
note.LengthTicks = 321;
note.TempoOverride = 150.0;
note.Velocity = 40.0;
note.Intensity = 160.0;
note.Modulation = -80.0;
note.PreutteranceOverride = 120.0;
note.Vibrato.LengthPercent = 70.0;
note.PitchPoints.Add(new PitchPoint(0, -200.0));
note.PitchPoints.Add(new PitchPoint(120, 300.0, PitchPointShape.Linear));
SelectAllOf(viewModel);
viewModel.ResetNoteCommand.Execute(null);
Assert.Equal(UTAUNote.FollowScoreValue, note.TempoOverride);
Assert.Equal(UTAUNote.DefaultVelocity, note.Velocity);
Assert.Equal(UTAUNote.DefaultIntensity, note.Intensity);
Assert.Equal(UTAUNote.DefaultModulation, note.Modulation);
Assert.Equal(UTAUNote.FollowOtoValue, note.PreutteranceOverride);
Assert.Equal(0.0, note.Vibrato.LengthPercent);
Assert.Empty(note.PitchPoints);
Assert.Equal("あ", note.Lyric);
Assert.Equal(64, note.Tone);
Assert.Equal(321, note.LengthTicks);
}
[Fact]
public void UndoingANoteResetBringsThePitchPointsAndTheParametersBack()
{
var pronounce = new UTAUVoicePronounce();
var viewModel = CreateViewModel(pronounce, 60);
var note = viewModel.Notes[0].Note;
note.Velocity = 40.0;
note.PitchPoints.Add(new PitchPoint(0, -200.0));
note.PitchPoints.Add(new PitchPoint(120, 300.0, PitchPointShape.Linear));
SelectAllOf(viewModel);
var recorder = new Recorder(pronounce);
viewModel.ResetNoteCommand.Execute(null);
recorder.UndoAll();
Assert.Equal(40.0, note.Velocity);
Assert.Equal(2, note.PitchPoints.Count);
Assert.Equal([0, 120], note.PitchPoints.Select(x => x.Ticks));
Assert.Equal([-200.0, 300.0], note.PitchPoints.Select(x => x.Cents));
}
[Fact]
public void PastingPutsTheCopiedNotesAfterTheSelection()
{
var pronounce = new UTAUVoicePronounce();
var viewModel = CreateViewModel(pronounce, 60, 62, 64);
viewModel.Select(viewModel.Notes[0]);
viewModel.CopyNotesCommand.Execute(null);
viewModel.PasteNotesCommand.Execute(null);
Assert.Equal([60, 60, 62, 64], viewModel.Notes.Select(x => x.Note.Tone));
Assert.Equal([60, 60, 62, 64], pronounce.Notes.Select(x => x.Tone));
}
[Fact]
public void CopyingTakesTheNotesInScoreOrderNotInTheOrderTheyWereClicked()
{
var viewModel = CreateViewModel(60, 62, 64);
viewModel.Select(viewModel.Notes[2]);
viewModel.ToggleSelection(viewModel.Notes[0]);
viewModel.CopyNotesCommand.Execute(null);
viewModel.PasteNotesCommand.Execute(null);
Assert.Equal([60, 62, 64, 60, 64], viewModel.Notes.Select(x => x.Note.Tone));
}
[Fact]
public void PastingKeepsTheOrderOfTheCopiedNotes()
{
var viewModel = CreateViewModel(60, 62, 64);
viewModel.SelectAll();
viewModel.CopyNotesCommand.Execute(null);
viewModel.PasteNotesCommand.Execute(null);
Assert.Equal([60, 62, 64, 60, 62, 64], viewModel.Notes.Select(x => x.Note.Tone));
}
[Fact]
public void PastingSelectsWhatItPastedAndNothingElse()
{
var viewModel = CreateViewModel(60, 62);
viewModel.Select(viewModel.Notes[0]);
viewModel.CopyNotesCommand.Execute(null);
viewModel.PasteNotesCommand.Execute(null);
Assert.Equal(1, viewModel.SelectedCount);
Assert.Same(viewModel.Notes[1], viewModel.SelectedNote);
Assert.True(viewModel.Notes[1].IsSelected);
Assert.False(viewModel.Notes[0].IsSelected);
}
[Fact]
public void ACopiedNoteCarriesItsParametersAndItsPitchPoints()
{
var viewModel = CreateViewModel(60, 62);
var note = viewModel.Notes[0].Note;
note.Lyric = "か";
note.LengthTicks = 321;
note.Velocity = 40.0;
note.Vibrato.LengthPercent = 70.0;
note.PitchPoints.Add(new PitchPoint(60, -150.0, PitchPointShape.Linear));
viewModel.Select(viewModel.Notes[0]);
viewModel.CopyNotesCommand.Execute(null);
viewModel.PasteNotesCommand.Execute(null);
var pasted = viewModel.Notes[1].Note;
Assert.NotSame(note, pasted);
Assert.Equal("か", pasted.Lyric);
Assert.Equal(321, pasted.LengthTicks);
Assert.Equal(40.0, pasted.Velocity);
Assert.Equal(70.0, pasted.Vibrato.LengthPercent);
Assert.Equal([60], pasted.PitchPoints.Select(x => x.Ticks));
Assert.Equal([-150.0], pasted.PitchPoints.Select(x => x.Cents));
Assert.Equal([PitchPointShape.Linear], pasted.PitchPoints.Select(x => x.Shape));
}
[Fact]
public void EditingAPastedNoteLeavesTheOriginalAlone()
{
var viewModel = CreateViewModel(60, 62);
viewModel.Select(viewModel.Notes[0]);
viewModel.CopyNotesCommand.Execute(null);
viewModel.PasteNotesCommand.Execute(null);
viewModel.Notes[1].Note.Lyric = "き";
Assert.Equal("あ", viewModel.Notes[0].Note.Lyric);
}
[Fact]
public void CopiedNotesReachAnotherEditor()
{
var origin = CreateViewModel(60, 62);
origin.SelectAll();
origin.CopyNotesCommand.Execute(null);
var other = CreateViewModel(64);
other.Select(other.Notes[0]);
other.PasteNotesCommand.Execute(null);
Assert.Equal([64, 60, 62], other.Notes.Select(x => x.Note.Tone));
Assert.Equal([60, 62], origin.Notes.Select(x => x.Note.Tone));
}
[Fact]
public void PastingTwiceMakesTwoIndependentNotes()
{
var viewModel = CreateViewModel(60);
viewModel.Select(viewModel.Notes[0]);
viewModel.CopyNotesCommand.Execute(null);
viewModel.PasteNotesCommand.Execute(null);
viewModel.PasteNotesCommand.Execute(null);
Assert.Equal(3, viewModel.Notes.Count);
Assert.NotSame(viewModel.Notes[1].Note, viewModel.Notes[2].Note);
}
[Fact]
public void UndoingAPasteTakesTheNotesOutOfTheScore()
{
var pronounce = new UTAUVoicePronounce();
var viewModel = CreateViewModel(pronounce, 60, 62);
viewModel.SelectAll();
viewModel.CopyNotesCommand.Execute(null);
var recorder = new Recorder(pronounce);
viewModel.PasteNotesCommand.Execute(null);
Assert.Equal(4, pronounce.Notes.Count);
recorder.UndoAll();
Assert.Equal(2, pronounce.Notes.Count);
Assert.Equal([60, 62], pronounce.Notes.Select(x => x.Tone));
}
[Fact]
public void CopyingNothingLeavesTheClipboardAlone()
{
var viewModel = CreateViewModel(60);
viewModel.Select(viewModel.Notes[0]);
viewModel.CopyNotesCommand.Execute(null);
viewModel.Select(null);
viewModel.CopyNotesCommand.Execute(null);
viewModel.PasteNotesCommand.Execute(null);
Assert.Equal(2, viewModel.Notes.Count);
}
[Fact]
public void PastingWithNothingSelectedAppendsToTheEnd()
{
var viewModel = CreateViewModel(60, 62);
viewModel.Select(viewModel.Notes[0]);
viewModel.CopyNotesCommand.Execute(null);
viewModel.Select(null);
viewModel.PasteNotesCommand.Execute(null);
Assert.Equal([60, 62, 60], viewModel.Notes.Select(x => x.Note.Tone));
}
[Fact]
public void EveryBatchOperationNeedsASelection()
{
var viewModel = CreateViewModel(60);
viewModel.Select(null);
Assert.False(viewModel.OctaveUpCommand.CanExecute(null));
Assert.False(viewModel.OctaveDownCommand.CanExecute(null));
Assert.False(viewModel.QuantizeLengthCommand.CanExecute(null));
Assert.False(viewModel.ResetVibratoCommand.CanExecute(null));
Assert.False(viewModel.ResetTimingCommand.CanExecute(null));
Assert.False(viewModel.ResetNoteCommand.CanExecute(null));
Assert.False(viewModel.CopyNotesCommand.CanExecute(null));
}
[Fact]
public void ThePositionsFollowTheLengthsAfterAQuantize()
{
var viewModel = CreateViewModel(60, 62, 64);
viewModel.SnapDivision = new NoteDivision(16);
viewModel.Notes[0].Note.LengthTicks = 130;
viewModel.Notes[1].Note.LengthTicks = 180;
SelectAllOf(viewModel);
viewModel.QuantizeLengthCommand.Execute(null);
Assert.Equal([0, 120, 360], viewModel.Notes.Select(x => x.StartTicks));
}
}
+541
ファイルの表示
@@ -0,0 +1,541 @@
using System.Windows.Threading;
using UTAU.Notes;
using UTAU.ViewModels;
using YukkuriMovieMaker.UndoRedo;
namespace UTAU.Tests;
[Collection("NoteClipboard")]
public sealed class NoteCollectionSyncTests
{
sealed class Recorder
{
readonly List<IUndoRedoCommand> commands = [];
bool recording = true;
public Recorder(UTAUVoicePronounce pronounce)
=> pronounce.UndoRedoCommandCreated += (_, e) =>
{
if (recording && e.Command is IUndoRedoCommand command)
commands.Add(command);
};
public int Recorded => commands.Count(x => !x.IsEmpty);
public void UndoAll()
{
recording = false;
for (var index = commands.Count - 1; index >= 0; index--)
{
if (!commands[index].IsEmpty)
commands[index].Undo();
}
}
public void RedoAll()
{
recording = false;
foreach (var command in commands)
{
if (!command.IsEmpty)
command.Redo();
}
}
}
static (UTAUVoicePronounce Pronounce, NoteEditorViewModel ViewModel) Create(params int[] tones)
{
var pronounce = new UTAUVoicePronounce();
foreach (var tone in tones)
pronounce.Notes.Add(new UTAUNote { Lyric = "あ", Tone = tone, LengthTicks = UTAUNote.DefaultLengthTicks });
return (pronounce, new NoteEditorViewModel(pronounce));
}
static void Pump()
{
var frame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(
new Action(() => frame.Continue = false),
DispatcherPriority.SystemIdle);
Dispatcher.PushFrame(frame);
}
static void AssertMirrors(UTAUVoicePronounce pronounce, NoteEditorViewModel viewModel)
{
Pump();
Assert.Equal(pronounce.Notes.Count, viewModel.Notes.Count);
for (var index = 0; index < pronounce.Notes.Count; index++)
Assert.Same(pronounce.Notes[index], viewModel.Notes[index].Note);
foreach (var note in viewModel.Notes)
Assert.Equal(viewModel.SelectedNotes.Contains(note), note.IsSelected);
Assert.Equal(viewModel.SelectedNote is null ? 0 : 1, viewModel.Notes.Count(x => x.IsPrimary));
Assert.Equal(viewModel.SelectedNotes.Count, viewModel.SelectedCount);
foreach (var selected in viewModel.SelectedNotes)
Assert.Contains(selected, viewModel.Notes);
if (viewModel.SelectedNote is { } primary)
{
Assert.Contains(primary, viewModel.Notes);
Assert.True(primary.IsPrimary);
}
var position = 0;
foreach (var note in viewModel.Notes)
{
Assert.Equal(position, note.StartTicks);
position += note.Note.LengthTicks;
}
Assert.Equal(position, viewModel.TotalTicks);
}
[Fact]
public void UndoingARestInsertTakesItOutOfTheEditor()
{
var (pronounce, viewModel) = Create(60, 62);
viewModel.Select(viewModel.Notes[0]);
var recorder = new Recorder(pronounce);
viewModel.InsertRestCommand.Execute(null);
Assert.Equal(3, viewModel.Notes.Count);
recorder.UndoAll();
Assert.Equal(2, viewModel.Notes.Count);
AssertMirrors(pronounce, viewModel);
}
[Fact]
public void UndoingARemovalPutsTheNotesBackInTheEditor()
{
var (pronounce, viewModel) = Create(60, 62, 64);
viewModel.Select(viewModel.Notes[1]);
var recorder = new Recorder(pronounce);
viewModel.RemoveNoteCommand.Execute(null);
Assert.Equal(2, viewModel.Notes.Count);
recorder.UndoAll();
Assert.Equal(3, viewModel.Notes.Count);
Assert.Equal([60, 62, 64], viewModel.Notes.Select(x => x.Note.Tone));
AssertMirrors(pronounce, viewModel);
}
[Fact]
public void UndoingAPasteTakesTheNotesOutOfTheEditor()
{
var (pronounce, viewModel) = Create(60, 62);
viewModel.SelectAll();
viewModel.CopyNotesCommand.Execute(null);
var recorder = new Recorder(pronounce);
viewModel.PasteNotesCommand.Execute(null);
Assert.Equal(4, viewModel.Notes.Count);
recorder.UndoAll();
Assert.Equal(2, viewModel.Notes.Count);
Assert.Equal([60, 62], viewModel.Notes.Select(x => x.Note.Tone));
AssertMirrors(pronounce, viewModel);
}
[Fact]
public void RedoingAPasteBringsTheNotesBack()
{
var (pronounce, viewModel) = Create(60, 62);
viewModel.SelectAll();
viewModel.CopyNotesCommand.Execute(null);
var recorder = new Recorder(pronounce);
viewModel.PasteNotesCommand.Execute(null);
recorder.UndoAll();
recorder.RedoAll();
Assert.Equal(4, viewModel.Notes.Count);
Assert.Equal([60, 62, 60, 62], viewModel.Notes.Select(x => x.Note.Tone));
AssertMirrors(pronounce, viewModel);
}
[Fact]
public void UndoingAPasteDropsTheSelectionItLeftBehind()
{
var (pronounce, viewModel) = Create(60, 62);
viewModel.SelectAll();
viewModel.CopyNotesCommand.Execute(null);
var recorder = new Recorder(pronounce);
viewModel.PasteNotesCommand.Execute(null);
Assert.Equal(2, viewModel.SelectedCount);
recorder.UndoAll();
Assert.Equal(0, viewModel.SelectedCount);
Assert.Null(viewModel.SelectedNote);
AssertMirrors(pronounce, viewModel);
}
[Fact]
public void UndoingARemovalLeavesTheSurvivingSelectionAlone()
{
var (pronounce, viewModel) = Create(60, 62, 64);
viewModel.Select(viewModel.Notes[0]);
var recorder = new Recorder(pronounce);
viewModel.RemoveNoteCommand.Execute(null);
var kept = viewModel.SelectedNote;
recorder.UndoAll();
Assert.Same(kept, viewModel.SelectedNote);
Assert.Equal(1, viewModel.SelectedCount);
AssertMirrors(pronounce, viewModel);
}
[Fact]
public void ANoteAddedFromOutsideShowsUpInTheEditor()
{
var (pronounce, viewModel) = Create(60, 62);
pronounce.Notes.Insert(1, new UTAUNote { Lyric = "か", Tone = 64 });
Assert.Equal(3, viewModel.Notes.Count);
Assert.Equal([60, 64, 62], viewModel.Notes.Select(x => x.Note.Tone));
AssertMirrors(pronounce, viewModel);
}
[Fact]
public void ANoteRemovedFromOutsideLeavesTheEditor()
{
var (pronounce, viewModel) = Create(60, 62, 64);
viewModel.SelectAll();
pronounce.Notes.RemoveAt(1);
Assert.Equal(2, viewModel.Notes.Count);
Assert.Equal(2, viewModel.SelectedCount);
AssertMirrors(pronounce, viewModel);
}
[Fact]
public void ClearingTheScoreFromOutsideEmptiesTheEditor()
{
var (pronounce, viewModel) = Create(60, 62, 64);
viewModel.SelectAll();
pronounce.Notes.Clear();
Assert.Empty(viewModel.Notes);
Assert.Equal(0, viewModel.SelectedCount);
Assert.Null(viewModel.SelectedNote);
AssertMirrors(pronounce, viewModel);
}
[Fact]
public void TheEditorKeepsTheViewModelOfANoteThatStays()
{
var (pronounce, viewModel) = Create(60, 62, 64);
var kept = viewModel.Notes[2];
pronounce.Notes.RemoveAt(0);
Assert.Same(kept, viewModel.Notes[1]);
AssertMirrors(pronounce, viewModel);
}
[Fact]
public void MovingANoteFromOutsideReordersTheEditor()
{
var (pronounce, viewModel) = Create(60, 62, 64);
var moved = viewModel.Notes[0];
pronounce.Notes.Move(0, 2);
Assert.Equal([62, 64, 60], viewModel.Notes.Select(x => x.Note.Tone));
Assert.Same(moved, viewModel.Notes[2]);
AssertMirrors(pronounce, viewModel);
}
[Fact]
public void TheEditorStopsListeningOnceDisposed()
{
var (pronounce, viewModel) = Create(60, 62);
viewModel.Dispose();
pronounce.Notes.Add(new UTAUNote { Lyric = "か", Tone = 64 });
Assert.Empty(viewModel.Notes);
}
[Fact]
public void ADroppedNoteStopsDrivingTheEditor()
{
var (pronounce, viewModel) = Create(60, 62, 64);
var dropped = pronounce.Notes[1];
pronounce.Notes.RemoveAt(1);
dropped.Tone = 80;
Assert.Equal([60, 64], viewModel.Notes.Select(x => x.Note.Tone));
AssertMirrors(pronounce, viewModel);
}
[Fact]
public void TheNoteListMirrorsAtOnceAndThePositionsFollowOnTheDispatcher()
{
var (pronounce, viewModel) = Create(60, 62, 64);
pronounce.Notes.RemoveAt(0);
Assert.Equal(2, viewModel.Notes.Count);
Assert.Equal([62, 64], viewModel.Notes.Select(x => x.Note.Tone));
Assert.Equal([UTAUNote.DefaultLengthTicks, UTAUNote.DefaultLengthTicks * 2], viewModel.Notes.Select(x => x.StartTicks));
Pump();
Assert.Equal([0, UTAUNote.DefaultLengthTicks], viewModel.Notes.Select(x => x.StartTicks));
Assert.Equal(UTAUNote.DefaultLengthTicks * 2, viewModel.TotalTicks);
}
[Fact]
public void ABurstOfChangesCostsOneLayoutPass()
{
var (pronounce, viewModel) = Create(60, 62, 64, 65, 67);
Pump();
var passes = 0;
viewModel.PropertyChanged += (_, e) =>
{
if (e.PropertyName == nameof(NoteEditorViewModel.TotalTicks))
passes++;
};
for (var index = 0; index < 4; index++)
pronounce.Notes.RemoveAt(0);
Pump();
Assert.Equal(1, passes);
AssertMirrors(pronounce, viewModel);
}
[Fact]
public void ScrollingCatchesUpAPendingLayout()
{
var (pronounce, viewModel) = Create(60, 62, 64);
pronounce.Notes.RemoveAt(0);
viewModel.SetViewport(0.0, 400.0);
Assert.Equal([0, UTAUNote.DefaultLengthTicks], viewModel.Notes.Select(x => x.StartTicks));
Assert.Equal(UTAUNote.DefaultLengthTicks * 2, viewModel.TotalTicks);
}
[Fact]
public void OurOwnEditsLeaveNothingPendingForTheDispatcher()
{
var (pronounce, viewModel) = Create(60, 62);
viewModel.Select(viewModel.Notes[0]);
viewModel.SnapDivision = new NoteDivision(16);
viewModel.InsertRestCommand.Execute(null);
Assert.Equal(3, viewModel.Notes.Count);
Assert.Equal([240, 120, 240], viewModel.Notes.Select(x => x.Note.LengthTicks));
Assert.Equal([0, 240, 360], viewModel.Notes.Select(x => x.StartTicks));
Assert.Equal(600, viewModel.TotalTicks);
}
static void AssertSameShapeAsAFreshEditor(UTAUVoicePronounce pronounce, NoteEditorViewModel viewModel)
{
Pump();
using var fresh = new NoteEditorViewModel(pronounce);
Assert.Equal(fresh.Notes.Select(x => x.Note), viewModel.Notes.Select(x => x.Note));
Assert.Equal(fresh.Notes.Select(x => x.StartTicks), viewModel.Notes.Select(x => x.StartTicks));
Assert.Equal(fresh.VisibleNotes.Select(x => x.Note), viewModel.VisibleNotes.Select(x => x.Note));
Assert.Equal(fresh.TotalTicks, viewModel.TotalTicks);
Assert.Equal(fresh.MinimumTone, viewModel.MinimumTone);
Assert.Equal(fresh.MaximumTone, viewModel.MaximumTone);
Assert.Equal(fresh.CanvasWidth, viewModel.CanvasWidth);
Assert.Equal(fresh.CanvasHeight, viewModel.CanvasHeight);
Assert.Equal(fresh.Keyboard.Count, viewModel.Keyboard.Count);
Assert.Equal(fresh.TimeGridLines.Count, viewModel.TimeGridLines.Count);
Assert.Equal(fresh.PitchCurve.Count, viewModel.PitchCurve.Count);
Assert.Equal(fresh.ExpressionBars.Count, viewModel.ExpressionBars.Count);
}
[Fact]
public void AnyRunOfChangesLeavesTheEditorWhereAFreshOneWouldBe()
{
var random = new Random(20260823);
for (var trial = 0; trial < 200; trial++)
{
var (pronounce, viewModel) = Create(60, 62, 64, 65);
var steps = random.Next(1, 9);
for (var step = 0; step < steps; step++)
{
switch (random.Next(6))
{
case 0:
pronounce.Notes.Insert(
random.Next(pronounce.Notes.Count + 1),
new UTAUNote { Lyric = "か", Tone = 50 + random.Next(30), LengthTicks = 60 + random.Next(400) });
break;
case 1 when pronounce.Notes.Count > 1:
pronounce.Notes.RemoveAt(random.Next(pronounce.Notes.Count));
break;
case 2 when pronounce.Notes.Count > 1:
pronounce.Notes.Move(random.Next(pronounce.Notes.Count), random.Next(pronounce.Notes.Count));
break;
case 3:
pronounce.Notes[random.Next(pronounce.Notes.Count)].LengthTicks = 60 + random.Next(400);
break;
case 4:
viewModel.Select(viewModel.Notes[random.Next(viewModel.Notes.Count)]);
viewModel.InsertRestCommand.Execute(null);
break;
default:
if (viewModel.Notes.Count > 1)
{
viewModel.Select(viewModel.Notes[random.Next(viewModel.Notes.Count)]);
viewModel.RemoveNoteCommand.Execute(null);
}
break;
}
}
AssertSameShapeAsAFreshEditor(pronounce, viewModel);
AssertMirrors(pronounce, viewModel);
viewModel.Dispose();
}
}
[Fact]
public void TheLayoutCatchesUpBeforeAnythingDrawsTheEditor()
{
var (pronounce, viewModel) = Create(60, 62, 64);
Pump();
var order = new List<string>();
viewModel.PropertyChanged += (_, e) =>
{
if (e.PropertyName == nameof(NoteEditorViewModel.TotalTicks))
order.Add("layout");
};
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => order.Add("draw")), DispatcherPriority.Render);
pronounce.Notes.RemoveAt(0);
Pump();
Assert.Equal(["layout", "draw"], order);
}
[Fact]
public void PastingIntoAnEditorThatWasEmptiedFromOutsideWorks()
{
var (pronounce, viewModel) = Create(60, 62);
viewModel.SelectAll();
viewModel.CopyNotesCommand.Execute(null);
pronounce.Notes.Clear();
viewModel.PasteNotesCommand.Execute(null);
Assert.Equal([60, 62], viewModel.Notes.Select(x => x.Note.Tone));
Assert.Equal(2, viewModel.SelectedCount);
AssertMirrors(pronounce, viewModel);
}
[Fact]
public void ADroppedNoteNeverStaysInTheDrawnList()
{
var (pronounce, viewModel) = Create(60, 62, 64);
Pump();
var dropped = viewModel.Notes[1];
Assert.Contains(dropped, viewModel.VisibleNotes);
pronounce.Notes.RemoveAt(1);
Assert.DoesNotContain(dropped, viewModel.VisibleNotes);
Assert.All(viewModel.VisibleNotes, x => Assert.Contains(x, viewModel.Notes));
AssertMirrors(pronounce, viewModel);
}
[Fact]
public void AChangeFromAnotherThreadIsBroughtBackToTheEditorThread()
{
var (pronounce, viewModel) = Create(60, 62);
Pump();
var thread = new Thread(() => pronounce.Notes.Add(new UTAUNote { Lyric = "か", Tone = 64 }));
thread.Start();
thread.Join();
Assert.Equal(2, viewModel.Notes.Count);
Pump();
Assert.Equal(3, viewModel.Notes.Count);
AssertMirrors(pronounce, viewModel);
}
[Fact]
public void AChangeThatArrivesAfterDisposalIsIgnored()
{
var (pronounce, viewModel) = Create(60, 62);
var thread = new Thread(() => pronounce.Notes.Add(new UTAUNote { Lyric = "か", Tone = 64 }));
thread.Start();
thread.Join();
viewModel.Dispose();
Pump();
Assert.Empty(viewModel.Notes);
Assert.Equal(3, pronounce.Notes.Count);
}
[Fact]
public void DisposingTwiceIsHarmless()
{
var (pronounce, viewModel) = Create(60, 62);
viewModel.Dispose();
viewModel.Dispose();
Assert.Empty(viewModel.Notes);
Assert.Equal(2, pronounce.Notes.Count);
}
[Fact]
public void ARedundantChangeCostsNoLayoutPass()
{
var (pronounce, viewModel) = Create(60, 62, 64);
Pump();
var passes = 0;
viewModel.PropertyChanged += (_, e) =>
{
if (e.PropertyName == nameof(NoteEditorViewModel.TotalTicks))
passes++;
};
pronounce.Notes.Move(1, 1);
Pump();
Assert.Equal(0, passes);
AssertMirrors(pronounce, viewModel);
}
[Fact]
public void RemovingManySelectedNotesResynchronisesOnlyOnce()
{
var (pronounce, viewModel) = Create(60, 62, 64, 65, 67, 69);
var rebuilds = 0;
viewModel.Notes.CollectionChanged += (_, _) => rebuilds++;
viewModel.Select(viewModel.Notes[1]);
viewModel.ToggleSelection(viewModel.Notes[2]);
viewModel.ToggleSelection(viewModel.Notes[3]);
viewModel.RemoveNoteCommand.Execute(null);
Assert.Equal(3, viewModel.Notes.Count);
Assert.Equal(1 + 3, rebuilds);
AssertMirrors(pronounce, viewModel);
}
}
+253
ファイルの表示
@@ -0,0 +1,253 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using UTAU.Notes;
using UTAU.ViewModels;
using UTAU.Views;
using YukkuriMovieMaker.Resources.Icons;
namespace UTAU.Tests;
[Collection("Wpf")]
public sealed class NoteContextMenuTests
{
const double PopupWidth = 980.0;
const double PopupHeight = 480.0;
static T RunSta<T>(Func<T> action)
{
var result = default(T)!;
Exception? error = null;
var thread = new Thread(() =>
{
try
{
result = action();
}
catch (Exception exception)
{
error = exception;
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
if (error is not null)
throw new InvalidOperationException(error.Message, error);
return result;
}
static (NoteEditorSurface Surface, NoteEditorViewModel ViewModel) Build(params int[] tones)
{
var pronounce = new UTAUVoicePronounce();
foreach (var tone in tones)
pronounce.Notes.Add(new UTAUNote { Lyric = "あ", Tone = tone, LengthTicks = UTAUNote.DefaultLengthTicks });
var viewModel = new NoteEditorViewModel(pronounce);
var surface = new NoteEditorSurface { DataContext = viewModel };
var host = new Border { Width = PopupWidth, Height = PopupHeight, Child = surface };
for (var pass = 0; pass < 3; pass++)
{
host.Measure(new Size(PopupWidth, PopupHeight));
host.Arrange(new Rect(0.0, 0.0, PopupWidth, PopupHeight));
host.UpdateLayout();
}
return (surface, viewModel);
}
static IEnumerable<DependencyObject> Descend(DependencyObject root)
{
var count = VisualTreeHelper.GetChildrenCount(root);
for (var index = 0; index < count; index++)
{
var child = VisualTreeHelper.GetChild(root, index);
yield return child;
foreach (var descendant in Descend(child))
yield return descendant;
}
}
static FrameworkElement NoteBody(NoteEditorSurface surface, NoteViewModel note)
=> Descend(surface.RollCanvas)
.OfType<Grid>()
.First(x => ReferenceEquals(x.DataContext, note));
[Fact]
public void TheRollCanvasCarriesAContextMenu()
{
var headers = RunSta(() =>
{
var (surface, _) = Build(60, 62);
return surface.RollCanvas.ContextMenu!.Items
.OfType<MenuItem>()
.Select(x => (string)x.Header)
.ToArray();
});
Assert.Equal(
[
Texts.NoteContextCopy,
Texts.NoteContextPaste,
Texts.SelectAllNotes,
Texts.OctaveUp,
Texts.OctaveDown,
Texts.QuantizeLength,
Texts.ResetGroup,
Texts.EditLyrics,
Texts.DetachEditor,
],
headers);
}
[Fact]
public void TheResetGroupHoldsTheFourResets()
{
var headers = RunSta(() =>
{
var (surface, _) = Build(60, 62);
var group = surface.RollCanvas.ContextMenu!.Items.OfType<MenuItem>()
.First(x => (string)x.Header == Texts.ResetGroup);
return group.Items.OfType<MenuItem>().Select(x => (string)x.Header).ToArray();
});
Assert.Equal(
[Texts.ResetPitch, Texts.ResetVibrato, Texts.ResetTiming, Texts.ResetNote],
headers);
}
[Fact]
public void EveryMenuEntryIsBoundToACommand()
{
var unbound = RunSta(() =>
{
var (surface, _) = Build(60, 62);
var items = surface.RollCanvas.ContextMenu!.Items.OfType<MenuItem>().ToList();
var leaves = items.Where(x => x.Items.Count == 0)
.Concat(items.SelectMany(x => x.Items.OfType<MenuItem>()))
.ToList();
return leaves.Where(x => x.Command is null).Select(x => (string)x.Header).ToArray();
});
Assert.Empty(unbound);
}
[Fact]
public void TheMenuCommandsAreTheOnesOfTheEditor()
{
var same = RunSta(() =>
{
var (surface, viewModel) = Build(60, 62);
var items = surface.RollCanvas.ContextMenu!.Items.OfType<MenuItem>().ToList();
return ReferenceEquals(items[0].Command, viewModel.CopyNotesCommand)
&& ReferenceEquals(items[3].Command, viewModel.OctaveUpCommand)
&& ReferenceEquals(items[4].Command, viewModel.OctaveDownCommand)
&& ReferenceEquals(items[5].Command, viewModel.QuantizeLengthCommand)
&& ReferenceEquals(items[6].Items.OfType<MenuItem>().Last().Command, viewModel.ResetNoteCommand)
&& ReferenceEquals(items[7].Command, viewModel.EditLyricsCommand)
&& ReferenceEquals(items[8].Command, viewModel.DetachCommand);
});
Assert.True(same);
}
static readonly (string Header, string Icon)[] ExpectedIcons =
[
(Texts.NoteContextCopy, IconKeys.ContentCopy),
(Texts.NoteContextPaste, IconKeys.ContentPaste),
(Texts.SelectAllNotes, IconKeys.SelectAll),
(Texts.OctaveUp, IconKeys.ArrowUp),
(Texts.OctaveDown, IconKeys.ArrowDown),
(Texts.QuantizeLength, IconKeys.Magnet),
(Texts.ResetGroup, IconKeys.Restore),
(Texts.ResetPitch, IconKeys.VectorCurve),
(Texts.ResetVibrato, IconKeys.SineWave),
(Texts.ResetTiming, IconKeys.TimerOutline),
(Texts.ResetNote, IconKeys.BackupRestore),
(Texts.EditLyrics, IconKeys.TextBoxEdit),
(Texts.DetachEditor, IconKeys.OpenInNew),
];
static List<MenuItem> Entries(ItemsControl menu)
{
var entries = new List<MenuItem>();
foreach (var item in menu.Items.OfType<MenuItem>())
{
entries.Add(item);
entries.AddRange(Entries(item));
}
return entries;
}
[Fact]
public void EveryMenuEntryAsksForItsOwnIcon()
{
var asked = RunSta(() =>
{
var (surface, _) = Build(60, 62);
var menu = surface.RollCanvas.ContextMenu!;
foreach (var key in ExpectedIcons.Select(x => x.Icon).Distinct())
menu.Resources[key] = key;
return Entries(menu).Select(x => ((string)x.Header, x.Icon as string)).ToArray();
});
Assert.Equal(ExpectedIcons.Length, asked.Length);
Assert.Equal(ExpectedIcons, asked.Select(x => (x.Item1, x.Item2 ?? string.Empty)).ToArray());
}
[Fact]
public void NoMenuEntryIsLeftWithoutAnIcon()
{
var missing = RunSta(() =>
{
var (surface, _) = Build(60, 62);
var menu = surface.RollCanvas.ContextMenu!;
foreach (var key in ExpectedIcons.Select(x => x.Icon).Distinct())
menu.Resources[key] = key;
return Entries(menu).Where(x => x.Icon is null).Select(x => (string)x.Header).ToArray();
});
Assert.Empty(missing);
}
[Fact]
public void RightClickingAnUnselectedNoteSelectsIt()
{
var selected = RunSta(() =>
{
var (surface, viewModel) = Build(60, 62, 64);
viewModel.Select(viewModel.Notes[0]);
var body = NoteBody(surface, viewModel.Notes[2]);
body.RaiseEvent(new MouseButtonEventArgs(Mouse.PrimaryDevice, 0, MouseButton.Right)
{
RoutedEvent = UIElement.MouseRightButtonDownEvent,
});
return (viewModel.SelectedCount, IsThird: ReferenceEquals(viewModel.SelectedNote, viewModel.Notes[2]));
});
Assert.Equal(1, selected.SelectedCount);
Assert.True(selected.IsThird);
}
[Fact]
public void RightClickingInsideTheSelectionKeepsIt()
{
var count = RunSta(() =>
{
var (surface, viewModel) = Build(60, 62, 64);
viewModel.SelectAll();
var body = NoteBody(surface, viewModel.Notes[1]);
body.RaiseEvent(new MouseButtonEventArgs(Mouse.PrimaryDevice, 0, MouseButton.Right)
{
RoutedEvent = UIElement.MouseRightButtonDownEvent,
});
return viewModel.SelectedCount;
});
Assert.Equal(3, count);
}
}
+295
ファイルの表示
@@ -0,0 +1,295 @@
using System.Windows;
using System.Windows.Controls;
using UTAU.Notes;
using UTAU.ViewModels;
using UTAU.Views;
using YukkuriMovieMaker.Controls;
namespace UTAU.Tests;
[Collection("Wpf")]
public sealed class NoteEditorDetachTests
{
static T RunSta<T>(Func<T> action)
{
var result = default(T)!;
Exception? error = null;
var thread = new Thread(() =>
{
try
{
result = action();
}
catch (Exception exception)
{
error = exception;
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
if (error is not null)
throw new InvalidOperationException(error.Message, error);
return result;
}
static UTAUVoicePronounce CreatePronounce(params string[] lyrics)
{
var pronounce = new UTAUVoicePronounce();
foreach (var lyric in lyrics)
pronounce.Notes.Add(new UTAUNote { Lyric = lyric, Tone = 60, LengthTicks = UTAUNote.DefaultLengthTicks });
return pronounce;
}
static NoteEditor CreateEditor(UTAUVoicePronounce pronounce)
{
var editor = new NoteEditor();
var host = new Border { Width = 200.0, Height = 26.0, Child = editor };
host.Measure(new Size(200.0, 26.0));
host.Arrange(new Rect(0.0, 0.0, 200.0, 26.0));
host.UpdateLayout();
editor.Pronounce = pronounce;
return editor;
}
static ContentControl PopupHostOf(NoteEditor editor)
=> (ContentControl)((PopupButton)editor.Content).PopupContent!;
static NoteEditorViewModel ViewModelOf(NoteEditorSurface surface)
=> (NoteEditorViewModel)surface.DataContext;
[Fact]
public void DetachingTakesTheSurfaceOutOfThePopupAndIntoTheWindow()
{
var state = RunSta(() =>
{
var editor = CreateEditor(CreatePronounce("あ", "い"));
var before = (NoteEditorSurface)PopupHostOf(editor).Content!;
editor.Detach();
var moved = ReferenceEquals(editor.DetachedWindow?.Surface, before);
var emptied = PopupHostOf(editor).Content is null;
editor.CloseDetached();
return (moved, emptied);
});
Assert.True(state.moved);
Assert.True(state.emptied);
}
[Fact]
public void ClosingTheWindowPutsTheSameSurfaceBackInThePopup()
{
var state = RunSta(() =>
{
var editor = CreateEditor(CreatePronounce("あ", "い"));
var before = PopupHostOf(editor).Content;
editor.Detach();
editor.CloseDetached();
return (
Same: ReferenceEquals(PopupHostOf(editor).Content, before),
Gone: editor.DetachedWindow is null);
});
Assert.True(state.Same);
Assert.True(state.Gone);
}
[Fact]
public void ThePopupButtonIsHeldShutWhileTheWindowIsOpen()
{
var state = RunSta(() =>
{
var editor = CreateEditor(CreatePronounce("あ"));
var button = (PopupButton)editor.Content;
editor.Detach();
var whileOpen = button.IsEnabled;
editor.CloseDetached();
return (whileOpen, AfterClose: button.IsEnabled);
});
Assert.False(state.whileOpen);
Assert.True(state.AfterClose);
}
[Fact]
public void DetachingBeginsAnEditAndClosingEndsIt()
{
var state = RunSta(() =>
{
var editor = CreateEditor(CreatePronounce("あ"));
var begun = 0;
var ended = 0;
editor.BeginEdit += (_, _) => begun++;
editor.EndEdit += (_, _) => ended++;
editor.Detach();
var afterDetach = (Begun: begun, Ended: ended);
editor.CloseDetached();
return (afterDetach, After: (Begun: begun, Ended: ended));
});
Assert.Equal((1, 0), state.afterDetach);
Assert.Equal((1, 1), state.After);
}
[Fact]
public void TheDetachedSurfaceEditsTheSamePronounce()
{
var pronounce = CreatePronounce("あ", "い", "う");
var applied = RunSta(() =>
{
var editor = CreateEditor(pronounce);
editor.Detach();
var viewModel = ViewModelOf(editor.DetachedWindow!.Surface!);
viewModel.SelectAll();
var count = viewModel.ApplyLyrics(LyricSplitter.Split("かきく"));
editor.CloseDetached();
return count;
});
Assert.Equal(3, applied);
Assert.Equal(["か", "き", "く"], pronounce.Notes.Select(x => x.Lyric));
}
[Fact]
public void TheEditsMadeInTheWindowAreThereWhenItCloses()
{
var pronounce = CreatePronounce("あ", "い");
var inPopup = RunSta(() =>
{
var editor = CreateEditor(pronounce);
editor.Detach();
var viewModel = ViewModelOf(editor.DetachedWindow!.Surface!);
viewModel.SelectAll();
viewModel.OctaveUpCommand.Execute(null);
editor.CloseDetached();
return ViewModelOf((NoteEditorSurface)PopupHostOf(editor).Content!)
.Notes.Select(x => x.Note.Tone).ToArray();
});
Assert.Equal([72, 72], inPopup);
Assert.Equal([72, 72], pronounce.Notes.Select(x => x.Tone));
}
[Fact]
public void ClearingThePronounceClosesTheWindow()
{
var state = RunSta(() =>
{
var editor = CreateEditor(CreatePronounce("あ"));
editor.Detach();
var whileOpen = editor.DetachedWindow is not null;
editor.Pronounce = null;
return (whileOpen, After: editor.DetachedWindow is not null, Back: PopupHostOf(editor).Content is NoteEditorSurface);
});
Assert.True(state.whileOpen);
Assert.False(state.After);
Assert.True(state.Back);
}
[Fact]
public void DetachingTwiceOpensOnlyOneWindow()
{
var same = RunSta(() =>
{
var editor = CreateEditor(CreatePronounce("あ"));
editor.Detach();
var first = editor.DetachedWindow;
editor.Detach();
var second = editor.DetachedWindow;
editor.CloseDetached();
return ReferenceEquals(first, second);
});
Assert.True(same);
}
[Fact]
public void TheCommandAsksTheViewToDetach()
{
var pronounce = CreatePronounce("あ");
var detached = RunSta(() =>
{
var editor = CreateEditor(pronounce);
var viewModel = ViewModelOf((NoteEditorSurface)PopupHostOf(editor).Content!);
viewModel.DetachCommand.Execute(null);
var open = editor.DetachedWindow is not null;
editor.CloseDetached();
return open;
});
Assert.True(detached);
}
static MenuItem DetachEntry(NoteEditorSurface surface)
=> surface.RollCanvas.ContextMenu!.Items
.OfType<MenuItem>()
.First(x => (string)x.Header == Texts.DetachEditor);
[Fact]
public void TheWindowDoesNotOfferToOpenAnotherWindow()
{
var state = RunSta(() =>
{
var editor = CreateEditor(CreatePronounce("あ"));
var surface = (NoteEditorSurface)PopupHostOf(editor).Content!;
var before = DetachEntry(surface).Visibility;
editor.Detach();
var whileOpen = DetachEntry(editor.DetachedWindow!.Surface!).Visibility;
editor.CloseDetached();
return (before, whileOpen, After: DetachEntry(surface).Visibility);
});
Assert.Equal(Visibility.Visible, state.before);
Assert.Equal(Visibility.Collapsed, state.whileOpen);
Assert.Equal(Visibility.Visible, state.After);
}
[Fact]
public void TheDetachCommandTurnsItselfOffWhileTheWindowIsOpen()
{
var state = RunSta(() =>
{
var editor = CreateEditor(CreatePronounce("あ"));
var viewModel = ViewModelOf((NoteEditorSurface)PopupHostOf(editor).Content!);
var before = viewModel.DetachCommand.CanExecute(null);
editor.Detach();
var whileOpen = (viewModel.DetachCommand.CanExecute(null), viewModel.IsDetached, viewModel.CanDetach);
editor.CloseDetached();
return (before, whileOpen, After: (viewModel.DetachCommand.CanExecute(null), viewModel.IsDetached, viewModel.CanDetach));
});
Assert.True(state.before);
Assert.Equal((false, true, false), state.whileOpen);
Assert.Equal((true, false, true), state.After);
}
[Fact]
public void TheWindowFollowsTheThemeOfTheHost()
{
var basedOn = RunSta(() =>
{
var window = new NoteEditorWindow(new NoteEditorSurface());
var result = window.Style?.BasedOn?.TargetType;
window.Release();
return result;
});
Assert.Equal(typeof(Window), basedOn);
}
[Fact]
public void TheWindowIsTitledLikeTheEditorButton()
{
var title = RunSta(() =>
{
var window = new NoteEditorWindow(new NoteEditorSurface());
var result = window.Title;
window.Release();
return result;
});
Assert.Equal(Texts.EditNotes, title);
}
}
+109
ファイルの表示
@@ -0,0 +1,109 @@
using System.Windows.Controls;
using UTAU.Notes;
using UTAU.ViewModels;
using UTAU.Views;
using YukkuriMovieMaker.Controls;
namespace UTAU.Tests;
[Collection("Wpf")]
public sealed class NoteEditorHostTests
{
static T RunSta<T>(Func<T> action)
{
var result = default(T)!;
Exception? error = null;
var thread = new Thread(() =>
{
try
{
result = action();
}
catch (Exception exception)
{
error = exception;
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
if (error is not null)
throw new InvalidOperationException(error.Message, error);
return result;
}
static UTAUVoicePronounce CreatePronounce()
{
var pronounce = new UTAUVoicePronounce();
pronounce.Notes.Add(new UTAUNote { Lyric = "あ", Tone = 60 });
return pronounce;
}
[Fact]
public void ThePopupHoldsTheEditingSurface()
{
var hosted = RunSta(() =>
{
var editor = new NoteEditor();
var button = (PopupButton)editor.Content;
var host = (ContentControl)button.PopupContent!;
return host.Content;
});
Assert.IsType<NoteEditorSurface>(hosted);
}
[Fact]
public void TheSurfaceGetsTheViewModelOfTheGivenPronounce()
{
var pronounce = CreatePronounce();
var context = RunSta(() =>
{
var editor = new NoteEditor();
editor.Pronounce = pronounce;
var button = (PopupButton)editor.Content;
var host = (ContentControl)button.PopupContent!;
return ((NoteEditorSurface)host.Content!).DataContext;
});
var viewModel = Assert.IsType<NoteEditorViewModel>(context);
Assert.Single(viewModel.Notes);
Assert.Same(pronounce.Notes[0], viewModel.Notes[0].Note);
}
[Fact]
public void ClearingThePronounceTakesTheViewModelAway()
{
var pronounce = CreatePronounce();
var context = RunSta(() =>
{
var editor = new NoteEditor();
editor.Pronounce = pronounce;
editor.Pronounce = null;
var button = (PopupButton)editor.Content;
var host = (ContentControl)button.PopupContent!;
return ((NoteEditorSurface)host.Content!).DataContext;
});
Assert.Null(context);
}
[Fact]
public void TheEditorAttributeBindsThePronounceToTheSurface()
{
var pronounce = CreatePronounce();
var context = RunSta(() =>
{
var attribute = new NoteEditorAttribute();
var control = attribute.Create();
attribute.SetBindings(control, pronounce, pronounce, typeof(UTAUVoicePronounce).GetProperty(nameof(UTAUVoicePronounce.Notes))!);
var editor = (NoteEditor)control;
var button = (PopupButton)editor.Content;
var host = (ContentControl)button.PopupContent!;
return ((NoteEditorSurface)host.Content!).DataContext;
});
var viewModel = Assert.IsType<NoteEditorViewModel>(context);
Assert.Same(pronounce.Notes[0], viewModel.Notes[0].Note);
}
}
+5 -7
ファイルの表示
@@ -4,7 +4,6 @@ using System.Windows.Media;
using UTAU.Notes;
using UTAU.ViewModels;
using UTAU.Views;
using YukkuriMovieMaker.Controls;
namespace UTAU.Tests;
@@ -38,12 +37,11 @@ public sealed class NoteEditorMeasuredLayoutTests
return result;
}
static (NoteEditor Editor, NoteEditorViewModel ViewModel, Border Host) Build()
static (NoteEditorSurface Editor, NoteEditorViewModel ViewModel, Border Host) Build()
{
var editor = new NoteEditor();
var button = (PopupButton)editor.Content;
var root = (Grid)button.PopupContent!;
button.PopupContent = null;
var editor = new NoteEditorSurface();
var root = (Grid)editor.Content!;
editor.Content = null;
var pronounce = new UTAUVoicePronounce();
for (var index = 0; index < NoteCount; index++)
@@ -102,7 +100,7 @@ public sealed class NoteEditorMeasuredLayoutTests
return false;
}
static ItemsControl KeyboardColumn(NoteEditor editor, NoteEditorViewModel viewModel)
static ItemsControl KeyboardColumn(NoteEditorSurface editor, NoteEditorViewModel viewModel)
=> Descend(editor.VerticalScroller)
.OfType<ItemsControl>()
.First(x => ReferenceEquals(x.ItemsSource, viewModel.Keyboard) && !IsUnder(x, editor.RollCanvas));
+123
ファイルの表示
@@ -0,0 +1,123 @@
using UTAU.Models;
using UTAU.Notes;
using UTAU.Phonemes;
using UTAU.Synthesis;
namespace UTAU.Tests;
public sealed class ParallelRenderTests : IDisposable
{
const double SampleMilliseconds = 300.0;
readonly string directory = TestVoiceBank.CreateTemporaryDirectory();
readonly AnalysisCache analysis = new(AnalysisCache.DefaultBudgetBytes);
public void Dispose() => TestVoiceBank.DeleteDirectory(directory);
VoiceBank Bank()
{
TestVoiceBank.WriteText(directory, VoiceBankLoader.CharacterFileName, "name=parallel\r\n");
TestVoiceBank.WriteText(
directory,
VoiceBankLoader.OtoFileName,
string.Join("\r\n",
[
"a.wav=あ,50,80,-200,100,40",
"ka.wav=か,50,120,-200,140,50",
"sa.wav=さ,50,120,-200,140,50",
]));
var index = 0;
foreach (var name in new[] { "a.wav", "ka.wav", "sa.wav" })
TestVoiceBank.WriteSample(directory, name, TestVoiceBank.CreateVowel(180.0 + index++ * 40.0, SampleMilliseconds));
return VoiceBankLoader.Load("parallel", directory);
}
static UTAUNote[] Score(int phrases)
{
var notes = new List<UTAUNote>();
string[] lyrics = ["あ", "か", "さ"];
for (var phrase = 0; phrase < phrases; phrase++)
{
if (phrase > 0)
notes.Add(new UTAUNote { Lyric = UTAUNote.RestLyric, LengthTicks = 240, Tone = 60 });
for (var index = 0; index < 4; index++)
notes.Add(new UTAUNote { Lyric = lyrics[index % 3], LengthTicks = 240, Tone = 60 + index % 5 });
}
return [.. notes];
}
double[] Render(VoiceBank bank, UTAUNote[] notes, SegmentCache cache)
{
var units = Phonemizer.Phonemize(bank, TempoMap.Create(notes, TimeBase.Default), null, PhonemizeOptions.Default);
var renderer = new UtauRenderer(
RenderSettings.Default with { Estimator = F0Estimator.Dio },
RenderCurves.Empty,
analysis,
cache);
return renderer.Render(units).Samples;
}
static SegmentCache Fresh() => new(SegmentCache.DefaultBudgetBytes);
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(8)]
[InlineData(20)]
public void RenderingTheSameScoreTwiceGivesTheSameAudio(int phrases)
{
var bank = Bank();
var notes = Score(phrases);
var first = Render(bank, notes, Fresh());
var second = Render(bank, notes, Fresh());
Assert.Equal(first, second);
}
[Fact]
public void RepeatedRendersStayIdentical()
{
var bank = Bank();
var notes = Score(12);
var expected = Render(bank, notes, Fresh());
for (var pass = 0; pass < 5; pass++)
Assert.Equal(expected, Render(bank, notes, Fresh()));
}
[Fact]
public void EverySegmentWritesADistinctStretchOfTheOutput()
{
var bank = Bank();
var notes = Score(20);
var samples = Render(bank, notes, Fresh());
var silent = 0;
foreach (var value in samples)
{
if (value == 0.0)
silent++;
}
Assert.True(samples.Length > 0);
Assert.True(silent < samples.Length, "the render produced only silence");
}
[Fact]
public void ACachedParallelRenderMatchesAFreshOne()
{
var bank = Bank();
var notes = Score(20);
var shared = Fresh();
var warm = Render(bank, notes, shared);
notes[5].Tone = 68;
var cached = Render(bank, notes, shared);
var fresh = Render(bank, notes, Fresh());
Assert.Equal(fresh, cached);
Assert.False(warm.AsSpan().SequenceEqual(cached));
}
}
+79 -2
ファイルの表示
@@ -475,10 +475,66 @@ public sealed class UnitTimingBuilderTests
public void PreutteranceIsScaledDownWhenThePreviousNoteIsTooShort()
{
var timings = UnitTimingBuilder.Build([CreateUnit(0.0, 20.0, 0.0, 0.0), CreateUnit(20.0, 200.0, 80.0, 40.0)]);
Assert.Equal(-20.0, timings[1].AudioStartMilliseconds, 9);
Assert.Equal(20.0, timings[1].FadeInMilliseconds, 9);
Assert.Equal(5.0, timings[1].AudioStartMilliseconds, 9);
Assert.Equal(7.5, timings[1].FadeInMilliseconds, 9);
}
[Fact]
public void APlosiveKeepsOneTenthOfThePreviousNote()
{
var timings = UnitTimingBuilder.Build([CreateUnit(0.0, 100.0, 0.0, 0.0), CreateUnit(100.0, 200.0, 200.0, -10.0)]);
Assert.Equal(10.0, timings[1].AudioStartMilliseconds, 9);
Assert.Equal(UTAUNote.DefaultFadeInMilliseconds, timings[1].FadeInMilliseconds, 9);
}
[Fact]
public void ARestLimitsThePreutteranceToTheGap()
{
var rest = new PhonemeUnit(new UTAUNote { Lyric = UTAUNote.RestLyric }, null, "R", 100.0, 30.0, 100.0, 30.0, 60);
var timings = UnitTimingBuilder.Build([CreateUnit(0.0, 100.0, 0.0, 0.0), rest, CreateUnit(130.0, 200.0, 80.0, 40.0)]);
Assert.Equal(100.0, timings[1].AudioStartMilliseconds, 9);
}
[Fact]
public void ANegativeOverlapLeavesAGapBeforeTheNextUnit()
{
var timings = UnitTimingBuilder.Build([CreateUnit(0.0, 200.0, 0.0, 0.0), CreateUnit(200.0, 200.0, 60.0, -10.0)]);
Assert.Equal(130.0, timings[0].AudioEndMilliseconds, 9);
Assert.Equal(140.0, timings[1].AudioStartMilliseconds, 9);
}
[Fact]
public void ANegativeOverlapIsLimitedByTheDefaultRelease()
{
var timings = UnitTimingBuilder.Build([CreateUnit(0.0, 100.0, 0.0, 0.0), CreateUnit(100.0, 200.0, 20.0, -60.0)]);
Assert.Equal(35.0, timings[0].AudioEndMilliseconds, 9);
Assert.Equal(80.0, timings[1].AudioStartMilliseconds, 9);
}
[Fact]
public void ThePreutteranceNeverExceedsThePreviousNote()
{
var timings = UnitTimingBuilder.Build([CreateUnit(0.0, 30.0, 10.0, 0.0), CreateUnit(30.0, 200.0, 100.0, 80.0)]);
Assert.Equal(0.0, timings[1].AudioStartMilliseconds, 9);
Assert.Equal(24.0, timings[1].FadeInMilliseconds, 9);
}
[Fact]
public void ALimitedPreutteranceSkipsIntoTheSample()
{
var timings = UnitTimingBuilder.Build([CreateUnit(0.0, 20.0, 0.0, 0.0), CreateUnit(20.0, 200.0, 80.0, 40.0)]);
var timing = timings[1];
var map = TimeMap.Create(0.0, 200.0, 400.0, timing.RenderLengthMilliseconds + timing.SkipMilliseconds, 100.0, StretchMode.Stretch);
var atNoteStart = timing.Unit.StartMilliseconds - timing.AudioStartMilliseconds + timing.SkipMilliseconds;
Assert.Equal(65.0, timing.SkipMilliseconds, 9);
Assert.Equal(80.0, map.Map(atNoteStart), 9);
}
[Fact]
public void AnUnlimitedPreutteranceSkipsNothing()
=> Assert.Equal(0.0, Assert.Single(UnitTimingBuilder.Build([CreateUnit(100.0, 200.0, 40.0, 20.0)])).SkipMilliseconds, 9);
[Fact]
public void SilentUnitsAreNotRendered()
{
@@ -537,6 +593,27 @@ public sealed class UnitTimingBuilderTests
Assert.Equal(60.0, Assert.Single(UnitTimingBuilder.Build([unit])).AudioStartMilliseconds, 9);
}
[Fact]
public void TheConsonantVelocityScalesThePreutterance()
{
var unit = CreateUnit(100.0, 200.0, 40.0, 20.0);
unit.Note.Velocity = 200.0;
var timing = Assert.Single(UnitTimingBuilder.Build([unit]));
Assert.Equal(80.0, timing.AudioStartMilliseconds, 9);
}
[Fact]
public void AnOverriddenPreutteranceIgnoresTheConsonantVelocity()
{
var unit = CreateUnit(100.0, 200.0, 40.0, 20.0);
unit.Note.PreutteranceOverride = 10.0;
unit.Note.Velocity = 200.0;
var timing = Assert.Single(UnitTimingBuilder.Build([unit]));
Assert.Equal(90.0, timing.AudioStartMilliseconds, 9);
}
[Fact]
public void EmptyInputProducesNoTimings()
=> Assert.Empty(UnitTimingBuilder.Build([]));
+5 -7
ファイルの表示
@@ -5,7 +5,6 @@ using System.Windows.Threading;
using UTAU.Notes;
using UTAU.ViewModels;
using UTAU.Views;
using YukkuriMovieMaker.Controls;
namespace UTAU.Tests;
@@ -55,10 +54,9 @@ public sealed class RenderMessageDisplayTests
static Border Build(NoteEditorViewModel viewModel)
{
var editor = new NoteEditor();
var button = (PopupButton)editor.Content;
var root = (Grid)button.PopupContent!;
button.PopupContent = null;
var editor = new NoteEditorSurface();
var root = (Grid)editor.Content!;
editor.Content = null;
root.DataContext = viewModel;
var host = new Border { Width = PopupWidth, Height = PopupHeight, Child = root };
@@ -68,10 +66,10 @@ public sealed class RenderMessageDisplayTests
return host;
}
static TextBlock WarningBlock(Border host)
static ScrollingText WarningBlock(Border host)
=> Descend(host)
.OfType<DockPanel>()
.SelectMany(x => x.Children.OfType<TextBlock>())
.SelectMany(x => x.Children.OfType<ScrollingText>())
.First(x => DockPanel.GetDock(x) == Dock.Right);
[Fact]
+25 -5
ファイルの表示
@@ -119,12 +119,33 @@ public sealed class UtauRendererTests : IDisposable
{
var notes = NoteSequenceBuilder.Build(text, NoteBuildOptions.Create(60));
var units = Phonemizer.Phonemize(bank, TempoMap.Create(notes, new TimeBase(tempo, speed)), null, PhonemizeOptions.Default);
using var arena = new WorldArena();
return new UtauRenderer(settings ?? RenderSettings.Default with { Estimator = F0Estimator.Dio }, curves ?? RenderCurves.Empty, cache, new SegmentCache(SegmentCache.DefaultBudgetBytes)).Render(units, arena);
return new UtauRenderer(settings ?? RenderSettings.Default with { Estimator = F0Estimator.Dio }, curves ?? RenderCurves.Empty, cache, new SegmentCache(SegmentCache.DefaultBudgetBytes)).Render(units);
}
static double Peak(double[] samples) => samples.Length == 0 ? 0.0 : samples.Max(Math.Abs);
VoiceBank BankAtLevel(string name, double level)
{
var path = Path.Combine(directory, name);
Directory.CreateDirectory(path);
TestVoiceBank.WriteText(path, VoiceBankLoader.CharacterFileName, "name=試験音源\r\n");
TestVoiceBank.WriteText(path, VoiceBankLoader.OtoFileName, "a.wav=あ,50,80,-500,100,40");
TestVoiceBank.WriteSample(path, "a.wav", [.. TestVoiceBank.CreateVowel().Select(x => x * level)]);
return VoiceBankLoader.Load(name, path);
}
const double QuietLevel = 0.25;
const double PeakCompression = 0.86;
[Fact]
public void AQuietSampleIsLiftedTowardTheSamePeak()
{
var loud = Peak(Render(BankAtLevel("loud", 1.0), "<!C4:1/4>あ").Samples);
var quiet = Peak(Render(BankAtLevel("quiet", QuietLevel), "<!C4:1/4>あ").Samples);
Assert.Equal(Math.Pow(QuietLevel, 1.0 - PeakCompression), quiet / loud, 2);
}
static double MeasureFundamental(RenderResult result)
{
using var arena = new WorldArena();
@@ -294,8 +315,7 @@ public sealed class UtauRendererTests : IDisposable
[Fact]
public void UnitsWithoutAnyRenderableEntryProduceAnEmptyResult()
{
using var arena = new WorldArena();
var result = new UtauRenderer(RenderSettings.Default with { Estimator = F0Estimator.Dio }, RenderCurves.Empty, cache, new SegmentCache(SegmentCache.DefaultBudgetBytes)).Render([], arena);
var result = new UtauRenderer(RenderSettings.Default with { Estimator = F0Estimator.Dio }, RenderCurves.Empty, cache, new SegmentCache(SegmentCache.DefaultBudgetBytes)).Render([]);
Assert.Empty(result.Samples);
Assert.Empty(result.Timings);
@@ -341,7 +361,7 @@ public sealed class SegmentedRenderTests : IDisposable
var units = Phonemizer.Phonemize(bank, TempoMap.Create(notes, TimeBase.Default), null, PhonemizeOptions.Default);
using var arena = new WorldArena();
var settings = RenderSettings.Default with { Estimator = F0Estimator.Dio };
return new UtauRenderer(settings, RenderCurves.Empty, cache, new SegmentCache(SegmentCache.DefaultBudgetBytes)).Render(units, arena).Samples;
return new UtauRenderer(settings, RenderCurves.Empty, cache, new SegmentCache(SegmentCache.DefaultBudgetBytes)).Render(units).Samples;
}
[Fact]
+130
ファイルの表示
@@ -0,0 +1,130 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using UTAU.Notes;
using UTAU.ViewModels;
using UTAU.Views;
namespace UTAU.Tests;
[Collection("Wpf")]
public sealed class ScrollingTextTests
{
const string Long = "697 個のノートを読み込みました 全 88 フレーズ 前後の休符 1200 ティックを除きました";
const string Short = "12 個のノート";
static T RunSta<T>(Func<T> action)
{
var result = default(T)!;
Exception? error = null;
var thread = new Thread(() =>
{
try
{
result = action();
}
catch (Exception exception)
{
error = exception;
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
if (error is not null)
throw new InvalidOperationException(error.Message, error);
return result;
}
static IEnumerable<DependencyObject> Descend(DependencyObject root)
{
var count = VisualTreeHelper.GetChildrenCount(root);
for (var index = 0; index < count; index++)
{
var child = VisualTreeHelper.GetChild(root, index);
yield return child;
foreach (var descendant in Descend(child))
yield return descendant;
}
}
static (bool Scrolling, double Hidden, double Width) Measure(string text, double available)
{
var control = new ScrollingText { Text = text, FontSize = 12.0 };
var host = new Border { Width = available, Height = 26.0, Child = control };
host.Measure(new Size(available, 26.0));
host.Arrange(new Rect(0.0, 0.0, available, 26.0));
host.UpdateLayout();
return (control.IsScrolling, control.HiddenWidth, control.ActualWidth);
}
[Fact]
public void ShortTextDoesNotScroll()
{
var result = RunSta(() => Measure(Short, 400.0));
Assert.False(result.Scrolling);
Assert.Equal(0.0, result.Hidden);
}
[Fact]
public void OverflowingTextScrolls()
{
var result = RunSta(() => Measure(Long, 200.0));
Assert.True(result.Scrolling);
Assert.True(result.Hidden > 0.0, $"hidden={result.Hidden}");
Assert.Equal(200.0, result.Width, 1);
}
static double NaturalWidth(string text)
{
var control = new ScrollingText { Text = text, FontSize = 12.0 };
control.Measure(new Size(double.PositiveInfinity, 26.0));
return control.DesiredSize.Width;
}
[Fact]
public void TextThatFitsDoesNotScroll()
{
var result = RunSta(() =>
{
var natural = NaturalWidth(Long);
return (natural, Measure(Long, natural + 8.0));
});
Assert.True(result.natural > 0.0);
Assert.False(result.Item2.Scrolling);
Assert.Equal(0.0, result.Item2.Hidden);
}
[Fact]
public void TheToolbarUsesScrollingTextForBothMessages()
{
var found = RunSta(() =>
{
var editor = new NoteEditorSurface();
var root = (Grid)editor.Content!;
editor.Content = null;
var pronounce = new UTAUVoicePronounce { ImportMessage = Long, RenderMessage = Long };
pronounce.Notes.Add(new UTAUNote { Lyric = "あ" });
using var viewModel = new NoteEditorViewModel(pronounce);
root.DataContext = viewModel;
var host = new Border { Width = 980.0, Height = 480.0, Child = root };
host.Measure(new Size(980.0, 480.0));
host.Arrange(new Rect(0.0, 0.0, 980.0, 480.0));
host.UpdateLayout();
return Descend(host)
.OfType<DockPanel>()
.SelectMany(x => x.Children.OfType<ScrollingText>())
.Select(x => x.Text)
.ToArray();
});
Assert.Equal(2, found.Length);
Assert.All(found, x => Assert.Equal(Long, x));
}
}
+46 -7
ファイルの表示
@@ -3,7 +3,6 @@ using UTAU.Models;
using UTAU.Notes;
using UTAU.Phonemes;
using UTAU.Synthesis;
using WorldNet;
namespace UTAU.Tests;
@@ -51,13 +50,12 @@ public sealed class SegmentCacheTests : IDisposable
double[] Render(VoiceBank bank, UTAUNote[] notes, RenderSettings? settings = null)
{
var units = Phonemizer.Phonemize(bank, TempoMap.Create(notes, TimeBase.Default), null, PhonemizeOptions.Default);
using var arena = new WorldArena();
var renderer = new UtauRenderer(
settings ?? RenderSettings.Default with { Estimator = F0Estimator.Dio },
RenderCurves.Empty,
analysis,
segments);
return renderer.Render(units, arena).Samples;
return renderer.Render(units).Samples;
}
[Fact]
@@ -87,10 +85,52 @@ public sealed class SegmentCacheTests : IDisposable
RenderCurves.Empty,
analysis,
new SegmentCache(SegmentCache.DefaultBudgetBytes));
using var arena = new WorldArena();
var units = Phonemizer.Phonemize(bank, TempoMap.Create(notes, TimeBase.Default), null, PhonemizeOptions.Default);
Assert.Equal(fresh.Render(units, arena).Samples, cached);
Assert.Equal(fresh.Render(units).Samples, cached);
}
static UTAUNote[] LongScore(int phrases)
{
var notes = new List<UTAUNote>();
for (var phrase = 0; phrase < phrases; phrase++)
{
if (phrase > 0)
notes.Add(new UTAUNote { Lyric = UTAUNote.RestLyric, LengthTicks = 240, Tone = 60 });
notes.Add(new UTAUNote { Lyric = "あ", LengthTicks = 240, Tone = 60 });
notes.Add(new UTAUNote { Lyric = "か", LengthTicks = 240, Tone = 62 });
}
return [.. notes];
}
[Fact]
public void ShiftingTheWholeScoreReusesEveryLaterSegment()
{
var bank = Bank();
var notes = LongScore(8);
Render(bank, notes);
var before = segments.Count;
notes[0].PreutteranceOverride = 200.0;
Render(bank, notes);
Assert.Equal(before + 1, segments.Count);
}
[Fact]
public void AnEditThatMovesLaterNotesRebuildsFewerThanEverySegment()
{
var bank = Bank();
var notes = LongScore(8);
Render(bank, notes);
var before = segments.Count;
notes[0].LengthTicks = 480;
Render(bank, notes);
Assert.True(segments.Count - before < before, $"rebuilt={segments.Count - before} of {before}");
}
[Fact]
@@ -159,13 +199,12 @@ public sealed class SegmentCacheTests : IDisposable
double[] RenderFresh(VoiceBank bank, UTAUNote[] notes, RenderSettings? settings = null)
{
var units = Phonemizer.Phonemize(bank, TempoMap.Create(notes, TimeBase.Default), null, PhonemizeOptions.Default);
using var arena = new WorldArena();
var renderer = new UtauRenderer(
settings ?? RenderSettings.Default with { Estimator = F0Estimator.Dio },
RenderCurves.Empty,
analysis,
new SegmentCache(SegmentCache.DefaultBudgetBytes));
return renderer.Render(units, arena).Samples;
return renderer.Render(units).Samples;
}
[Theory]
+95 -6
ファイルの表示
@@ -60,19 +60,26 @@ public sealed class TimeMapTests
}
[Fact]
public void StretchModeAlsoCompresses()
public void StretchModeNeverRunsFasterThanTheSource()
{
var map = TimeMap.Create(0.0, 0.0, 400.0, 100.0, 100.0, StretchMode.Stretch);
Assert.Equal(200.0, map.Map(50.0), 9);
Assert.Equal(400.0, map.Map(100.0), 9);
Assert.Equal(50.0, map.Map(50.0), 9);
Assert.Equal(100.0, map.Map(100.0), 9);
}
[Fact]
public void ConsonantIsCompressedWhenTheOutputIsShorterThanTheConsonant()
public void ConsonantKeepsItsSpeedWhenTheOutputIsShorter()
{
var map = TimeMap.Create(0.0, 200.0, 400.0, 50.0, 100.0, StretchMode.Loop);
Assert.Equal(50.0, map.ConsonantOutputLength, 9);
Assert.Equal(200.0, map.Map(50.0), 9);
Assert.Equal(200.0, map.ConsonantOutputLength, 9);
Assert.Equal(50.0, map.Map(50.0), 9);
}
[Fact]
public void TheConsonantVelocityScalesTheConsonantOutput()
{
Assert.Equal(100.0, TimeMap.Create(0.0, 200.0, 400.0, 1000.0, 200.0, StretchMode.Loop).ConsonantOutputLength, 9);
Assert.Equal(400.0, TimeMap.Create(0.0, 200.0, 400.0, 1000.0, 0.0, StretchMode.Loop).ConsonantOutputLength, 9);
}
[Fact]
@@ -89,6 +96,24 @@ public sealed class TimeMapTests
public sealed class SpectrumTransformTests
{
[Fact]
public void AMixingWeightAndAGainScaleThePowerAlike()
{
var scaled = SpectrumTransform.ToPower(0.25 * SpectrumTransform.ToAmplitude(4.0));
var gained = new[] { 4.0 };
SpectrumTransform.ApplyGain(gained, 0.25);
Assert.Equal(gained[0], scaled, 12);
}
[Fact]
public void MixingWeightsThatSumToOneKeepTheLevel()
{
var sum = 0.4 * SpectrumTransform.ToAmplitude(9.0) + 0.6 * SpectrumTransform.ToAmplitude(9.0);
Assert.Equal(9.0, SpectrumTransform.ToPower(sum), 12);
}
static double[] CreatePeak(int size, int index)
{
var spectrum = new double[size];
@@ -469,3 +494,67 @@ public sealed class AnalysisCacheTests
Assert.Equal(0, cache.UsedBytes);
}
}
public sealed class PitchTrackTests
{
static PhonemeUnit Unit(double start, double length, int tone, double preutterance, double overlap)
=> new(
new UTAUNote { Lyric = "a", Tone = tone },
new OtoEntry(@"C:ank", "a.wav", "a", 0.0, 0.0, 0.0, preutterance, overlap),
"a",
start,
length,
start,
length,
tone);
static PitchTrack Track(params PhonemeUnit[] units)
=> PitchTrack.Create(UnitTimingBuilder.Build(units), 0.0, 5.0, 80);
[Fact]
public void ThePitchStepsAtTheNoteBoundary()
{
var track = Track(Unit(0.0, 200.0, 60, 0.0, 0.0), Unit(200.0, 200.0, 72, 80.0, 40.0));
Assert.Equal(6000.0, track.CentsAt(39), 9);
Assert.Equal(7200.0, track.CentsAt(40), 9);
for (var frame = 0; frame < 80; frame++)
Assert.True(track.CentsAt(frame) is 6000.0 or 7200.0);
}
[Fact]
public void TheOverlapKeepsThePitchOfThePreviousNote()
{
var track = Track(Unit(0.0, 200.0, 60, 0.0, 0.0), Unit(200.0, 200.0, 72, 80.0, 40.0));
Assert.Equal(6000.0, track.CentsAt(24), 9);
}
[Fact]
public void APhraseOpeningNoteExtendsItsFirstPointBackToItsAudioStart()
{
var second = Unit(300.0, 200.0, 72, 80.0, 40.0);
second.Note.LengthTicks = 240;
second.Note.PitchPoints.Add(new PitchPoint(-50, 500.0));
second.Note.PitchPoints.Add(new PitchPoint(0, 0.0));
var track = Track(Unit(0.0, 200.0, 60, 0.0, 0.0), second);
Assert.Equal(7200.0, track.CentsAt(43), 9);
Assert.Equal(7700.0, track.CentsAt(44), 9);
Assert.Equal(7200.0, track.CentsAt(60), 9);
}
[Fact]
public void APortamentoReachesAcrossThePreviousNote()
{
var second = Unit(200.0, 200.0, 72, 80.0, 40.0);
second.Note.LengthTicks = 240;
second.Note.PitchPoints.Add(new PitchPoint(-120, -1200.0));
second.Note.PitchPoints.Add(new PitchPoint(0, 0.0));
var track = Track(Unit(0.0, 200.0, 60, 0.0, 0.0), second);
Assert.Equal(6000.0, track.CentsAt(20), 9);
Assert.Equal(6600.0, track.CentsAt(30), 9);
Assert.Equal(7200.0, track.CentsAt(40), 9);
}
}
-6
ファイルの表示
@@ -30,12 +30,6 @@
</ItemGroup>
<ItemGroup>
<Reference Include="NAudio">
<HintPath>$(YMM4DirPath)NAudio.dll</HintPath>
</Reference>
<Reference Include="NAudio.Core">
<HintPath>$(YMM4DirPath)NAudio.Core.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json">
<HintPath>$(YMM4DirPath)Newtonsoft.Json.dll</HintPath>
</Reference>
+2 -1
ファイルの表示
@@ -150,7 +150,8 @@ public sealed class UstPhraseRangeTests : IDisposable
Assert.Equal(["か", "あ"], second.Notes.Select(x => x.Lyric));
Assert.Equal(UstPhraseRange.All, whole.ImportedRange);
Assert.Equal(new UstPhraseRange(2, 1), second.ImportedRange);
Assert.Contains(string.Format(Texts.UstPhraseTotalFormat, Phrases.Length), second.ImportMessage);
Assert.Contains(string.Format(Texts.UstPhraseRangeFormat, 2, 1, Phrases.Length), second.ImportMessage);
Assert.Contains(string.Format(Texts.UstPhraseTotalFormat, Phrases.Length), whole.ImportMessage);
Assert.Contains(string.Format(Texts.UstPhraseOffsetFormat, 2160), second.ImportMessage);
}
+47
ファイルの表示
@@ -388,6 +388,53 @@ public sealed class UstTests
Assert.Equal(79520, rests.Sum(x => x.LengthTicks));
}
[Fact]
public void ANoteLongerThanTheNoteLimitKeepsTheTimeline()
{
var result = Import(Document(
"Tempo=120.00",
["Length=32640", "Lyric=a", "NoteNum=60"],
["Length=480", "Lyric=i", "NoteNum=62"]));
Assert.Equal([30720, 1920, 480], result.Notes.Select(x => x.LengthTicks).ToArray());
}
[Fact]
public void ARestLongerThanTheNoteLimitKeepsTheTimeline()
{
var result = Import(Document(
"Tempo=120.00",
Sung(),
["Length=32640", "Lyric=R", "NoteNum=60"],
Sung("Lyric=i")));
Assert.Equal([480, 30720, 1920, 480], result.Notes.Select(x => x.LengthTicks).ToArray());
}
[Fact]
public void ARestShorterThanTheNoteLimitDoesNotPileUpDelay()
{
var result = Import(Document(
"Tempo=120.00",
Sung(),
["Length=10", "Lyric=R", "NoteNum=60"],
Sung("Lyric=i"),
["Length=10", "Lyric=R", "NoteNum=60"],
Sung("Lyric=u")));
Assert.Equal([480, 15, 475, 15, 475], result.Notes.Select(x => x.LengthTicks).ToArray());
}
[Fact]
public void ADurationWithoutADeltaFollowsTheScoreLength()
{
var text = "[#SETTING]\r\nTempo=120.00\r\n"
+ "[#0000]\r\nDuration=240\r\nLength=480\r\nLyric=a\r\nNoteNum=60\r\n";
var result = Import(text);
Assert.Equal(480, Assert.Single(result.Notes).LengthTicks);
}
[Fact]
public void TheSettingTempoIsUsed()
{
+3
ファイルの表示
@@ -1,4 +1,7 @@
<Solution>
<Folder Name="/Solution Items/">
<File Path=".editorconfig" />
</Folder>
<Project Path="UTAU/UTAU.csproj" />
<Project Path="UTAU.Tests/UTAU.Tests.csproj" />
<Project Path="YukkuriMovieMaker.Generator/YukkuriMovieMaker.Generator/YukkuriMovieMaker.Generator.csproj" />
+158
ファイルの表示
@@ -0,0 +1,158 @@
using System.Globalization;
using System.Text;
namespace UTAU.Notes;
internal static class LyricSplitter
{
public const char Quote = '"';
public const char Separator = ' ';
static readonly char[] Contracted =
['ゃ', 'ゅ', 'ょ', 'ぁ', 'ぃ', 'ぅ', 'ぇ', 'ぉ', 'ャ', 'ュ', 'ョ', 'ァ', 'ィ', 'ゥ', 'ェ', 'ォ'];
public static List<string> Split(string? text)
{
var lyrics = new List<string>();
if (string.IsNullOrEmpty(text))
return lyrics;
var builder = new StringBuilder();
var rest = text.AsSpan();
while (!rest.IsEmpty)
{
var element = Take(ref rest);
if (ContainsWhitespace(element))
{
Flush(lyrics, builder);
}
else if (ContainsContracted(element))
{
builder.Append(element);
lyrics.Add(builder.ToString());
builder.Clear();
}
else if (ContainsStandalone(element))
{
Flush(lyrics, builder);
builder.Append(element);
}
else if (IsQuote(element))
{
TakeQuoted(ref rest, lyrics, builder);
}
else
{
if (builder.Length > 0 && ContainsStandalone(builder))
{
lyrics.Add(builder.ToString());
builder.Clear();
}
builder.Append(element);
}
}
Flush(lyrics, builder);
return lyrics;
}
public static string Join(IEnumerable<string> lyrics)
{
var builder = new StringBuilder();
foreach (var lyric in lyrics)
{
if (builder.Length != 0)
builder.Append(Separator);
if (lyric.Length == 0)
builder.Append(Quote).Append(Quote);
else if (ContainsWhitespace(lyric))
builder.Append(Quote).Append(lyric).Append(Quote);
else if (!ContainsStandalone(lyric))
builder.Append(lyric);
else if (lyric.Length == 1 || (lyric.Length == 2 && ContainsContracted(lyric.AsSpan(1))))
builder.Append(lyric);
else
builder.Append(Quote).Append(lyric).Append(Quote);
}
return builder.ToString();
}
static ReadOnlySpan<char> Take(ref ReadOnlySpan<char> rest)
{
var length = StringInfo.GetNextTextElementLength(rest);
var element = rest[..length];
rest = rest[length..];
return element;
}
static void TakeQuoted(ref ReadOnlySpan<char> rest, List<string> lyrics, StringBuilder builder)
{
while (!rest.IsEmpty)
{
var element = Take(ref rest);
if (IsQuote(element))
{
lyrics.Add(builder.ToString());
builder.Clear();
return;
}
builder.Append(element);
}
}
static void Flush(List<string> lyrics, StringBuilder builder)
{
if (builder.Length == 0)
return;
lyrics.Add(builder.ToString());
builder.Clear();
}
static bool IsQuote(ReadOnlySpan<char> element) => element.Length == 1 && element[0] == Quote;
static bool ContainsWhitespace(ReadOnlySpan<char> element)
{
foreach (var value in element)
{
if (char.IsWhiteSpace(value))
return true;
}
return false;
}
static bool ContainsContracted(ReadOnlySpan<char> element) => element.IndexOfAny(Contracted) >= 0;
static bool ContainsStandalone(ReadOnlySpan<char> element)
{
foreach (var value in element)
{
if (IsStandalone(value))
return true;
}
return false;
}
static bool ContainsStandalone(StringBuilder builder)
{
foreach (var chunk in builder.GetChunks())
{
if (ContainsStandalone(chunk.Span))
return true;
}
return false;
}
static bool IsStandalone(char value)
=> value is >= '\u4e00' and <= '\u9fff'
or >= '\u3040' and <= '\u309f'
or >= '\u30a0' and <= '\u30ff'
or >= '\uac00' and <= '\ud7af';
}
+12 -8
ファイルの表示
@@ -15,6 +15,10 @@ internal sealed class UTAUNote : UndoRedoable
public const int MaximumLengthTicks = TimeBase.TicksPerWholeNote * 16;
public const double DefaultFadeInMilliseconds = 5.0;
public const double DefaultFadeOutMilliseconds = 35.0;
public const double DefaultVelocity = 100.0;
public const double DefaultIntensity = 100.0;
public const double DefaultModulation = 0.0;
public const double DefaultStartPointMilliseconds = 0.0;
public const double FollowOtoValue = 0.0;
public const double FollowScoreValue = 0.0;
public const string RestLyric = "R";
@@ -24,10 +28,10 @@ internal sealed class UTAUNote : UndoRedoable
bool suppressAutoVcv;
int tone = MusicalTone.MiddleC.NoteNumber;
int lengthTicks = DefaultLengthTicks;
double velocity = 100.0;
double intensity = 100.0;
double modulation;
double startPointMilliseconds;
double velocity = DefaultVelocity;
double intensity = DefaultIntensity;
double modulation = DefaultModulation;
double startPointMilliseconds = DefaultStartPointMilliseconds;
double tempoOverride;
double preutteranceOverride;
double overlapOverride;
@@ -103,7 +107,7 @@ internal sealed class UTAUNote : UndoRedoable
[Display(GroupName = nameof(Texts.NoteGroupExpression), Name = nameof(Texts.NoteVelocity), Description = nameof(Texts.NoteVelocityDescription), ResourceType = typeof(Texts))]
[TextBoxSlider("F0", "", 0.0, 200.0, Delay = -1)]
[Range(0.0, 200.0)]
[DefaultValue(100.0)]
[DefaultValue(DefaultVelocity)]
public double Velocity
{
get => velocity;
@@ -113,7 +117,7 @@ internal sealed class UTAUNote : UndoRedoable
[Display(GroupName = nameof(Texts.NoteGroupExpression), Name = nameof(Texts.NoteIntensity), ResourceType = typeof(Texts))]
[TextBoxSlider("F0", "%", 0.0, 200.0, Delay = -1)]
[Range(0.0, 200.0)]
[DefaultValue(100.0)]
[DefaultValue(DefaultIntensity)]
public double Intensity
{
get => intensity;
@@ -123,7 +127,7 @@ internal sealed class UTAUNote : UndoRedoable
[Display(GroupName = nameof(Texts.NoteGroupExpression), Name = nameof(Texts.NoteModulation), Description = nameof(Texts.ParameterModulationDescription), ResourceType = typeof(Texts))]
[TextBoxSlider("F0", "%", -200.0, 200.0, Delay = -1)]
[Range(-200.0, 200.0)]
[DefaultValue(0.0)]
[DefaultValue(DefaultModulation)]
public double Modulation
{
get => modulation;
@@ -153,7 +157,7 @@ internal sealed class UTAUNote : UndoRedoable
[Display(GroupName = nameof(Texts.NoteGroupTiming), Name = nameof(Texts.NoteStartPoint), Description = nameof(Texts.NoteStartPointDescription), ResourceType = typeof(Texts))]
[TextBoxSlider("F0", "ms", 0.0, 500.0, Delay = -1)]
[Range(0.0, 5000.0)]
[DefaultValue(0.0)]
[DefaultValue(DefaultStartPointMilliseconds)]
public double StartPointMilliseconds
{
get => startPointMilliseconds;
+25 -8
ファイルの表示
@@ -36,6 +36,7 @@ internal sealed record UstImportResult(
internal static class UstImporter
{
public const double MaximumDeclaredTempo = 1000.0;
public const int MaximumSectionTicks = TimeBase.TicksPerWholeNote * 1024;
public const double CentsPerPitchUnit = 10.0;
public const int EnvelopeFieldCount = 7;
const double TempoEpsilon = 1e-9;
@@ -52,6 +53,7 @@ internal static class UstImporter
var legacyPitchNoteCount = 0;
var position = 0;
var end = 0;
var emitted = 0;
foreach (var section in document.NoteSections)
{
@@ -59,16 +61,15 @@ internal static class UstImporter
var duration = ParseInteger(section.Find(UstKeys.Duration));
var delta = ParseInteger(section.Find(UstKeys.Delta));
var noteLength = duration ?? length ?? 0;
var hasSpacing = delta is not null && duration is not null && length is not null;
var noteLength = Math.Min((hasSpacing ? duration : length) ?? 0, MaximumSectionTicks);
if (noteLength <= 0)
continue;
var start = delta is not null && duration is not null && length is not null
? Math.Max(position + delta.Value, end)
: end;
var start = hasSpacing ? Math.Max(position + delta!.Value, end) : end;
var previousTone = notes.Count == 0 ? MusicalTone.MiddleC.NoteNumber : notes[^1].Tone;
AddRest(notes, start - end, previousTone);
emitted += AddRest(notes, start - emitted, previousTone);
var sectionTempo = ParseNumber(section.Find(UstKeys.Tempo));
var isTempoChange = IsUsableTempo(sectionTempo)
@@ -76,12 +77,14 @@ internal static class UstImporter
if (isTempoChange)
currentTempo = ClampTempo(sectionTempo!.Value);
var note = CreateNote(section, noteLength, new TimeBase(currentTempo, 1.0));
var note = CreateNote(section, HeadLengthTicks(start + noteLength - emitted), new TimeBase(currentTempo, 1.0));
if (isTempoChange)
note.TempoOverride = currentTempo;
if (note.PitchPoints.Count == 0 && HasLegacyPitch(section))
legacyPitchNoteCount++;
notes.Add(note);
emitted += note.LengthTicks;
emitted += AddRest(notes, start + noteLength - emitted, note.Tone);
position = start;
end = start + noteLength;
@@ -245,11 +248,12 @@ internal static class UstImporter
|| section.Find(UstKeys.LegacyPitches) is not null
|| section.Find(UstKeys.LegacyPitchesTypo) is not null;
static void AddRest(List<UTAUNote> notes, int lengthTicks, int tone)
static int AddRest(List<UTAUNote> notes, int lengthTicks, int tone)
{
var emitted = 0;
while (lengthTicks >= UTAUNote.MinimumLengthTicks)
{
var chunk = Math.Min(lengthTicks, UTAUNote.MaximumLengthTicks);
var chunk = HeadLengthTicks(lengthTicks);
notes.Add(new UTAUNote
{
Lyric = UTAUNote.RestLyric,
@@ -257,7 +261,20 @@ internal static class UstImporter
LengthTicks = chunk,
});
lengthTicks -= chunk;
emitted += chunk;
}
return emitted;
}
static int HeadLengthTicks(int lengthTicks)
{
if (lengthTicks <= UTAUNote.MaximumLengthTicks)
return lengthTicks;
var remainder = lengthTicks - UTAUNote.MaximumLengthTicks;
return remainder >= UTAUNote.MinimumLengthTicks
? UTAUNote.MaximumLengthTicks
: UTAUNote.MaximumLengthTicks - (UTAUNote.MinimumLengthTicks - remainder);
}
static (int Leading, int Total) TrimSurroundingRests(List<UTAUNote> notes)
+6 -2
ファイルの表示
@@ -19,11 +19,15 @@ internal sealed record PhonemeUnit(
public double EndMilliseconds => StartMilliseconds + LengthMilliseconds;
public double Preutterance => Note.PreutteranceOverride > UTAUNote.FollowOtoValue
public bool HasPreutteranceOverride => Note.PreutteranceOverride > UTAUNote.FollowOtoValue;
public bool HasOverlapOverride => Note.OverlapOverride > UTAUNote.FollowOtoValue;
public double Preutterance => HasPreutteranceOverride
? Note.PreutteranceOverride
: Entry?.Preutterance ?? 0.0;
public double Overlap => Note.OverlapOverride > UTAUNote.FollowOtoValue
public double Overlap => HasOverlapOverride
? Note.OverlapOverride
: Entry?.Overlap ?? 0.0;
}
+142
ファイルの表示
@@ -0,0 +1,142 @@
using UTAU.Notes;
namespace UTAU.Synthesis;
internal sealed class PitchTrack
{
readonly record struct TrackNote(UTAUNote Note, double StartMilliseconds, double LengthMilliseconds, int Tone, double AudioStartMilliseconds)
{
public double EndMilliseconds => StartMilliseconds + LengthMilliseconds;
public double Cents => Tone * 100.0;
}
readonly double[] cents;
PitchTrack(double[] cents) => this.cents = cents;
public static PitchTrack Create(IReadOnlyList<UnitTiming> timings, double startMilliseconds, double framePeriod, int frameCount)
{
ArgumentNullException.ThrowIfNull(timings);
var cents = new double[Math.Max(frameCount, 0)];
var notes = CollectNotes(timings);
if (cents.Length == 0 || notes.Count == 0)
return new PitchTrack(cents);
FillTones(cents, notes, startMilliseconds, framePeriod);
ApplyVibrato(cents, notes, startMilliseconds, framePeriod);
ApplyPortamento(cents, notes, startMilliseconds, framePeriod);
return new PitchTrack(cents);
}
public double CentsAt(int frame)
=> cents.Length == 0 ? 0.0 : cents[Math.Clamp(frame, 0, cents.Length - 1)];
static List<TrackNote> CollectNotes(IReadOnlyList<UnitTiming> timings)
{
var notes = new List<TrackNote>(timings.Count);
foreach (var timing in timings)
{
var unit = timing.Unit;
if (unit.Note.IsRest)
continue;
notes.Add(new TrackNote(unit.Note, unit.NoteStartMilliseconds, unit.NoteLengthMilliseconds, unit.Tone, timing.AudioStartMilliseconds));
}
notes.Sort((left, right) => left.StartMilliseconds.CompareTo(right.StartMilliseconds));
var distinct = new List<TrackNote>(notes.Count);
foreach (var note in notes)
{
if (distinct.Count > 0 && distinct[^1].StartMilliseconds == note.StartMilliseconds && ReferenceEquals(distinct[^1].Note, note.Note))
{
distinct[^1] = distinct[^1] with
{
AudioStartMilliseconds = Math.Min(distinct[^1].AudioStartMilliseconds, note.AudioStartMilliseconds),
};
continue;
}
distinct.Add(note);
}
return distinct;
}
static void FillTones(double[] cents, List<TrackNote> notes, double startMilliseconds, double framePeriod)
{
var index = 0;
foreach (var note in notes)
{
while (index < cents.Length && startMilliseconds + index * framePeriod < note.EndMilliseconds)
{
cents[index] = note.Cents;
index++;
}
}
if (index == 0)
{
Array.Fill(cents, notes[^1].Cents);
return;
}
for (var i = index; i < cents.Length; i++)
cents[i] = cents[i - 1];
}
static void ApplyVibrato(double[] cents, List<TrackNote> notes, double startMilliseconds, double framePeriod)
{
foreach (var note in notes)
{
if (!note.Note.Vibrato.IsEnabled)
continue;
var from = Math.Max((int)Math.Ceiling((note.StartMilliseconds - startMilliseconds) / framePeriod), 0);
var to = Math.Min((int)((note.EndMilliseconds - startMilliseconds) / framePeriod), cents.Length);
for (var i = from; i < to; i++)
cents[i] = note.Cents + note.Note.Vibrato.Evaluate(startMilliseconds + i * framePeriod - note.StartMilliseconds, note.LengthMilliseconds);
}
}
static void ApplyPortamento(double[] cents, List<TrackNote> notes, double startMilliseconds, double framePeriod)
{
for (var n = 0; n < notes.Count; n++)
{
var note = notes[n];
if (note.Note.PitchPoints.Count == 0 || note.Note.LengthTicks <= 0)
continue;
var scale = note.LengthMilliseconds / note.Note.LengthTicks;
var points = new List<(double X, double Y, PitchPointShape Shape)>(note.Note.PitchPoints.Count + 2);
foreach (var point in note.Note.PitchPoints)
points.Add((note.StartMilliseconds + point.Ticks * scale, note.Cents + point.Cents, point.Shape));
var opensPhrase = n == 0 || notes[n - 1].EndMilliseconds < note.StartMilliseconds;
var lead = opensPhrase
? Math.Max(startMilliseconds, note.AudioStartMilliseconds)
: note.StartMilliseconds;
if (points[0].X > lead)
points.Insert(0, (lead, points[0].Y, points[0].Shape));
if (points[^1].X < note.EndMilliseconds)
points.Add((note.EndMilliseconds, points[^1].Y, points[^1].Shape));
for (var s = 0; s < points.Count - 1; s++)
{
var from = points[s];
var to = points[s + 1];
var first = Math.Max((int)Math.Ceiling((from.X - startMilliseconds) / framePeriod), 0);
var last = Math.Min((int)Math.Ceiling((to.X - startMilliseconds) / framePeriod), cents.Length);
var span = to.X - from.X;
for (var i = first; i < last; i++)
{
var x = startMilliseconds + i * framePeriod;
var progress = span <= 0.0 ? 1.0 : (x - from.X) / span;
var pitch = PitchPoint.Interpolate(from.Y, to.Y, progress, from.Shape);
var basePitch = n > 0 && x < notes[n - 1].EndMilliseconds ? notes[n - 1].Cents : note.Cents;
cents[i] += pitch - basePitch;
}
}
}
}
}
+2 -2
ファイルの表示
@@ -37,12 +37,12 @@ internal sealed class SegmentCache(long budgetBytes)
{
if (!entries.TryGetValue(key, out var node))
return false;
if (node.Value.Samples.Length != destination.Length)
if (node.Value.Samples.Length < destination.Length)
return false;
order.Remove(node);
order.AddFirst(node);
node.Value.Samples.CopyTo(destination);
node.Value.Samples.AsSpan(0, destination.Length).CopyTo(destination);
return true;
}
}
+3 -12
ファイルの表示
@@ -38,6 +38,7 @@ internal readonly record struct UnitKey(
double RenderLengthMilliseconds,
double FadeInMilliseconds,
double FadeOutMilliseconds,
double SkipMilliseconds,
double NoteStartMilliseconds,
double NoteLengthMilliseconds,
int Tone,
@@ -54,6 +55,7 @@ internal readonly record struct UnitKey(
&& RenderLengthMilliseconds.Equals(other.RenderLengthMilliseconds)
&& FadeInMilliseconds.Equals(other.FadeInMilliseconds)
&& FadeOutMilliseconds.Equals(other.FadeOutMilliseconds)
&& SkipMilliseconds.Equals(other.SkipMilliseconds)
&& NoteStartMilliseconds.Equals(other.NoteStartMilliseconds)
&& NoteLengthMilliseconds.Equals(other.NoteLengthMilliseconds)
&& Tone == other.Tone
@@ -72,6 +74,7 @@ internal readonly record struct UnitKey(
hash.Add(RenderLengthMilliseconds);
hash.Add(FadeInMilliseconds);
hash.Add(FadeOutMilliseconds);
hash.Add(SkipMilliseconds);
hash.Add(NoteStartMilliseconds);
hash.Add(NoteLengthMilliseconds);
hash.Add(Tone);
@@ -93,27 +96,21 @@ internal sealed class SegmentKey : IEquatable<SegmentKey>
public SegmentKey(
RenderSettings settings,
int startFrame,
int frameCount,
int sampleRate,
double offset,
double framePeriod,
UnitKey[] units)
{
Settings = settings;
StartFrame = startFrame;
FrameCount = frameCount;
SampleRate = sampleRate;
Offset = offset;
FramePeriod = framePeriod;
this.units = units;
var code = new HashCode();
code.Add(settings);
code.Add(startFrame);
code.Add(frameCount);
code.Add(sampleRate);
code.Add(offset);
code.Add(framePeriod);
foreach (var unit in units)
code.Add(unit);
@@ -122,24 +119,18 @@ internal sealed class SegmentKey : IEquatable<SegmentKey>
public RenderSettings Settings { get; }
public int StartFrame { get; }
public int FrameCount { get; }
public int SampleRate { get; }
public double Offset { get; }
public double FramePeriod { get; }
public bool Equals(SegmentKey? other)
=> other is not null
&& hash == other.hash
&& Settings == other.Settings
&& StartFrame == other.StartFrame
&& FrameCount == other.FrameCount
&& SampleRate == other.SampleRate
&& Offset.Equals(other.Offset)
&& FramePeriod.Equals(other.FramePeriod)
&& units.AsSpan().SequenceEqual(other.units.AsSpan());
+4
ファイルの表示
@@ -68,6 +68,10 @@ internal static class SpectrumTransform
}
}
public static double ToAmplitude(double power) => Math.Sqrt(power);
public static double ToPower(double amplitude) => amplitude * amplitude;
public static double Clamp(double aperiodicity)
=> double.IsNaN(aperiodicity)
? MaximumAperiodicity
+6 -7
ファイルの表示
@@ -21,17 +21,14 @@ internal readonly record struct TimeMap(
StretchMode stretchMode)
{
var scale = VelocityToConsonantScale(velocity);
var consonantSourceLength = Math.Max(consonantEnd - regionStart, 0.0);
var consonantOutputLength = Math.Min(consonantSourceLength * scale, Math.Max(outputLength, 0.0));
if (consonantSourceLength > 0.0 && consonantOutputLength > 0.0)
scale = consonantOutputLength / consonantSourceLength;
var consonantOutputLength = Math.Max(consonantEnd - regionStart, 0.0) * scale;
return new TimeMap(
regionStart,
consonantEnd,
regionEnd,
consonantOutputLength,
Math.Max(outputLength - consonantOutputLength, 0.0),
Math.Max(Math.Max(outputLength, 0.0) - consonantOutputLength, 0.0),
scale,
stretchMode);
}
@@ -53,8 +50,10 @@ internal readonly record struct TimeMap(
var elapsed = outputMilliseconds - ConsonantOutputLength;
if (StretchMode == StretchMode.Stretch)
{
var progress = SustainOutputLength > 0.0 ? Math.Clamp(elapsed / SustainOutputLength, 0.0, 1.0) : 0.0;
return ConsonantEnd + sustainSourceLength * progress;
var speed = SustainOutputLength > 0.0
? Math.Clamp(sustainSourceLength / SustainOutputLength, 0.0, 1.0)
: 0.0;
return Math.Min(ConsonantEnd + elapsed * speed, RegionEnd);
}
var period = sustainSourceLength * 2.0;
+58 -22
ファイルの表示
@@ -1,3 +1,4 @@
using UTAU.Notes;
using UTAU.Phonemes;
namespace UTAU.Synthesis;
@@ -7,7 +8,8 @@ internal readonly record struct UnitTiming(
double AudioStartMilliseconds,
double RenderLengthMilliseconds,
double FadeInMilliseconds,
double FadeOutMilliseconds)
double FadeOutMilliseconds,
double SkipMilliseconds)
{
public double AudioEndMilliseconds => AudioStartMilliseconds + RenderLengthMilliseconds;
@@ -33,32 +35,63 @@ internal readonly record struct UnitTiming(
internal static class UnitTimingBuilder
{
const double AdjacentHeadShare = 0.5;
const double PlosiveHeadShare = 0.9;
public static IReadOnlyList<UnitTiming> Build(IReadOnlyList<PhonemeUnit> units)
{
var timings = new List<UnitTiming>(units.Count);
var preutterances = new double[units.Count];
var overlaps = new double[units.Count];
var adjacent = new bool[units.Count];
var skips = new double[units.Count];
for (var i = 0; i < units.Count; i++)
{
var preutterance = units[i].Preutterance;
var overlap = units[i].Overlap;
var head = preutterance - overlap;
var available = i == 0 ? 0.0 : units[i - 1].LengthMilliseconds;
var consonantScale = TimeMap.VelocityToConsonantScale(units[i].Note.Velocity);
var preutterance = units[i].HasPreutteranceOverride ? units[i].Preutterance : units[i].Preutterance * consonantScale;
var overlap = units[i].HasOverlapOverride ? units[i].Overlap : units[i].Overlap * consonantScale;
var requested = preutterance;
var preceding = FindPrecedingVoiced(units, i);
if (i > 0 && head > available && head > 0.0)
if (preceding >= 0)
{
var ratio = available / head;
preutterance *= ratio;
overlap *= ratio;
}
else if (i == 0 && head < 0.0)
{
overlap = preutterance;
var precedingLength = units[preceding].LengthMilliseconds;
var gap = units[i].StartMilliseconds - units[preceding].EndMilliseconds;
var limit = preutterance;
adjacent[i] = gap <= 0.0;
if (adjacent[i])
{
var head = preutterance - overlap;
if (overlap > 0.0)
{
if (head > precedingLength * AdjacentHeadShare)
limit = precedingLength * AdjacentHeadShare / head * preutterance;
}
else
limit = Math.Min(limit, precedingLength * PlosiveHeadShare);
limit = Math.Min(limit, precedingLength);
if (preutterances[preceding] < UTAUNote.DefaultFadeInMilliseconds)
limit = Math.Min(limit, precedingLength + preutterances[preceding] - UTAUNote.DefaultFadeInMilliseconds);
}
else if (gap < preutterance)
limit = gap;
if (preutterance > limit)
{
overlap *= preutterance > 0.0 ? limit / preutterance : 0.0;
preutterance = limit;
}
if (overlap < 0.0)
overlap = Math.Max(overlap, Math.Min(0.0, UTAUNote.DefaultFadeOutMilliseconds - precedingLength + preutterance));
}
preutterances[i] = preutterance;
overlaps[i] = Math.Max(overlap, 0.0);
preutterances[i] = Math.Max(preutterance, 0.0);
overlaps[i] = overlap;
skips[i] = Math.Max(requested - preutterances[i], 0.0);
}
for (var i = 0; i < units.Count; i++)
@@ -74,12 +107,11 @@ internal static class UnitTimingBuilder
: units[next].StartMilliseconds - preutterances[next] + overlaps[next] - audioStart;
renderLength = Math.Max(renderLength, RenderSettings.MinimumUnitLengthMilliseconds);
var previous = FindPreviousVoiced(units, i);
var fadeIn = previous >= 0 && overlaps[i] > 0.0 ? overlaps[i] : unit.Note.FadeInMilliseconds;
var fadeOut = next >= 0 && overlaps[next] > 0.0 ? overlaps[next] : unit.Note.FadeOutMilliseconds;
var fadeIn = adjacent[i] && overlaps[i] > 0.0 ? overlaps[i] : unit.Note.FadeInMilliseconds;
var fadeOut = next >= 0 && adjacent[next] && overlaps[next] > 0.0 ? overlaps[next] : unit.Note.FadeOutMilliseconds;
(fadeIn, fadeOut) = LimitFades(fadeIn, fadeOut, renderLength);
timings.Add(new UnitTiming(unit, audioStart, renderLength, fadeIn, fadeOut));
timings.Add(new UnitTiming(unit, audioStart, renderLength, fadeIn, fadeOut, skips[i]));
}
return timings;
@@ -103,9 +135,13 @@ internal static class UnitTimingBuilder
return next < units.Count && !units[next].IsSilent ? next : -1;
}
static int FindPreviousVoiced(IReadOnlyList<PhonemeUnit> units, int index)
static int FindPrecedingVoiced(IReadOnlyList<PhonemeUnit> units, int index)
{
var previous = index - 1;
return previous >= 0 && !units[previous].IsSilent ? previous : -1;
for (var preceding = index - 1; preceding >= 0; preceding--)
{
if (!units[preceding].IsSilent)
return preceding;
}
return -1;
}
}
+182 -70
ファイルの表示
@@ -15,7 +15,8 @@ internal sealed class UtauRenderer(RenderSettings settings, RenderCurves curves,
double RegionStart,
double RegionEnd,
double ConsonantEnd,
double MeanF0);
double MeanF0,
double AutoGain);
sealed record Segment(int StartFrame, int FrameCount, IReadOnlyList<int> TimingIndices);
@@ -36,18 +37,55 @@ internal sealed class UtauRenderer(RenderSettings settings, RenderCurves curves,
int EndSample,
double RegionStart,
double RegionEnd,
double ConsonantEnd);
double ConsonantEnd,
double SourcePeak,
double RegionPeak);
sealed class RenderState : IDisposable
{
public required WorldArena Arena { get; init; }
public required SegmentBuffers Buffers { get; init; }
public required double[] FrameSpectrum { get; init; }
public required double[] WarpedSpectrum { get; init; }
public required double[] FrameAperiodicity { get; init; }
public static RenderState Create(int widest, int spectrumSize, int outputSamples) => new()
{
Arena = new WorldArena(),
Buffers = new SegmentBuffers(
new double[widest],
new double[(long)widest * spectrumSize],
new double[(long)widest * spectrumSize],
new double[widest],
new double[widest],
new double[widest],
new double[outputSamples]),
FrameSpectrum = new double[spectrumSize],
WarpedSpectrum = new double[spectrumSize],
FrameAperiodicity = new double[spectrumSize],
};
public void Dispose() => Arena.Dispose();
}
const long RenderBufferBudgetBytes = 768L * 1024 * 1024;
const long MaximumFrameElements = 1L << 24;
const double FrameCountEpsilon = 1e-9;
const int SegmentGapFrames = 10;
const double PeakCompressionPercent = 86.0;
const double PeakTarget = 0.5;
const double VoicedRatioBias = 5.0;
const double VoicedRatioSlope = 10.0;
readonly Dictionary<string, AudioSample> loadedSamples = new(StringComparer.OrdinalIgnoreCase);
public RenderResult Render(IReadOnlyList<PhonemeUnit> units, WorldArena arena)
public RenderResult Render(IReadOnlyList<PhonemeUnit> units)
{
ArgumentNullException.ThrowIfNull(units);
ArgumentNullException.ThrowIfNull(arena);
var timings = UnitTimingBuilder.Build(units);
if (timings.Count == 0)
@@ -76,60 +114,87 @@ internal sealed class UtauRenderer(RenderSettings settings, RenderCurves curves,
var outputLength = ToSampleIndex(frameCount - 1, framePeriod, sampleRate) + 1;
var samples = new double[outputLength];
var frameSpectrum = new double[spectrumSize];
var warpedSpectrum = new double[spectrumSize];
var frameAperiodicity = new double[spectrumSize];
var widest = segments.Max(x => x.FrameCount);
var buffers = new SegmentBuffers(
new double[widest],
new double[widest * spectrumSize],
new double[widest * spectrumSize],
new double[widest],
new double[widest],
new double[widest],
new double[ToSampleIndex(widest - 1, framePeriod, sampleRate) + 1]);
var cacheable = ReferenceEquals(curves, RenderCurves.Empty);
var outputSamples = ToSampleIndex(widest - 1, framePeriod, sampleRate) + 1;
foreach (var segment in segments)
{
var produced = ToSampleIndex(segment.FrameCount - 1, framePeriod, sampleRate) + 1;
var start = ToSampleIndex(segment.StartFrame, framePeriod, sampleRate);
var length = Math.Min(produced, samples.Length - start);
if (length <= 0)
continue;
var key = cacheable
? BuildSegmentKey(segment, timings, requests, offset, framePeriod, sampleRate)
: null;
if (key is not null && segmentCache.TryCopyInto(key, samples.AsSpan(start, length)))
continue;
RenderSegment(
segment,
timings,
requests,
arena,
offset,
framePeriod,
sampleRate,
fftSize,
spectrumSize,
frameSpectrum,
warpedSpectrum,
frameAperiodicity,
buffers,
samples);
if (key is not null)
segmentCache.Store(key, samples.AsSpan(start, length));
}
Parallel.For(
0,
segments.Count,
new ParallelOptions { MaxDegreeOfParallelism = DetermineParallelism(widest, spectrumSize, segments.Count) },
() => RenderState.Create(widest, spectrumSize, outputSamples),
(index, _, state) =>
{
var limit = index + 1 < segments.Count
? ToSampleIndex(segments[index + 1].StartFrame, framePeriod, sampleRate)
: samples.Length;
RenderOne(segments[index], limit, timings, requests, state, offset, framePeriod, sampleRate, fftSize, spectrumSize, samples, cacheable);
return state;
},
state => state.Dispose());
return new RenderResult(samples, sampleRate, timings, offset);
}
static int DetermineParallelism(int widest, int spectrumSize, int segmentCount)
{
var perWorker = (long)widest * spectrumSize * sizeof(double) * 2;
if (perWorker <= 0)
return 1;
var affordable = (int)Math.Clamp(RenderBufferBudgetBytes / perWorker, 1, Environment.ProcessorCount);
return Math.Min(affordable, Math.Max(segmentCount, 1));
}
void RenderOne(
Segment segment,
int outputLimit,
IReadOnlyList<UnitTiming> timings,
IReadOnlyList<AnalysisRequest?> requests,
RenderState state,
double offset,
double framePeriod,
int sampleRate,
int fftSize,
int spectrumSize,
double[] samples,
bool cacheable)
{
var produced = ToSampleIndex(segment.FrameCount - 1, framePeriod, sampleRate) + 1;
var start = ToSampleIndex(segment.StartFrame, framePeriod, sampleRate);
var length = Math.Min(Math.Min(produced, samples.Length - start), outputLimit - start);
if (length <= 0)
return;
var key = cacheable
? BuildSegmentKey(segment, timings, requests, offset, framePeriod, sampleRate)
: null;
if (key is not null && segmentCache.TryCopyInto(key, samples.AsSpan(start, length)))
return;
RenderSegment(
segment,
start,
length,
timings,
requests,
state.Arena,
offset,
framePeriod,
sampleRate,
fftSize,
spectrumSize,
state.FrameSpectrum,
state.WarpedSpectrum,
state.FrameAperiodicity,
state.Buffers,
samples);
if (key is not null)
segmentCache.Store(key, state.Buffers.Output.AsSpan(0, produced));
}
static int ToSampleIndex(int frame, double framePeriod, int sampleRate)
=> (int)(frame * framePeriod / 1000.0 * sampleRate);
@@ -141,6 +206,7 @@ internal sealed class UtauRenderer(RenderSettings settings, RenderCurves curves,
double framePeriod,
int sampleRate)
{
var origin = offset + segment.StartFrame * framePeriod;
var units = new UnitKey[segment.TimingIndices.Count];
for (var i = 0; i < units.Length; i++)
@@ -161,11 +227,12 @@ internal sealed class UtauRenderer(RenderSettings settings, RenderCurves curves,
request.RegionEnd,
request.ConsonantEnd)
: null,
timing.AudioStartMilliseconds,
timing.AudioStartMilliseconds - origin,
timing.RenderLengthMilliseconds,
timing.FadeInMilliseconds,
timing.FadeOutMilliseconds,
unit.NoteStartMilliseconds,
timing.SkipMilliseconds,
unit.NoteStartMilliseconds - origin,
unit.NoteLengthMilliseconds,
unit.Tone,
note.LengthTicks,
@@ -176,7 +243,7 @@ internal sealed class UtauRenderer(RenderSettings settings, RenderCurves curves,
[.. note.PitchPoints]);
}
return new SegmentKey(settings, segment.StartFrame, segment.FrameCount, sampleRate, offset, framePeriod, units);
return new SegmentKey(settings, segment.FrameCount, sampleRate, framePeriod, units);
}
static IReadOnlyList<Segment> BuildSegments(
@@ -215,6 +282,8 @@ internal sealed class UtauRenderer(RenderSettings settings, RenderCurves curves,
void RenderSegment(
Segment segment,
int outputStart,
int outputLength,
IReadOnlyList<UnitTiming> timings,
IReadOnlyList<AnalysisRequest?> requests,
WorldArena arena,
@@ -245,6 +314,12 @@ internal sealed class UtauRenderer(RenderSettings settings, RenderCurves curves,
Array.Clear(voicedWeight, 0, frameCount);
Array.Clear(logF0Sum, 0, frameCount);
var track = PitchTrack.Create(
[.. segment.TimingIndices.Select(x => timings[x])],
offset + segment.StartFrame * framePeriod,
framePeriod,
frameCount);
foreach (var index in segment.TimingIndices)
{
var source = BuildSource(requests[index], arena);
@@ -254,6 +329,7 @@ internal sealed class UtauRenderer(RenderSettings settings, RenderCurves curves,
AccumulateUnit(
timings[index],
source,
track,
offset,
framePeriod,
segment.StartFrame,
@@ -284,15 +360,13 @@ internal sealed class UtauRenderer(RenderSettings settings, RenderCurves curves,
output,
arena);
var start = ToSampleIndex(segment.StartFrame, framePeriod, sampleRate);
var length = Math.Min(produced, samples.Length - start);
if (length > 0)
Array.Copy(buffers.Output, 0, samples, start, length);
Array.Copy(buffers.Output, 0, samples, outputStart, outputLength);
}
void AccumulateUnit(
UnitTiming timing,
UnitSource source,
PitchTrack track,
double offset,
double framePeriod,
int segmentStartFrame,
@@ -311,11 +385,11 @@ internal sealed class UtauRenderer(RenderSettings settings, RenderCurves curves,
var note = unit.Note;
var startFrame = Math.Max((int)Math.Floor((timing.AudioStartMilliseconds - offset) / framePeriod) - segmentStartFrame, 0);
var endFrame = Math.Min((int)Math.Ceiling((timing.AudioEndMilliseconds - offset) / framePeriod) - segmentStartFrame, frameCount - 1);
var gain = settings.Gain * Math.Clamp(note.Intensity, 0.0, 200.0) / 100.0;
var gain = settings.Gain * Math.Clamp(note.Intensity, 0.0, 200.0) / 100.0 * source.AutoGain;
var baseFormantRatio = settings.FormantRatio;
var hasFormantCurve = curves.HasFormant;
var hasBreathinessCurve = curves.HasBreathiness;
var map = TimeMap.Create(source.RegionStart, source.ConsonantEnd, source.RegionEnd, timing.RenderLengthMilliseconds, note.Velocity, settings.StretchMode);
var map = TimeMap.Create(source.RegionStart, source.ConsonantEnd, source.RegionEnd, timing.RenderLengthMilliseconds + timing.SkipMilliseconds, note.Velocity, settings.StretchMode);
var modulation = Math.Clamp(note.Modulation, -200.0, 200.0) / 100.0;
for (var frame = startFrame; frame <= endFrame; frame++)
@@ -326,7 +400,7 @@ internal sealed class UtauRenderer(RenderSettings settings, RenderCurves curves,
if (weight <= 0.0)
continue;
var sourceMilliseconds = map.Map(elapsed);
var sourceMilliseconds = map.Map(elapsed + timing.SkipMilliseconds);
var frameIndex = source.Features.GetFrameIndex(sourceMilliseconds);
SampleFeatures(source.Features, frameIndex, frameSpectrum, frameAperiodicity, out var sourceF0);
@@ -346,7 +420,7 @@ internal sealed class UtauRenderer(RenderSettings settings, RenderCurves curves,
var baseIndex = (long)frame * spectrumSize;
for (var k = 0; k < spectrumSize; k++)
{
spectrogram[baseIndex + k] += weight * warpedSpectrum[k];
spectrogram[baseIndex + k] += weight * SpectrumTransform.ToAmplitude(warpedSpectrum[k]);
aperiodicity[baseIndex + k] += weight * frameAperiodicity[k];
}
weightSum[frame] += weight;
@@ -354,11 +428,7 @@ internal sealed class UtauRenderer(RenderSettings settings, RenderCurves curves,
if (sourceF0 <= 0.0)
continue;
var progress = unit.NoteLengthMilliseconds > 0.0
? (absolute - unit.NoteStartMilliseconds) / unit.NoteLengthMilliseconds
: 0.0;
var cents = note.EvaluatePitchOffsetCents(progress, unit.NoteLengthMilliseconds);
var targetF0 = MusicalTone.FrequencyOf(unit.Tone + cents / 100.0);
var targetF0 = MusicalTone.FrequencyOf(track.CentsAt(frame) / 100.0);
var ratio = source.MeanF0 > 0.0 ? sourceF0 / source.MeanF0 : 1.0;
var value = targetF0 * Math.Pow(ratio, modulation);
if (!double.IsFinite(value) || value <= 0.0)
@@ -397,7 +467,7 @@ internal sealed class UtauRenderer(RenderSettings settings, RenderCurves curves,
for (var k = 0; k < spectrumSize; k++)
{
spectrogram[baseIndex + k] = Math.Max(spectrogram[baseIndex + k], SpectrumTransform.MinimumPower);
spectrogram[baseIndex + k] = Math.Max(SpectrumTransform.ToPower(spectrogram[baseIndex + k]), SpectrumTransform.MinimumPower);
aperiodicity[baseIndex + k] = SpectrumTransform.Clamp(aperiodicity[baseIndex + k] / total);
}
@@ -476,7 +546,19 @@ internal sealed class UtauRenderer(RenderSettings settings, RenderCurves curves,
endSample,
regionStart,
regionEnd,
consonantEnd);
consonantEnd,
Peak(sample.Samples, 0, sample.Samples.Length),
Peak(sample.Samples, sample.MillisecondsToSamples(regionStart), sample.MillisecondsToSamples(regionEnd)));
}
static double Peak(ReadOnlySpan<double> samples, int from, int to)
{
from = Math.Clamp(from, 0, samples.Length);
to = Math.Clamp(to, from, samples.Length);
var peak = 0.0;
for (var i = from; i < to; i++)
peak = Math.Max(peak, Math.Abs(samples[i]));
return peak;
}
void AnalyzeInParallel(IReadOnlyList<AnalysisRequest?> requests)
@@ -524,7 +606,35 @@ internal sealed class UtauRenderer(RenderSettings settings, RenderCurves curves,
value.RegionStart,
value.RegionEnd,
value.ConsonantEnd,
ComputeMeanF0(features, value.RegionStart, value.RegionEnd));
ComputeMeanF0(features, value.RegionStart, value.RegionEnd),
ComputeAutoGain(
value.SourcePeak,
value.RegionPeak,
ComputeVoicedRatio(features, value.RegionStart, value.RegionEnd)));
}
static double ComputeVoicedRatio(WorldFeatures features, double regionStart, double regionEnd)
{
var voiced = 0;
var count = 0;
var first = Math.Max((int)Math.Floor(features.GetFrameIndex(regionStart)), 0);
var last = Math.Min((int)Math.Ceiling(features.GetFrameIndex(regionEnd)), features.FrameCount - 1);
for (var i = first; i <= last; i++)
{
count++;
if (features.F0[i] > 0.0)
voiced++;
}
return count == 0 ? 0.0 : (double)voiced / count;
}
static double ComputeAutoGain(double sourcePeak, double regionPeak, double voicedRatio)
{
var weight = 1.0 / (1.0 + Math.Exp(VoicedRatioBias - VoicedRatioSlope * voicedRatio));
var peak = regionPeak * weight + sourcePeak * (1.0 - weight);
return peak <= 0.0 ? 1.0 : Math.Pow(PeakTarget / peak, PeakCompressionPercent / 100.0);
}
static double ComputeMeanF0(WorldFeatures features, double regionStart, double regionEnd)
@@ -559,6 +669,7 @@ internal sealed class UtauRenderer(RenderSettings settings, RenderCurves curves,
}
catch (Exception exception) when (exception is IOException or InvalidOperationException or FormatException or NotSupportedException or ArgumentException)
{
UTAUTelemetry.Report(exception);
return null;
}
}
@@ -585,6 +696,7 @@ internal sealed class UtauRenderer(RenderSettings settings, RenderCurves curves,
}
catch (Exception exception) when (exception is IOException or InvalidOperationException or FormatException or NotSupportedException or ArgumentException)
{
UTAUTelemetry.Report(exception);
}
}
+18 -2
ファイルの表示
@@ -198,14 +198,30 @@
<data name="PitchPointCentsDescription" xml:space="preserve"><value>الانحراف عن درجة النوتة. 100 سنت تساوي نصف نغمة.</value></data>
<data name="SelectAllNotes" xml:space="preserve"><value>تحديد كل النوتات</value></data>
<data name="SelectionCountFormat" xml:space="preserve"><value>تم تحديد {0} نوتة</value></data>
<data name="NoteContextCopy" xml:space="preserve"><value>نسخ النوتات</value></data>
<data name="NoteContextPaste" xml:space="preserve"><value>لصق النوتات</value></data>
<data name="OctaveUp" xml:space="preserve"><value>رفع أوكتاف</value></data>
<data name="OctaveDown" xml:space="preserve"><value>خفض أوكتاف</value></data>
<data name="QuantizeLength" xml:space="preserve"><value>محاذاة الأطوال إلى المحاذاة</value></data>
<data name="ResetGroup" xml:space="preserve"><value>إعادة الضبط</value></data>
<data name="ResetVibrato" xml:space="preserve"><value>إعادة ضبط الفيبراتو</value></data>
<data name="ResetTiming" xml:space="preserve"><value>إعادة ضبط التوقيت</value></data>
<data name="ResetNote" xml:space="preserve"><value>إعادة ضبط النوتات إلى الافتراضي</value></data>
<data name="UstImportedFormat" xml:space="preserve"><value>تم تحميل {0} نوتة</value></data>
<data name="UstImportFailed" xml:space="preserve"><value>تعذّر قراءة ملف UST</value></data>
<data name="UstImportEmpty" xml:space="preserve"><value>لا توجد نوتات لتحميلها في الملف</value></data>
<data name="UstLegacyPitchIgnored" xml:space="preserve"><value>لم يتم استيراد بيانات الدرجة القديمة</value></data>
<data name="UstRestTrimmedFormat" xml:space="preserve"><value>تمت إزالة {0} تِك من السكتات في البداية والنهاية</value></data>
<data name="UstPhraseTotalFormat" xml:space="preserve"><value>{0} عبارة إجمالاً</value></data>
<data name="UstPhraseRangeFormat" xml:space="preserve"><value>تم تحميل {1} عبارة بدءاً من العبارة {0}</value></data>
<data name="UstPhraseOffsetFormat" xml:space="preserve"><value>يبدأ عند التِك {0} من الأصل</value></data>
<data name="UstPhraseRangeFormat" xml:space="preserve"><value>{1} من {2} عبارة بدءاً من {0}</value></data>
<data name="UstPhraseOffsetFormat" xml:space="preserve"><value>من التِك {0} في الأصل</value></data>
<data name="NoteTempo" xml:space="preserve"><value>الإيقاع</value></data>
<data name="NoteTempoDescription" xml:space="preserve"><value>القيمة 0 تتبع إيقاع النوتة الموسيقية. وإدخال قيمة يغيّر الإيقاع بدءاً من هذه النوتة.</value></data>
<data name="EditLyrics" xml:space="preserve"><value>تحرير الكلمات دفعة واحدة</value></data>
<data name="LyricsBulkEditHint" xml:space="preserve"><value>تُفصل الكلمات بالمسافات وفواصل الأسطر. تُؤخذ الكانجي والكانا حرفاً حرفاً، ويصبح الجزء المحاط بعلامتي اقتباس نوتة واحدة.</value></data>
<data name="LyricCountFormat" xml:space="preserve"><value>{0} / {1}</value></data>
<data name="ButtonApply" xml:space="preserve"><value>تطبيق</value></data>
<data name="ButtonCancel" xml:space="preserve"><value>إلغاء</value></data>
<data name="ButtonReset" xml:space="preserve"><value>استرجاع</value></data>
<data name="DetachEditor" xml:space="preserve"><value>التحرير في نافذة منفصلة</value></data>
</root>
+18 -2
ファイルの表示
@@ -138,13 +138,29 @@ PitchPointTimeDescription,,ノートの先頭からの位置です。480ティ
PitchPointCentsDescription,,ノートの音程からのずれです。100セントが半音です。,The offset from the pitch of the note. 100 cents is a semitone.,相对音符音高的偏移。100 音分为半音。,相對音符音高的偏移。100 音分為半音。,노트 음정으로부터의 차이입니다. 100센트가 반음입니다.,El desvío respecto al tono de la nota. 100 centésimas equivalen a un semitono.,الانحراف عن درجة النوتة. 100 سنت تساوي نصف نغمة.,Selisih dari nada not. 100 sen sama dengan satu seminada.
SelectAllNotes,,すべてのノートを選択,Select all the notes,选择所有音符,選擇所有音符,모든 노트 선택,Seleccionar todas las notas,تحديد كل النوتات,Pilih semua not
SelectionCountFormat,,{0} 個を選択中,{0} notes selected,已选择 {0} 个音符,已選擇 {0} 個音符,{0}개 선택 중,{0} notas seleccionadas,تم تحديد {0} نوتة,{0} not terpilih
NoteContextCopy,,ノートをコピー,Copy the notes,复制音符,複製音符,노트 복사,Copiar las notas,نسخ النوتات,Salin not
NoteContextPaste,,ノートを貼り付け,Paste the notes,粘贴音符,貼上音符,노트 붙여넣기,Pegar las notas,لصق النوتات,Tempel not
OctaveUp,,オクターブ上げる,Move an octave up,升高八度,升高八度,한 옥타브 올리기,Subir una octava,رفع أوكتاف,Naikkan satu oktaf
OctaveDown,,オクターブ下げる,Move an octave down,降低八度,降低八度,한 옥타브 내리기,Bajar una octava,خفض أوكتاف,Turunkan satu oktaf
QuantizeLength,,長さを吸着に合わせる,Round the lengths to the snap,将长度对齐到吸附,將長度對齊到吸附,길이를 스냅에 맞추기,Ajustar las duraciones al ajuste,محاذاة الأطوال إلى المحاذاة,Bulatkan panjang ke pengancingan
ResetGroup,,戻す,Reset,重置,重設,되돌리기,Restablecer,إعادة الضبط,Setel ulang
ResetVibrato,,ビブラートを戻す,Reset the vibrato,重置颤音,重設顫音,비브라토 되돌리기,Restablecer el vibrato,إعادة ضبط الفيبراتو,Setel ulang vibrato
ResetTiming,,発声タイミングを戻す,Reset the timing,重置发声时间,重設發聲時間,발성 타이밍 되돌리기,Restablecer los tiempos,إعادة ضبط التوقيت,Setel ulang pewaktuan
ResetNote,,ノートを既定に戻す,Reset the notes to the defaults,将音符重置为默认值,將音符重設為預設值,노트를 기본값으로 되돌리기,Restablecer las notas a los valores predeterminados,إعادة ضبط النوتات إلى الافتراضي,Setel ulang not ke bawaan
UstImportedFormat,,{0} 個のノートを読み込みました,Loaded {0} notes,已载入 {0} 个音符,已載入 {0} 個音符,노트 {0}개를 불러왔습니다,Se cargaron {0} notas,تم تحميل {0} نوتة,Memuat {0} not
UstImportFailed,,USTを読み込めませんでした,The UST file could not be read,无法读取 UST 文件,無法讀取 UST 檔案,UST를 읽지 못했습니다,No se pudo leer el archivo UST,تعذّر قراءة ملف UST,Berkas UST tidak dapat dibaca
UstImportEmpty,,読み込めるノートがありません,The file has no notes to load,文件中没有可载入的音符,檔案中沒有可載入的音符,불러올 노트가 없습니다,El archivo no tiene notas que cargar,لا توجد نوتات لتحميلها في الملف,Berkas tidak memiliki not untuk dimuat
UstLegacyPitchIgnored,,旧式の音程は取り込めません,The legacy pitch data was not imported,未导入旧式音高数据,未匯入舊式音高資料,구형 음정 자료는 가져오지 않았습니다,Los datos de tono heredados no se importaron,لم يتم استيراد بيانات الدرجة القديمة,Data nada lawas tidak diimpor
UstRestTrimmedFormat,,前後の休符 {0} ティックを除きました,Trimmed {0} ticks of leading and trailing rests,已去除首尾休止符 {0} 刻,已去除首尾休止符 {0} 刻,앞뒤 쉼표 {0}틱을 제거했습니다,Se recortaron {0} tics de silencios inicial y final,تمت إزالة {0} تِك من السكتات في البداية والنهاية,Memangkas {0} tik istirahat di awal dan akhir
UstPhraseTotalFormat,,全 {0} フレーズ,{0} phrases in total,共 {0} 个乐句,共 {0} 個樂句,전체 {0} 프레이즈,{0} frases en total,{0} عبارة إجمالاً,Total {0} frasa
UstPhraseRangeFormat,,フレーズ {0} から {1} 個を読み込みました,Loaded {1} phrases starting at phrase {0},从第 {0} 个乐句起载入了 {1} 个,從第 {0} 個樂句起載入了 {1} 個,프레이즈 {0}부터 {1}개를 불러왔습니다,Se cargaron {1} frases desde la frase {0},تم تحميل {1} عبارة بدءاً من العبارة {0},Memuat {1} frasa mulai dari frasa {0}
UstPhraseOffsetFormat,,元の {0} ティック目から始まります,Starts {0} ticks into the original,从原曲第 {0} 刻开始,從原曲第 {0} 刻開始,원곡의 {0}틱부터 시작합니다,Empieza en el tic {0} del original,يبدأ عند التِك {0} من الأصل,Dimulai pada tik {0} dari aslinya
UstPhraseRangeFormat,,全 {2} フレーズ中 {0} から {1} 個,{1} of {2} phrases from {0},共 {2} 个乐句中自第 {0} 个起 {1} 个,共 {2} 個樂句中自第 {0} 個起 {1} 個,전체 {2} 프레이즈 중 {0}부터 {1}개,{1} de {2} frases desde la {0},{1} من {2} عبارة بدءاً من {0},{1} dari {2} frasa mulai {0}
UstPhraseOffsetFormat,,元の {0} ティック目から,from tick {0} of the original,自原曲第 {0} 刻,自原曲第 {0} 刻,원곡 {0}틱부터,desde el tic {0} del original,من التِك {0} في الأصل,dari tik {0} aslinya
NoteTempo,,テンポ,Tempo,速度,速度,템포,Tempo,الإيقاع,Tempo
NoteTempoDescription,,0でこの譜面のテンポに従います。値を入れるとこのノートから先のテンポが変わります。,0 follows the tempo of the score. A value changes the tempo from this note onward.,0 表示沿用乐谱的速度。填入数值则从该音符起改变速度。,0 表示沿用樂譜的速度。填入數值則從該音符起改變速度。,0이면 악보의 템포를 따릅니다. 값을 넣으면 이 노트부터 템포가 바뀝니다.,0 sigue el tempo de la partitura. Un valor cambia el tempo a partir de esta nota.,القيمة 0 تتبع إيقاع النوتة الموسيقية. وإدخال قيمة يغيّر الإيقاع بدءاً من هذه النوتة.,0 mengikuti tempo partitur. Sebuah nilai mengubah tempo mulai dari not ini.
EditLyrics,,歌詞をまとめて編集,Edit the lyrics together,批量编辑歌词,批次編輯歌詞,가사 일괄 편집,Editar las letras en conjunto,تحرير الكلمات دفعة واحدة,Sunting lirik sekaligus
LyricsBulkEditHint,,空白と改行で区切ります。漢字とかなは1文字ずつ、引用符で囲んだ部分はまとめて1つのノートになります。,"Words are separated by spaces and line breaks. Kanji and kana are taken one character at a time, and a part enclosed in quotation marks becomes a single note.",以空格与换行分隔。汉字与假名逐字分开,用引号括起的部分作为一个音符。,以空格與換行分隔。漢字與假名逐字分開,用引號括起的部分作為一個音符。,"공백과 줄바꿈으로 나눕니다. 한자와 가나는 한 글자씩, 따옴표로 묶은 부분은 하나의 노트가 됩니다.",Las palabras se separan con espacios y saltos de línea. Los kanji y los kana se toman de uno en uno y la parte entre comillas forma una sola nota.,تُفصل الكلمات بالمسافات وفواصل الأسطر. تُؤخذ الكانجي والكانا حرفاً حرفاً، ويصبح الجزء المحاط بعلامتي اقتباس نوتة واحدة.,"Kata dipisahkan dengan spasi dan ganti baris. Kanji dan kana diambil satu per satu, dan bagian dalam tanda kutip menjadi satu not."
LyricCountFormat,,{0} / {1},{0} / {1},{0} / {1},{0} / {1},{0} / {1},{0} / {1},{0} / {1},{0} / {1}
ButtonApply,,適用,Apply,应用,套用,적용,Aplicar,تطبيق,Terapkan
ButtonCancel,,取り消し,Cancel,取消,取消,취소,Cancelar,إلغاء,Batal
ButtonReset,,元に戻す,Revert,还原,還原,되돌리기,Revertir,استرجاع,Kembalikan
DetachEditor,,別ウィンドウで編集,Edit in a separate window,在独立窗口中编辑,在獨立視窗中編輯,별도 창에서 편집,Editar en una ventana aparte,التحرير في نافذة منفصلة,Sunting di jendela terpisah
1 Key Parameter ja-jp en-us zh-cn zh-tw ko-kr es-es ar-sa id-id
138 PitchPointCentsDescription ノートの音程からのずれです。100セントが半音です。 The offset from the pitch of the note. 100 cents is a semitone. 相对音符音高的偏移。100 音分为半音。 相對音符音高的偏移。100 音分為半音。 노트 음정으로부터의 차이입니다. 100센트가 반음입니다. El desvío respecto al tono de la nota. 100 centésimas equivalen a un semitono. الانحراف عن درجة النوتة. 100 سنت تساوي نصف نغمة. Selisih dari nada not. 100 sen sama dengan satu seminada.
139 SelectAllNotes すべてのノートを選択 Select all the notes 选择所有音符 選擇所有音符 모든 노트 선택 Seleccionar todas las notas تحديد كل النوتات Pilih semua not
140 SelectionCountFormat {0} 個を選択中 {0} notes selected 已选择 {0} 个音符 已選擇 {0} 個音符 {0}개 선택 중 {0} notas seleccionadas تم تحديد {0} نوتة {0} not terpilih
141 NoteContextCopy ノートをコピー Copy the notes 复制音符 複製音符 노트 복사 Copiar las notas نسخ النوتات Salin not
142 NoteContextPaste ノートを貼り付け Paste the notes 粘贴音符 貼上音符 노트 붙여넣기 Pegar las notas لصق النوتات Tempel not
143 OctaveUp オクターブ上げる Move an octave up 升高八度 升高八度 한 옥타브 올리기 Subir una octava رفع أوكتاف Naikkan satu oktaf
144 OctaveDown オクターブ下げる Move an octave down 降低八度 降低八度 한 옥타브 내리기 Bajar una octava خفض أوكتاف Turunkan satu oktaf
145 QuantizeLength 長さを吸着に合わせる Round the lengths to the snap 将长度对齐到吸附 將長度對齊到吸附 길이를 스냅에 맞추기 Ajustar las duraciones al ajuste محاذاة الأطوال إلى المحاذاة Bulatkan panjang ke pengancingan
146 ResetGroup 戻す Reset 重置 重設 되돌리기 Restablecer إعادة الضبط Setel ulang
147 ResetVibrato ビブラートを戻す Reset the vibrato 重置颤音 重設顫音 비브라토 되돌리기 Restablecer el vibrato إعادة ضبط الفيبراتو Setel ulang vibrato
148 ResetTiming 発声タイミングを戻す Reset the timing 重置发声时间 重設發聲時間 발성 타이밍 되돌리기 Restablecer los tiempos إعادة ضبط التوقيت Setel ulang pewaktuan
149 ResetNote ノートを既定に戻す Reset the notes to the defaults 将音符重置为默认值 將音符重設為預設值 노트를 기본값으로 되돌리기 Restablecer las notas a los valores predeterminados إعادة ضبط النوتات إلى الافتراضي Setel ulang not ke bawaan
150 UstImportedFormat {0} 個のノートを読み込みました Loaded {0} notes 已载入 {0} 个音符 已載入 {0} 個音符 노트 {0}개를 불러왔습니다 Se cargaron {0} notas تم تحميل {0} نوتة Memuat {0} not
151 UstImportFailed USTを読み込めませんでした The UST file could not be read 无法读取 UST 文件 無法讀取 UST 檔案 UST를 읽지 못했습니다 No se pudo leer el archivo UST تعذّر قراءة ملف UST Berkas UST tidak dapat dibaca
152 UstImportEmpty 読み込めるノートがありません The file has no notes to load 文件中没有可载入的音符 檔案中沒有可載入的音符 불러올 노트가 없습니다 El archivo no tiene notas que cargar لا توجد نوتات لتحميلها في الملف Berkas tidak memiliki not untuk dimuat
153 UstLegacyPitchIgnored 旧式の音程は取り込めません The legacy pitch data was not imported 未导入旧式音高数据 未匯入舊式音高資料 구형 음정 자료는 가져오지 않았습니다 Los datos de tono heredados no se importaron لم يتم استيراد بيانات الدرجة القديمة Data nada lawas tidak diimpor
154 UstRestTrimmedFormat 前後の休符 {0} ティックを除きました Trimmed {0} ticks of leading and trailing rests 已去除首尾休止符 {0} 刻 已去除首尾休止符 {0} 刻 앞뒤 쉼표 {0}틱을 제거했습니다 Se recortaron {0} tics de silencios inicial y final تمت إزالة {0} تِك من السكتات في البداية والنهاية Memangkas {0} tik istirahat di awal dan akhir
155 UstPhraseTotalFormat 全 {0} フレーズ {0} phrases in total 共 {0} 个乐句 共 {0} 個樂句 전체 {0} 프레이즈 {0} frases en total {0} عبارة إجمالاً Total {0} frasa
156 UstPhraseRangeFormat フレーズ {0} から {1} 個を読み込みました 全 {2} フレーズ中 {0} から {1} 個 Loaded {1} phrases starting at phrase {0} {1} of {2} phrases from {0} 从第 {0} 个乐句起载入了 {1} 个 共 {2} 个乐句中自第 {0} 个起 {1} 个 從第 {0} 個樂句起載入了 {1} 個 共 {2} 個樂句中自第 {0} 個起 {1} 個 프레이즈 {0}부터 {1}개를 불러왔습니다 전체 {2} 프레이즈 중 {0}부터 {1}개 Se cargaron {1} frases desde la frase {0} {1} de {2} frases desde la {0} تم تحميل {1} عبارة بدءاً من العبارة {0} {1} من {2} عبارة بدءاً من {0} Memuat {1} frasa mulai dari frasa {0} {1} dari {2} frasa mulai {0}
157 UstPhraseOffsetFormat 元の {0} ティック目から始まります 元の {0} ティック目から Starts {0} ticks into the original from tick {0} of the original 从原曲第 {0} 刻开始 自原曲第 {0} 刻 從原曲第 {0} 刻開始 自原曲第 {0} 刻 원곡의 {0}틱부터 시작합니다 원곡 {0}틱부터 Empieza en el tic {0} del original desde el tic {0} del original يبدأ عند التِك {0} من الأصل من التِك {0} في الأصل Dimulai pada tik {0} dari aslinya dari tik {0} aslinya
158 NoteTempo テンポ Tempo 速度 速度 템포 Tempo الإيقاع Tempo
159 NoteTempoDescription 0でこの譜面のテンポに従います。値を入れるとこのノートから先のテンポが変わります。 0 follows the tempo of the score. A value changes the tempo from this note onward. 0 表示沿用乐谱的速度。填入数值则从该音符起改变速度。 0 表示沿用樂譜的速度。填入數值則從該音符起改變速度。 0이면 악보의 템포를 따릅니다. 값을 넣으면 이 노트부터 템포가 바뀝니다. 0 sigue el tempo de la partitura. Un valor cambia el tempo a partir de esta nota. القيمة 0 تتبع إيقاع النوتة الموسيقية. وإدخال قيمة يغيّر الإيقاع بدءاً من هذه النوتة. 0 mengikuti tempo partitur. Sebuah nilai mengubah tempo mulai dari not ini.
160 EditLyrics 歌詞をまとめて編集 Edit the lyrics together 批量编辑歌词 批次編輯歌詞 가사 일괄 편집 Editar las letras en conjunto تحرير الكلمات دفعة واحدة Sunting lirik sekaligus
161 LyricsBulkEditHint 空白と改行で区切ります。漢字とかなは1文字ずつ、引用符で囲んだ部分はまとめて1つのノートになります。 Words are separated by spaces and line breaks. Kanji and kana are taken one character at a time, and a part enclosed in quotation marks becomes a single note. 以空格与换行分隔。汉字与假名逐字分开,用引号括起的部分作为一个音符。 以空格與換行分隔。漢字與假名逐字分開,用引號括起的部分作為一個音符。 공백과 줄바꿈으로 나눕니다. 한자와 가나는 한 글자씩, 따옴표로 묶은 부분은 하나의 노트가 됩니다. Las palabras se separan con espacios y saltos de línea. Los kanji y los kana se toman de uno en uno y la parte entre comillas forma una sola nota. تُفصل الكلمات بالمسافات وفواصل الأسطر. تُؤخذ الكانجي والكانا حرفاً حرفاً، ويصبح الجزء المحاط بعلامتي اقتباس نوتة واحدة. Kata dipisahkan dengan spasi dan ganti baris. Kanji dan kana diambil satu per satu, dan bagian dalam tanda kutip menjadi satu not.
162 LyricCountFormat {0} / {1} {0} / {1} {0} / {1} {0} / {1} {0} / {1} {0} / {1} {0} / {1} {0} / {1}
163 ButtonApply 適用 Apply 应用 套用 적용 Aplicar تطبيق Terapkan
164 ButtonCancel 取り消し Cancel 取消 取消 취소 Cancelar إلغاء Batal
165 ButtonReset 元に戻す Revert 还原 還原 되돌리기 Revertir استرجاع Kembalikan
166 DetachEditor 別ウィンドウで編集 Edit in a separate window 在独立窗口中编辑 在獨立視窗中編輯 별도 창에서 편집 Editar en una ventana aparte التحرير في نافذة منفصلة Sunting di jendela terpisah
+18 -2
ファイルの表示
@@ -198,14 +198,30 @@
<data name="PitchPointCentsDescription" xml:space="preserve"><value>The offset from the pitch of the note. 100 cents is a semitone.</value></data>
<data name="SelectAllNotes" xml:space="preserve"><value>Select all the notes</value></data>
<data name="SelectionCountFormat" xml:space="preserve"><value>{0} notes selected</value></data>
<data name="NoteContextCopy" xml:space="preserve"><value>Copy the notes</value></data>
<data name="NoteContextPaste" xml:space="preserve"><value>Paste the notes</value></data>
<data name="OctaveUp" xml:space="preserve"><value>Move an octave up</value></data>
<data name="OctaveDown" xml:space="preserve"><value>Move an octave down</value></data>
<data name="QuantizeLength" xml:space="preserve"><value>Round the lengths to the snap</value></data>
<data name="ResetGroup" xml:space="preserve"><value>Reset</value></data>
<data name="ResetVibrato" xml:space="preserve"><value>Reset the vibrato</value></data>
<data name="ResetTiming" xml:space="preserve"><value>Reset the timing</value></data>
<data name="ResetNote" xml:space="preserve"><value>Reset the notes to the defaults</value></data>
<data name="UstImportedFormat" xml:space="preserve"><value>Loaded {0} notes</value></data>
<data name="UstImportFailed" xml:space="preserve"><value>The UST file could not be read</value></data>
<data name="UstImportEmpty" xml:space="preserve"><value>The file has no notes to load</value></data>
<data name="UstLegacyPitchIgnored" xml:space="preserve"><value>The legacy pitch data was not imported</value></data>
<data name="UstRestTrimmedFormat" xml:space="preserve"><value>Trimmed {0} ticks of leading and trailing rests</value></data>
<data name="UstPhraseTotalFormat" xml:space="preserve"><value>{0} phrases in total</value></data>
<data name="UstPhraseRangeFormat" xml:space="preserve"><value>Loaded {1} phrases starting at phrase {0}</value></data>
<data name="UstPhraseOffsetFormat" xml:space="preserve"><value>Starts {0} ticks into the original</value></data>
<data name="UstPhraseRangeFormat" xml:space="preserve"><value>{1} of {2} phrases from {0}</value></data>
<data name="UstPhraseOffsetFormat" xml:space="preserve"><value>from tick {0} of the original</value></data>
<data name="NoteTempo" xml:space="preserve"><value>Tempo</value></data>
<data name="NoteTempoDescription" xml:space="preserve"><value>0 follows the tempo of the score. A value changes the tempo from this note onward.</value></data>
<data name="EditLyrics" xml:space="preserve"><value>Edit the lyrics together</value></data>
<data name="LyricsBulkEditHint" xml:space="preserve"><value>Words are separated by spaces and line breaks. Kanji and kana are taken one character at a time, and a part enclosed in quotation marks becomes a single note.</value></data>
<data name="LyricCountFormat" xml:space="preserve"><value>{0} / {1}</value></data>
<data name="ButtonApply" xml:space="preserve"><value>Apply</value></data>
<data name="ButtonCancel" xml:space="preserve"><value>Cancel</value></data>
<data name="ButtonReset" xml:space="preserve"><value>Revert</value></data>
<data name="DetachEditor" xml:space="preserve"><value>Edit in a separate window</value></data>
</root>
+18 -2
ファイルの表示
@@ -198,14 +198,30 @@
<data name="PitchPointCentsDescription" xml:space="preserve"><value>El desvío respecto al tono de la nota. 100 centésimas equivalen a un semitono.</value></data>
<data name="SelectAllNotes" xml:space="preserve"><value>Seleccionar todas las notas</value></data>
<data name="SelectionCountFormat" xml:space="preserve"><value>{0} notas seleccionadas</value></data>
<data name="NoteContextCopy" xml:space="preserve"><value>Copiar las notas</value></data>
<data name="NoteContextPaste" xml:space="preserve"><value>Pegar las notas</value></data>
<data name="OctaveUp" xml:space="preserve"><value>Subir una octava</value></data>
<data name="OctaveDown" xml:space="preserve"><value>Bajar una octava</value></data>
<data name="QuantizeLength" xml:space="preserve"><value>Ajustar las duraciones al ajuste</value></data>
<data name="ResetGroup" xml:space="preserve"><value>Restablecer</value></data>
<data name="ResetVibrato" xml:space="preserve"><value>Restablecer el vibrato</value></data>
<data name="ResetTiming" xml:space="preserve"><value>Restablecer los tiempos</value></data>
<data name="ResetNote" xml:space="preserve"><value>Restablecer las notas a los valores predeterminados</value></data>
<data name="UstImportedFormat" xml:space="preserve"><value>Se cargaron {0} notas</value></data>
<data name="UstImportFailed" xml:space="preserve"><value>No se pudo leer el archivo UST</value></data>
<data name="UstImportEmpty" xml:space="preserve"><value>El archivo no tiene notas que cargar</value></data>
<data name="UstLegacyPitchIgnored" xml:space="preserve"><value>Los datos de tono heredados no se importaron</value></data>
<data name="UstRestTrimmedFormat" xml:space="preserve"><value>Se recortaron {0} tics de silencios inicial y final</value></data>
<data name="UstPhraseTotalFormat" xml:space="preserve"><value>{0} frases en total</value></data>
<data name="UstPhraseRangeFormat" xml:space="preserve"><value>Se cargaron {1} frases desde la frase {0}</value></data>
<data name="UstPhraseOffsetFormat" xml:space="preserve"><value>Empieza en el tic {0} del original</value></data>
<data name="UstPhraseRangeFormat" xml:space="preserve"><value>{1} de {2} frases desde la {0}</value></data>
<data name="UstPhraseOffsetFormat" xml:space="preserve"><value>desde el tic {0} del original</value></data>
<data name="NoteTempo" xml:space="preserve"><value>Tempo</value></data>
<data name="NoteTempoDescription" xml:space="preserve"><value>0 sigue el tempo de la partitura. Un valor cambia el tempo a partir de esta nota.</value></data>
<data name="EditLyrics" xml:space="preserve"><value>Editar las letras en conjunto</value></data>
<data name="LyricsBulkEditHint" xml:space="preserve"><value>Las palabras se separan con espacios y saltos de línea. Los kanji y los kana se toman de uno en uno y la parte entre comillas forma una sola nota.</value></data>
<data name="LyricCountFormat" xml:space="preserve"><value>{0} / {1}</value></data>
<data name="ButtonApply" xml:space="preserve"><value>Aplicar</value></data>
<data name="ButtonCancel" xml:space="preserve"><value>Cancelar</value></data>
<data name="ButtonReset" xml:space="preserve"><value>Revertir</value></data>
<data name="DetachEditor" xml:space="preserve"><value>Editar en una ventana aparte</value></data>
</root>
+18 -2
ファイルの表示
@@ -198,14 +198,30 @@
<data name="PitchPointCentsDescription" xml:space="preserve"><value>Selisih dari nada not. 100 sen sama dengan satu seminada.</value></data>
<data name="SelectAllNotes" xml:space="preserve"><value>Pilih semua not</value></data>
<data name="SelectionCountFormat" xml:space="preserve"><value>{0} not terpilih</value></data>
<data name="NoteContextCopy" xml:space="preserve"><value>Salin not</value></data>
<data name="NoteContextPaste" xml:space="preserve"><value>Tempel not</value></data>
<data name="OctaveUp" xml:space="preserve"><value>Naikkan satu oktaf</value></data>
<data name="OctaveDown" xml:space="preserve"><value>Turunkan satu oktaf</value></data>
<data name="QuantizeLength" xml:space="preserve"><value>Bulatkan panjang ke pengancingan</value></data>
<data name="ResetGroup" xml:space="preserve"><value>Setel ulang</value></data>
<data name="ResetVibrato" xml:space="preserve"><value>Setel ulang vibrato</value></data>
<data name="ResetTiming" xml:space="preserve"><value>Setel ulang pewaktuan</value></data>
<data name="ResetNote" xml:space="preserve"><value>Setel ulang not ke bawaan</value></data>
<data name="UstImportedFormat" xml:space="preserve"><value>Memuat {0} not</value></data>
<data name="UstImportFailed" xml:space="preserve"><value>Berkas UST tidak dapat dibaca</value></data>
<data name="UstImportEmpty" xml:space="preserve"><value>Berkas tidak memiliki not untuk dimuat</value></data>
<data name="UstLegacyPitchIgnored" xml:space="preserve"><value>Data nada lawas tidak diimpor</value></data>
<data name="UstRestTrimmedFormat" xml:space="preserve"><value>Memangkas {0} tik istirahat di awal dan akhir</value></data>
<data name="UstPhraseTotalFormat" xml:space="preserve"><value>Total {0} frasa</value></data>
<data name="UstPhraseRangeFormat" xml:space="preserve"><value>Memuat {1} frasa mulai dari frasa {0}</value></data>
<data name="UstPhraseOffsetFormat" xml:space="preserve"><value>Dimulai pada tik {0} dari aslinya</value></data>
<data name="UstPhraseRangeFormat" xml:space="preserve"><value>{1} dari {2} frasa mulai {0}</value></data>
<data name="UstPhraseOffsetFormat" xml:space="preserve"><value>dari tik {0} aslinya</value></data>
<data name="NoteTempo" xml:space="preserve"><value>Tempo</value></data>
<data name="NoteTempoDescription" xml:space="preserve"><value>0 mengikuti tempo partitur. Sebuah nilai mengubah tempo mulai dari not ini.</value></data>
<data name="EditLyrics" xml:space="preserve"><value>Sunting lirik sekaligus</value></data>
<data name="LyricsBulkEditHint" xml:space="preserve"><value>Kata dipisahkan dengan spasi dan ganti baris. Kanji dan kana diambil satu per satu, dan bagian dalam tanda kutip menjadi satu not.</value></data>
<data name="LyricCountFormat" xml:space="preserve"><value>{0} / {1}</value></data>
<data name="ButtonApply" xml:space="preserve"><value>Terapkan</value></data>
<data name="ButtonCancel" xml:space="preserve"><value>Batal</value></data>
<data name="ButtonReset" xml:space="preserve"><value>Kembalikan</value></data>
<data name="DetachEditor" xml:space="preserve"><value>Sunting di jendela terpisah</value></data>
</root>
+18 -2
ファイルの表示
@@ -198,14 +198,30 @@
<data name="PitchPointCentsDescription" xml:space="preserve"><value>노트 음정으로부터의 차이입니다. 100센트가 반음입니다.</value></data>
<data name="SelectAllNotes" xml:space="preserve"><value>모든 노트 선택</value></data>
<data name="SelectionCountFormat" xml:space="preserve"><value>{0}개 선택 중</value></data>
<data name="NoteContextCopy" xml:space="preserve"><value>노트 복사</value></data>
<data name="NoteContextPaste" xml:space="preserve"><value>노트 붙여넣기</value></data>
<data name="OctaveUp" xml:space="preserve"><value>한 옥타브 올리기</value></data>
<data name="OctaveDown" xml:space="preserve"><value>한 옥타브 내리기</value></data>
<data name="QuantizeLength" xml:space="preserve"><value>길이를 스냅에 맞추기</value></data>
<data name="ResetGroup" xml:space="preserve"><value>되돌리기</value></data>
<data name="ResetVibrato" xml:space="preserve"><value>비브라토 되돌리기</value></data>
<data name="ResetTiming" xml:space="preserve"><value>발성 타이밍 되돌리기</value></data>
<data name="ResetNote" xml:space="preserve"><value>노트를 기본값으로 되돌리기</value></data>
<data name="UstImportedFormat" xml:space="preserve"><value>노트 {0}개를 불러왔습니다</value></data>
<data name="UstImportFailed" xml:space="preserve"><value>UST를 읽지 못했습니다</value></data>
<data name="UstImportEmpty" xml:space="preserve"><value>불러올 노트가 없습니다</value></data>
<data name="UstLegacyPitchIgnored" xml:space="preserve"><value>구형 음정 자료는 가져오지 않았습니다</value></data>
<data name="UstRestTrimmedFormat" xml:space="preserve"><value>앞뒤 쉼표 {0}틱을 제거했습니다</value></data>
<data name="UstPhraseTotalFormat" xml:space="preserve"><value>전체 {0} 프레이즈</value></data>
<data name="UstPhraseRangeFormat" xml:space="preserve"><value>프레이즈 {0}부터 {1}개를 불러왔습니다</value></data>
<data name="UstPhraseOffsetFormat" xml:space="preserve"><value>원곡의 {0}틱부터 시작합니다</value></data>
<data name="UstPhraseRangeFormat" xml:space="preserve"><value>전체 {2} 프레이즈 중 {0}부터 {1}개</value></data>
<data name="UstPhraseOffsetFormat" xml:space="preserve"><value>원곡 {0}틱부터</value></data>
<data name="NoteTempo" xml:space="preserve"><value>템포</value></data>
<data name="NoteTempoDescription" xml:space="preserve"><value>0이면 악보의 템포를 따릅니다. 값을 넣으면 이 노트부터 템포가 바뀝니다.</value></data>
<data name="EditLyrics" xml:space="preserve"><value>가사 일괄 편집</value></data>
<data name="LyricsBulkEditHint" xml:space="preserve"><value>공백과 줄바꿈으로 나눕니다. 한자와 가나는 한 글자씩, 따옴표로 묶은 부분은 하나의 노트가 됩니다.</value></data>
<data name="LyricCountFormat" xml:space="preserve"><value>{0} / {1}</value></data>
<data name="ButtonApply" xml:space="preserve"><value>적용</value></data>
<data name="ButtonCancel" xml:space="preserve"><value>취소</value></data>
<data name="ButtonReset" xml:space="preserve"><value>되돌리기</value></data>
<data name="DetachEditor" xml:space="preserve"><value>별도 창에서 편집</value></data>
</root>
+18 -2
ファイルの表示
@@ -198,14 +198,30 @@
<data name="PitchPointCentsDescription" xml:space="preserve"><value>ノートの音程からのずれです。100セントが半音です。</value></data>
<data name="SelectAllNotes" xml:space="preserve"><value>すべてのノートを選択</value></data>
<data name="SelectionCountFormat" xml:space="preserve"><value>{0} 個を選択中</value></data>
<data name="NoteContextCopy" xml:space="preserve"><value>ノートをコピー</value></data>
<data name="NoteContextPaste" xml:space="preserve"><value>ノートを貼り付け</value></data>
<data name="OctaveUp" xml:space="preserve"><value>オクターブ上げる</value></data>
<data name="OctaveDown" xml:space="preserve"><value>オクターブ下げる</value></data>
<data name="QuantizeLength" xml:space="preserve"><value>長さを吸着に合わせる</value></data>
<data name="ResetGroup" xml:space="preserve"><value>戻す</value></data>
<data name="ResetVibrato" xml:space="preserve"><value>ビブラートを戻す</value></data>
<data name="ResetTiming" xml:space="preserve"><value>発声タイミングを戻す</value></data>
<data name="ResetNote" xml:space="preserve"><value>ノートを既定に戻す</value></data>
<data name="UstImportedFormat" xml:space="preserve"><value>{0} 個のノートを読み込みました</value></data>
<data name="UstImportFailed" xml:space="preserve"><value>USTを読み込めませんでした</value></data>
<data name="UstImportEmpty" xml:space="preserve"><value>読み込めるノートがありません</value></data>
<data name="UstLegacyPitchIgnored" xml:space="preserve"><value>旧式の音程は取り込めません</value></data>
<data name="UstRestTrimmedFormat" xml:space="preserve"><value>前後の休符 {0} ティックを除きました</value></data>
<data name="UstPhraseTotalFormat" xml:space="preserve"><value>全 {0} フレーズ</value></data>
<data name="UstPhraseRangeFormat" xml:space="preserve"><value>フレーズ {0} から {1} 個を読み込みました</value></data>
<data name="UstPhraseOffsetFormat" xml:space="preserve"><value>元の {0} ティック目から始まります</value></data>
<data name="UstPhraseRangeFormat" xml:space="preserve"><value>全 {2} フレーズ中 {0} から {1} 個</value></data>
<data name="UstPhraseOffsetFormat" xml:space="preserve"><value>元の {0} ティック目から</value></data>
<data name="NoteTempo" xml:space="preserve"><value>テンポ</value></data>
<data name="NoteTempoDescription" xml:space="preserve"><value>0でこの譜面のテンポに従います。値を入れるとこのノートから先のテンポが変わります。</value></data>
<data name="EditLyrics" xml:space="preserve"><value>歌詞をまとめて編集</value></data>
<data name="LyricsBulkEditHint" xml:space="preserve"><value>空白と改行で区切ります。漢字とかなは1文字ずつ、引用符で囲んだ部分はまとめて1つのノートになります。</value></data>
<data name="LyricCountFormat" xml:space="preserve"><value>{0} / {1}</value></data>
<data name="ButtonApply" xml:space="preserve"><value>適用</value></data>
<data name="ButtonCancel" xml:space="preserve"><value>取り消し</value></data>
<data name="ButtonReset" xml:space="preserve"><value>元に戻す</value></data>
<data name="DetachEditor" xml:space="preserve"><value>別ウィンドウで編集</value></data>
</root>
+18 -2
ファイルの表示
@@ -198,14 +198,30 @@
<data name="PitchPointCentsDescription" xml:space="preserve"><value>相对音符音高的偏移。100 音分为半音。</value></data>
<data name="SelectAllNotes" xml:space="preserve"><value>选择所有音符</value></data>
<data name="SelectionCountFormat" xml:space="preserve"><value>已选择 {0} 个音符</value></data>
<data name="NoteContextCopy" xml:space="preserve"><value>复制音符</value></data>
<data name="NoteContextPaste" xml:space="preserve"><value>粘贴音符</value></data>
<data name="OctaveUp" xml:space="preserve"><value>升高八度</value></data>
<data name="OctaveDown" xml:space="preserve"><value>降低八度</value></data>
<data name="QuantizeLength" xml:space="preserve"><value>将长度对齐到吸附</value></data>
<data name="ResetGroup" xml:space="preserve"><value>重置</value></data>
<data name="ResetVibrato" xml:space="preserve"><value>重置颤音</value></data>
<data name="ResetTiming" xml:space="preserve"><value>重置发声时间</value></data>
<data name="ResetNote" xml:space="preserve"><value>将音符重置为默认值</value></data>
<data name="UstImportedFormat" xml:space="preserve"><value>已载入 {0} 个音符</value></data>
<data name="UstImportFailed" xml:space="preserve"><value>无法读取 UST 文件</value></data>
<data name="UstImportEmpty" xml:space="preserve"><value>文件中没有可载入的音符</value></data>
<data name="UstLegacyPitchIgnored" xml:space="preserve"><value>未导入旧式音高数据</value></data>
<data name="UstRestTrimmedFormat" xml:space="preserve"><value>已去除首尾休止符 {0} 刻</value></data>
<data name="UstPhraseTotalFormat" xml:space="preserve"><value>共 {0} 个乐句</value></data>
<data name="UstPhraseRangeFormat" xml:space="preserve"><value>从第 {0} 个乐句起载入了 {1} 个</value></data>
<data name="UstPhraseOffsetFormat" xml:space="preserve"><value>从原曲第 {0} 刻开始</value></data>
<data name="UstPhraseRangeFormat" xml:space="preserve"><value>共 {2} 个乐句中自第 {0} 个起 {1} 个</value></data>
<data name="UstPhraseOffsetFormat" xml:space="preserve"><value>自原曲第 {0} 刻</value></data>
<data name="NoteTempo" xml:space="preserve"><value>速度</value></data>
<data name="NoteTempoDescription" xml:space="preserve"><value>0 表示沿用乐谱的速度。填入数值则从该音符起改变速度。</value></data>
<data name="EditLyrics" xml:space="preserve"><value>批量编辑歌词</value></data>
<data name="LyricsBulkEditHint" xml:space="preserve"><value>以空格与换行分隔。汉字与假名逐字分开,用引号括起的部分作为一个音符。</value></data>
<data name="LyricCountFormat" xml:space="preserve"><value>{0} / {1}</value></data>
<data name="ButtonApply" xml:space="preserve"><value>应用</value></data>
<data name="ButtonCancel" xml:space="preserve"><value>取消</value></data>
<data name="ButtonReset" xml:space="preserve"><value>还原</value></data>
<data name="DetachEditor" xml:space="preserve"><value>在独立窗口中编辑</value></data>
</root>
+18 -2
ファイルの表示
@@ -198,14 +198,30 @@
<data name="PitchPointCentsDescription" xml:space="preserve"><value>相對音符音高的偏移。100 音分為半音。</value></data>
<data name="SelectAllNotes" xml:space="preserve"><value>選擇所有音符</value></data>
<data name="SelectionCountFormat" xml:space="preserve"><value>已選擇 {0} 個音符</value></data>
<data name="NoteContextCopy" xml:space="preserve"><value>複製音符</value></data>
<data name="NoteContextPaste" xml:space="preserve"><value>貼上音符</value></data>
<data name="OctaveUp" xml:space="preserve"><value>升高八度</value></data>
<data name="OctaveDown" xml:space="preserve"><value>降低八度</value></data>
<data name="QuantizeLength" xml:space="preserve"><value>將長度對齊到吸附</value></data>
<data name="ResetGroup" xml:space="preserve"><value>重設</value></data>
<data name="ResetVibrato" xml:space="preserve"><value>重設顫音</value></data>
<data name="ResetTiming" xml:space="preserve"><value>重設發聲時間</value></data>
<data name="ResetNote" xml:space="preserve"><value>將音符重設為預設值</value></data>
<data name="UstImportedFormat" xml:space="preserve"><value>已載入 {0} 個音符</value></data>
<data name="UstImportFailed" xml:space="preserve"><value>無法讀取 UST 檔案</value></data>
<data name="UstImportEmpty" xml:space="preserve"><value>檔案中沒有可載入的音符</value></data>
<data name="UstLegacyPitchIgnored" xml:space="preserve"><value>未匯入舊式音高資料</value></data>
<data name="UstRestTrimmedFormat" xml:space="preserve"><value>已去除首尾休止符 {0} 刻</value></data>
<data name="UstPhraseTotalFormat" xml:space="preserve"><value>共 {0} 個樂句</value></data>
<data name="UstPhraseRangeFormat" xml:space="preserve"><value>從第 {0} 個樂句起載入了 {1} 個</value></data>
<data name="UstPhraseOffsetFormat" xml:space="preserve"><value>從原曲第 {0} 刻開始</value></data>
<data name="UstPhraseRangeFormat" xml:space="preserve"><value>共 {2} 個樂句中自第 {0} 個起 {1} 個</value></data>
<data name="UstPhraseOffsetFormat" xml:space="preserve"><value>自原曲第 {0} 刻</value></data>
<data name="NoteTempo" xml:space="preserve"><value>速度</value></data>
<data name="NoteTempoDescription" xml:space="preserve"><value>0 表示沿用樂譜的速度。填入數值則從該音符起改變速度。</value></data>
<data name="EditLyrics" xml:space="preserve"><value>批次編輯歌詞</value></data>
<data name="LyricsBulkEditHint" xml:space="preserve"><value>以空格與換行分隔。漢字與假名逐字分開,用引號括起的部分作為一個音符。</value></data>
<data name="LyricCountFormat" xml:space="preserve"><value>{0} / {1}</value></data>
<data name="ButtonApply" xml:space="preserve"><value>套用</value></data>
<data name="ButtonCancel" xml:space="preserve"><value>取消</value></data>
<data name="ButtonReset" xml:space="preserve"><value>還原</value></data>
<data name="DetachEditor" xml:space="preserve"><value>在獨立視窗中編輯</value></data>
</root>
+13 -16
ファイルの表示
@@ -5,14 +5,16 @@
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Version>1.4.1</Version>
<Version>1.7.5</Version>
<Platforms>AnyCPU;x64;x64</Platforms>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="WorldNet" Version="1.1.0" />
<PackageReference Include="ILRepack" Version="2.0.46" PrivateAssets="all" ExcludeAssets="all" GeneratePathProperty="true" />
<PackageReference Include="NAudio" Version="2.3.0" />
<PackageReference Include="WorldNet" Version="1.2.1" />
</ItemGroup>
<ItemGroup>
@@ -22,18 +24,6 @@
</ItemGroup>
<ItemGroup>
<Reference Include="NAudio">
<HintPath>$(YMM4DirPath)NAudio.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="NAudio.Core">
<HintPath>$(YMM4DirPath)NAudio.Core.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="NAudio.Midi">
<HintPath>$(YMM4DirPath)NAudio.Midi.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="NCalc.Core">
<HintPath>$(YMM4DirPath)NCalc.Core.dll</HintPath>
<Private>false</Private>
@@ -87,13 +77,20 @@
<Compile Include="..\YMM4-GitHubUpdateNotifier\GitHubUpdateNotifier\*.cs" LinkBase="GitHubUpdateNotifier" />
</ItemGroup>
<Import Project="..\YMM4-Telemetry\Telemetry.props" />
<ItemGroup>
<ProjectReference Include="..\YukkuriMovieMaker.Generator\YukkuriMovieMaker.Generator\YukkuriMovieMaker.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<AdditionalFiles Include="**/*.csv" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(SkipPluginDeploy)' != 'true'">
<Exec Command="mkdir &quot;$(YMM4DirPath)user\plugin\$(ProjectName)&quot; &gt; NUL 2&gt;&amp;1&#xD;&#xA;copy &quot;$(TargetPath)&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;&#xD;&#xA;copy &quot;$(TargetDir)WorldNet.dll&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;" />
<Target Name="MergePluginAssembly" AfterTargets="PostBuildEvent" Inputs="$(TargetPath);$(TargetDir)NAudio.dll;$(TargetDir)NAudio.Core.dll;$(TargetDir)NAudio.Asio.dll;$(TargetDir)NAudio.Midi.dll;$(TargetDir)NAudio.Wasapi.dll;$(TargetDir)NAudio.WinMM.dll" Outputs="$(TargetDir)plugin\$(TargetFileName)">
<MakeDir Directories="$(TargetDir)plugin" />
<Exec Command="&quot;$(PkgILRepack)\tools\ILRepack.exe&quot; /out:&quot;$(TargetDir)plugin\$(TargetFileName)&quot; /lib:&quot;$([System.IO.Path]::GetDirectoryName('$(TargetPath)'))&quot; /lib:&quot;$([System.IO.Path]::GetDirectoryName('$(YMM4DirPath)'))&quot; /internalize &quot;$(TargetPath)&quot; &quot;$(TargetDir)NAudio.dll&quot; &quot;$(TargetDir)NAudio.Core.dll&quot; &quot;$(TargetDir)NAudio.Asio.dll&quot; &quot;$(TargetDir)NAudio.Midi.dll&quot; &quot;$(TargetDir)NAudio.Wasapi.dll&quot; &quot;$(TargetDir)NAudio.WinMM.dll&quot;" />
</Target>
<Target Name="PostBuild" AfterTargets="MergePluginAssembly" Condition="'$(SkipPluginDeploy)' != 'true'">
<Exec Command="mkdir &quot;$(YMM4DirPath)user\plugin\$(ProjectName)&quot; &gt; NUL 2&gt;&amp;1&#xD;&#xA;copy &quot;$(TargetDir)plugin\$(TargetFileName)&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;&#xD;&#xA;copy &quot;$(TargetDir)WorldNet.dll&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;" />
</Target>
</Project>
+100
ファイルの表示
@@ -0,0 +1,100 @@
using System.Diagnostics;
using System.Reflection;
using System.Windows;
using System.Windows.Threading;
using Telemetry;
namespace UTAU;
internal static class UTAUTelemetry
{
private const int MaxChainLength = 5;
private const int MaxFrames = 100;
private static readonly Assembly Own = typeof(UTAUTelemetry).Assembly;
private static int _started;
public static void EnsureStartedOnce()
{
if (Interlocked.Exchange(ref _started, 1) != 0)
return;
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
var application = Application.Current;
if (application is not null)
application.DispatcherUnhandledException += OnDispatcherUnhandledException;
TelemetryReporter.Start();
}
public static void Report(Exception exception) => TelemetryReporter.Report(exception);
private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
=> ReportOwn(e.ExceptionObject as Exception);
private static void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
=> ReportOwn(e.Exception);
private static void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
=> ReportOwn(e.Exception);
private static void ReportOwn(Exception? exception)
{
if (exception is not null && IsOwn(exception))
TelemetryReporter.Report(exception);
}
private static bool IsOwn(Exception exception)
{
var current = exception;
for (var depth = 0; current is not null && depth < MaxChainLength; depth++)
{
if (HasOwnFrame(current))
return true;
current = current is AggregateException aggregate && aggregate.InnerExceptions.Count > 0
? aggregate.InnerExceptions[0]
: current.InnerException;
}
return false;
}
private static bool HasOwnFrame(Exception exception)
{
StackFrame[]? frames;
try
{
frames = new StackTrace(exception, false).GetFrames();
}
catch (Exception)
{
return false;
}
if (frames is null)
return false;
for (var index = 0; index < Math.Min(frames.Length, MaxFrames); index++)
{
MethodBase? method;
try
{
method = frames[index].GetMethod();
}
catch (Exception)
{
continue;
}
if (method?.DeclaringType is { } declaringType && ReferenceEquals(declaringType.Assembly, Own))
return true;
}
return false;
}
}
+3 -1
ファイルの表示
@@ -31,8 +31,10 @@ internal static class UTAUUpdateNotifier
};
await new Notifier(Owner, Repository, options).NotifyAsync().ConfigureAwait(false);
}
catch
catch (Exception exception)
{
if (exception is not UpdateCheckException)
UTAUTelemetry.Report(exception);
}
}
+17 -3
ファイルの表示
@@ -4,7 +4,7 @@ using YukkuriMovieMaker.Plugin.Voice;
namespace UTAU;
[PluginDetails(AuthorName = "routersys", ContentId = "")]
[PluginDetails(AuthorName = "routersys", ContentId = "nc501723")]
internal sealed class UTAUVoicePlugin : IVoicePlugin
{
public const string EngineName = "UTAU";
@@ -18,16 +18,30 @@ internal sealed class UTAUVoicePlugin : IVoicePlugin
public bool IsVoicesCached => VoiceBankRepository.IsLoaded;
public Task UpdateVoicesAsync() => Task.Run(VoiceBankRepository.Reload);
public Task UpdateVoicesAsync() => Task.Run(Reload);
static IEnumerable<IVoiceSpeaker> GetVoices()
{
UTAUTelemetry.EnsureStartedOnce();
UTAUUpdateNotifier.EnsureCheckedOnce();
if (!VoiceBankRepository.IsLoaded)
VoiceBankRepository.Reload();
Reload();
foreach (var bank in VoiceBankRepository.Banks)
yield return new UTAUVoiceSpeaker(bank);
}
static void Reload()
{
try
{
VoiceBankRepository.Reload();
}
catch (Exception exception)
{
UTAUTelemetry.Report(exception);
throw;
}
}
}
+6 -8
ファイルの表示
@@ -135,19 +135,17 @@ internal sealed class UTAUVoicePronounce : UndoRedoable, IVoicePronounce
static string BuildImportMessage(UstImportResult imported, UstPhraseRange range)
{
var parts = new List<string>
{
string.Format(Texts.UstImportedFormat, imported.Notes.Count),
string.Format(Texts.UstPhraseTotalFormat, imported.TotalPhrases),
};
var parts = new List<string> { string.Format(Texts.UstImportedFormat, imported.Notes.Count) };
if (!range.CoversEverything)
if (range.CoversEverything)
parts.Add(string.Format(Texts.UstPhraseTotalFormat, imported.TotalPhrases));
else
{
var taken = range.Count > 0 ? range.Count : imported.TotalPhrases - range.Start + 1;
parts.Add(string.Format(Texts.UstPhraseRangeFormat, range.Start, Math.Max(taken, 0)));
parts.Add(string.Format(Texts.UstPhraseRangeFormat, range.Start, Math.Max(taken, 0), imported.TotalPhrases));
}
if (imported.StartTicks > 0)
if (!range.CoversEverything && imported.StartTicks > 0)
parts.Add(string.Format(Texts.UstPhraseOffsetFormat, imported.StartTicks));
if (imported.TrimmedRestTicks > 0)
parts.Add(string.Format(Texts.UstRestTrimmedFormat, imported.TrimmedRestTicks));
+14 -3
ファイルの表示
@@ -2,7 +2,6 @@ using UTAU.Models;
using UTAU.Notes;
using UTAU.Phonemes;
using UTAU.Synthesis;
using WorldNet;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Plugin.Voice;
@@ -49,6 +48,19 @@ internal sealed class UTAUVoiceSpeaker(VoiceBank bank) : IVoiceSpeaker
=> currentParameter is UTAUVoiceParameter ? currentParameter : CreateVoiceParameter();
public async Task<IVoicePronounce?> CreateVoiceAsync(string text, IVoicePronounce? pronounce, IVoiceParameter? parameter, string filePath)
{
try
{
return await CreateAsync(text, pronounce, parameter, filePath).ConfigureAwait(false);
}
catch (Exception exception) when (exception is not InvalidOperationException)
{
UTAUTelemetry.Report(exception);
throw;
}
}
async Task<IVoicePronounce?> CreateAsync(string text, IVoicePronounce? pronounce, IVoiceParameter? parameter, string filePath)
{
var param = parameter as UTAUVoiceParameter ?? new UTAUVoiceParameter();
var isUst = UstSource.TryGetPath(text, out var ustPath);
@@ -90,9 +102,8 @@ internal sealed class UTAUVoiceSpeaker(VoiceBank bank) : IVoiceSpeaker
parameter.Breathiness,
parameter.Brightness);
using var arena = new WorldArena();
var renderer = new UtauRenderer(settings, BuildCurves(pronounce, tempoMap), AnalysisCache.Shared, SegmentCache.Shared);
var result = renderer.Render(units, arena);
var result = renderer.Render(units);
if (result.Samples.Length == 0)
throw new InvalidOperationException(unresolved.Length > 0 ? unresolved : Texts.NoRenderableNoteMessage);
+37
ファイルの表示
@@ -0,0 +1,37 @@
using System.Windows.Input;
using UTAU.Notes;
using YukkuriMovieMaker.Commons;
namespace UTAU.ViewModels;
internal sealed class LyricsBulkEditViewModel : Bindable
{
readonly string original;
string text;
public LyricsBulkEditViewModel(string lyrics, int noteCount)
{
original = lyrics ?? string.Empty;
text = original;
NoteCount = noteCount;
ResetCommand = new ActionCommand(_ => Text != original, _ => Text = original);
}
public string Text
{
get => text;
set => Set(ref text, value ?? string.Empty, nameof(Text), nameof(LyricCount), nameof(CountText), nameof(HasMismatch));
}
public int NoteCount { get; }
public int LyricCount => LyricSplitter.Split(text).Count;
public string CountText => string.Format(Texts.LyricCountFormat, LyricCount, NoteCount);
public bool HasMismatch => LyricCount != NoteCount;
public ICommand ResetCommand { get; }
public IReadOnlyList<string> Lyrics => LyricSplitter.Split(text);
}
+334 -9
ファイルの表示
@@ -32,6 +32,9 @@ internal sealed class NoteEditorViewModel : Bindable, IDisposable
public const double MinimumFitQuarterNoteWidth = 24.0;
public const double MinimumFitPixelsPerTick = MinimumFitQuarterNoteWidth / TimeBase.TicksPerQuarterNote;
public const double MinimumFitSemitoneHeight = 10.0;
public const int OctaveSemitones = 12;
static readonly List<UTAUNote> copiedNotes = [];
readonly UTAUVoicePronounce pronounce;
readonly Dispatcher dispatcher;
@@ -51,6 +54,10 @@ internal sealed class NoteEditorViewModel : Bindable, IDisposable
Rect selectionBox;
bool isSelectionBoxVisible;
bool isBatching;
bool isDetached;
bool isMutatingSource;
bool layoutPending;
bool isDisposed;
ObservableCollection<PitchPoint>? observedPitchPoints;
PitchPoint? selectedPitchPoint;
PointCollection pitchCurve = [];
@@ -84,6 +91,7 @@ internal sealed class NoteEditorViewModel : Bindable, IDisposable
source = pronounce.Notes;
Notes = [.. source.Select(x => new NoteViewModel(x, this))];
Notes.CollectionChanged += OnNotesChanged;
source.CollectionChanged += OnSourceChanged;
ZoomInCommand = new ActionCommand(_ => pixelsPerTick < MaximumPixelsPerTick, _ => ZoomHorizontally(ZoomStep));
ZoomOutCommand = new ActionCommand(_ => pixelsPerTick > MinimumPixelsPerTick, _ => ZoomHorizontally(1.0 / ZoomStep));
ZoomVerticalInCommand = new ActionCommand(_ => semitoneHeight < MaximumSemitoneHeight, _ => ZoomVertically(ZoomStep));
@@ -91,6 +99,16 @@ internal sealed class NoteEditorViewModel : Bindable, IDisposable
InsertRestCommand = new ActionCommand(_ => selectedNotes.Count > 0, _ => InsertRest());
RemoveNoteCommand = new ActionCommand(_ => selectedNotes.Count > 0 && Notes.Count > selectedNotes.Count, _ => RemoveSelected());
SelectAllCommand = new ActionCommand(_ => Notes.Count > 0, _ => SelectAll());
OctaveUpCommand = new ActionCommand(_ => selectedNotes.Count > 0, _ => Transpose(OctaveSemitones));
OctaveDownCommand = new ActionCommand(_ => selectedNotes.Count > 0, _ => Transpose(-OctaveSemitones));
QuantizeLengthCommand = new ActionCommand(_ => selectedNotes.Count > 0 && !SnapDivision.IsFree, _ => QuantizeLength());
ResetVibratoCommand = new ActionCommand(_ => selectedNotes.Count > 0, _ => ResetVibrato());
ResetTimingCommand = new ActionCommand(_ => selectedNotes.Count > 0, _ => ResetTiming());
ResetNoteCommand = new ActionCommand(_ => selectedNotes.Count > 0, _ => ResetNote());
CopyNotesCommand = new ActionCommand(_ => selectedNotes.Count > 0, _ => CopyNotes());
PasteNotesCommand = new ActionCommand(_ => copiedNotes.Count > 0, _ => PasteNotes());
EditLyricsCommand = new ActionCommand(_ => selectedNotes.Count > 0, _ => LyricsEditRequested?.Invoke(this, EventArgs.Empty));
DetachCommand = new ActionCommand(_ => CanDetach, _ => DetachRequested?.Invoke(this, EventArgs.Empty));
AddPitchPointCommand = new ActionCommand(_ => SelectedNote is not null, _ => AddPitchPoint());
RemovePitchPointCommand = new ActionCommand(_ => SelectedPitchPoint is not null, _ => RemoveSelectedPitchPoint());
ResetPitchCommand = new ActionCommand(_ => SelectedNote is not null, _ => ResetPitch());
@@ -119,6 +137,42 @@ internal sealed class NoteEditorViewModel : Bindable, IDisposable
public ICommand SelectAllCommand { get; }
public ICommand OctaveUpCommand { get; }
public ICommand OctaveDownCommand { get; }
public ICommand QuantizeLengthCommand { get; }
public ICommand ResetVibratoCommand { get; }
public ICommand ResetTimingCommand { get; }
public ICommand ResetNoteCommand { get; }
public ICommand CopyNotesCommand { get; }
public ICommand PasteNotesCommand { get; }
public ICommand EditLyricsCommand { get; }
public ICommand DetachCommand { get; }
public bool IsDetached
{
get => isDetached;
set
{
if (Set(ref isDetached, value))
OnPropertyChanged(nameof(CanDetach));
}
}
public bool CanDetach => !isDetached;
public event EventHandler? LyricsEditRequested;
public event EventHandler? DetachRequested;
public string ImportMessage => pronounce.ImportMessage;
public string RenderMessage => pronounce.RenderMessage;
@@ -303,6 +357,7 @@ internal sealed class NoteEditorViewModel : Bindable, IDisposable
public void SetViewport(double left, double width)
{
FlushLayout();
viewportLeft = left;
viewportWidth = width;
if (!MoveWindow())
@@ -320,6 +375,130 @@ internal sealed class NoteEditorViewModel : Bindable, IDisposable
visibleLast = -1;
}
void OnSourceChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (isMutatingSource)
return;
if (dispatcher.CheckAccess())
AcceptSourceChange();
else
dispatcher.BeginInvoke(AcceptSourceChange);
}
void AcceptSourceChange()
{
if (isDisposed || !Resynchronise())
return;
RequestLayout();
}
void RequestLayout()
{
if (layoutPending)
return;
layoutPending = true;
dispatcher.BeginInvoke(FlushLayout, DispatcherPriority.Normal);
}
void MutateSource(Action action)
{
if (isMutatingSource)
{
action();
return;
}
isMutatingSource = true;
try
{
action();
}
finally
{
isMutatingSource = false;
if (Resynchronise())
layoutPending = true;
FlushLayout();
}
}
bool Resynchronise()
{
if (!SyncNotes())
return false;
RepairSelection();
return true;
}
public void FlushLayout()
{
if (isDisposed || !layoutPending)
return;
layoutPending = false;
InvalidateLayout();
}
bool SyncNotes()
{
if (IsSynchronised())
return false;
var orphans = new Dictionary<UTAUNote, NoteViewModel>(Notes.Count);
foreach (var note in Notes)
orphans.TryAdd(note.Note, note);
var rebuilt = new List<NoteViewModel>(source.Count);
foreach (var note in source)
rebuilt.Add(orphans.Remove(note, out var viewModel) ? viewModel : new NoteViewModel(note, this));
for (var index = VisibleNotes.Count - 1; index >= 0; index--)
{
if (orphans.ContainsKey(VisibleNotes[index].Note))
VisibleNotes.RemoveAt(index);
}
foreach (var orphan in orphans.Values)
{
selectedNotes.Remove(orphan);
orphan.IsSelected = false;
orphan.IsPrimary = false;
orphan.Dispose();
}
Notes.Clear();
foreach (var viewModel in rebuilt)
Notes.Add(viewModel);
return true;
}
bool IsSynchronised()
{
if (Notes.Count != source.Count)
return false;
for (var index = 0; index < source.Count; index++)
{
if (!ReferenceEquals(Notes[index].Note, source[index]))
return false;
}
return true;
}
void RepairSelection()
{
if (selectedNote is null ? selectedNotes.Count == 0 : selectedNotes.Contains(selectedNote))
return;
SetPrimary(selectedNotes.LastOrDefault());
}
void ResetWindow()
{
windowStartTicks = int.MaxValue;
@@ -967,8 +1146,14 @@ internal sealed class NoteEditorViewModel : Bindable, IDisposable
public void Dispose()
{
if (isDisposed)
return;
isDisposed = true;
pronounce.PropertyChanged -= OnPronouncePropertyChanged;
ObservePitchPoints(null);
layoutPending = false;
source.CollectionChanged -= OnSourceChanged;
Notes.CollectionChanged -= OnNotesChanged;
VisibleNotes.Clear();
selectedNotes.Clear();
@@ -1242,9 +1427,7 @@ internal sealed class NoteEditorViewModel : Bindable, IDisposable
Tone = selectedNote?.Note.Tone ?? MusicalTone.MiddleC.NoteNumber,
LengthTicks = SnapDivision.IsFree ? UTAUNote.DefaultLengthTicks : SnapDivision.Ticks,
};
source.Insert(index + 1, rest);
Notes.Insert(index + 1, new NoteViewModel(rest, this));
InvalidateLayout();
MutateSource(() => source.Insert(index + 1, rest));
}
void RemoveSelected()
@@ -1256,15 +1439,157 @@ internal sealed class NoteEditorViewModel : Bindable, IDisposable
var index = Notes.IndexOf(removing[0]);
Select(null);
foreach (var note in removing)
MutateSource(() =>
{
source.Remove(note.Note);
Notes.Remove(note);
note.Dispose();
}
foreach (var note in removing)
source.Remove(note.Note);
});
Select(Notes[Math.Min(index, Notes.Count - 1)]);
InvalidateLayout();
}
public string ReadSelectedLyrics()
=> LyricSplitter.Join(selectedNotes.OrderBy(Notes.IndexOf).Select(x => x.Note.Lyric));
public int ApplyLyrics(IReadOnlyList<string> lyrics)
{
ArgumentNullException.ThrowIfNull(lyrics);
var targets = selectedNotes.OrderBy(Notes.IndexOf).ToArray();
var count = Math.Min(lyrics.Count, targets.Length);
if (count == 0)
return 0;
Batch(() =>
{
for (var index = 0; index < count; index++)
targets[index].Note.Lyric = lyrics[index];
});
return count;
}
void Transpose(int semitones)
{
if (selectedNotes.Count == 0)
return;
var shift = Math.Clamp(
semitones,
-selectedNotes.Min(x => x.Note.Tone),
127 - selectedNotes.Max(x => x.Note.Tone));
if (shift == 0)
return;
Batch(
() =>
{
foreach (var note in selectedNotes)
note.Tone += shift;
},
InvalidateTones);
}
void QuantizeLength()
{
if (selectedNotes.Count == 0 || SnapDivision.IsFree)
return;
Batch(() =>
{
foreach (var note in selectedNotes)
note.LengthTicks = SnapLength(note.Note.LengthTicks);
});
}
void ResetVibrato()
{
if (selectedNotes.Count == 0)
return;
var defaults = new VibratoSettings();
Batch(() =>
{
foreach (var note in selectedNotes)
defaults.CopyTo(note.Note.Vibrato);
});
}
void ResetTiming()
{
if (selectedNotes.Count == 0)
return;
Batch(() =>
{
foreach (var note in selectedNotes)
ResetTiming(note.Note);
});
}
void ResetNote()
{
if (selectedNotes.Count == 0)
return;
var defaults = new VibratoSettings();
Batch(() =>
{
foreach (var note in selectedNotes)
{
var target = note.Note;
target.TempoOverride = UTAUNote.FollowScoreValue;
target.Velocity = UTAUNote.DefaultVelocity;
target.Intensity = UTAUNote.DefaultIntensity;
target.Modulation = UTAUNote.DefaultModulation;
ResetTiming(target);
defaults.CopyTo(target.Vibrato);
for (var index = target.PitchPoints.Count - 1; index >= 0; index--)
target.PitchPoints.RemoveAt(index);
}
});
SelectedPitchPoint = null;
}
static void ResetTiming(UTAUNote note)
{
note.PreutteranceOverride = UTAUNote.FollowOtoValue;
note.OverlapOverride = UTAUNote.FollowOtoValue;
note.StartPointMilliseconds = UTAUNote.DefaultStartPointMilliseconds;
note.FadeInMilliseconds = UTAUNote.DefaultFadeInMilliseconds;
note.FadeOutMilliseconds = UTAUNote.DefaultFadeOutMilliseconds;
}
void CopyNotes()
{
if (selectedNotes.Count == 0)
return;
copiedNotes.Clear();
foreach (var note in selectedNotes.OrderBy(Notes.IndexOf))
copiedNotes.Add(note.Note.Clone());
}
void PasteNotes()
{
if (copiedNotes.Count == 0)
return;
var first = (selectedNotes.Count == 0 ? Notes.Count - 1 : selectedNotes.Max(Notes.IndexOf)) + 1;
MutateSource(() =>
{
var index = first;
foreach (var copied in copiedNotes)
{
source.Insert(index, copied.Clone());
index++;
}
});
ClearSelection();
for (var offset = 0; offset < copiedNotes.Count; offset++)
AddToSelection(Notes[first + offset]);
SetPrimary(Notes[first]);
}
void AddPitchPoint()
+2
ファイルの表示
@@ -78,6 +78,7 @@ internal sealed class UTAUSettingsViewModel : Bindable
}
catch (Exception exception)
{
UTAUTelemetry.Report(exception);
StatusText = exception.Message;
}
finally
@@ -138,6 +139,7 @@ internal sealed class UTAUSettingsViewModel : Bindable
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or System.ComponentModel.Win32Exception)
{
UTAUTelemetry.Report(exception);
StatusText = exception.Message;
}
}
+1
ファイルの表示
@@ -94,6 +94,7 @@ internal sealed class VoiceBankViewModel(VoiceBank bank)
}
catch (Exception exception) when (exception is NotSupportedException or IOException or UriFormatException or ArgumentException)
{
UTAUTelemetry.Report(exception);
return null;
}
}
+45
ファイルの表示
@@ -0,0 +1,45 @@
<UserControl x:Class="UTAU.Views.LyricsBulkEditView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:root="clr-namespace:UTAU"
xmlns:vm="clr-namespace:UTAU.ViewModels"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="560"
d:DataContext="{d:DesignInstance Type={x:Type vm:LyricsBulkEditViewModel}}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="26"/>
</Grid.RowDefinitions>
<TextBox x:Name="LyricBox" Grid.Row="0"
Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}"
AcceptsReturn="True" TextWrapping="Wrap"
VerticalScrollBarVisibility="Auto"
SpellCheck.IsEnabled="False"
ToolTip="{x:Static root:Texts.LyricsBulkEditHint}"/>
<Grid Grid.Row="1">
<TextBlock VerticalAlignment="Center" HorizontalAlignment="Left" Text="{Binding CountText}">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Opacity" Value="0.75"/>
<Style.Triggers>
<DataTrigger Binding="{Binding HasMismatch}" Value="True">
<Setter Property="Opacity" Value="1"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Button Width="88" Height="26" Content="{x:Static root:Texts.ButtonReset}" Command="{Binding ResetCommand}"/>
<Button Width="88" Height="26" Content="{x:Static root:Texts.ButtonCancel}" IsCancel="True"/>
<Button x:Name="ApplyButton" Width="88" Height="26" IsDefault="True"
Content="{x:Static root:Texts.ButtonApply}" Click="Apply_Click"/>
</StackPanel>
</Grid>
</Grid>
</UserControl>
+21
ファイルの表示
@@ -0,0 +1,21 @@
using System.Windows;
using System.Windows.Controls;
namespace UTAU.Views;
public partial class LyricsBulkEditView : UserControl
{
public LyricsBulkEditView()
{
InitializeComponent();
Loaded += (_, _) =>
{
LyricBox.Focus();
LyricBox.SelectAll();
};
}
public event EventHandler? Applied;
void Apply_Click(object sender, RoutedEventArgs e) => Applied?.Invoke(this, EventArgs.Empty);
}
+18
ファイルの表示
@@ -0,0 +1,18 @@
<Window x:Class="UTAU.Views.LyricsBulkEditWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:root="clr-namespace:UTAU"
xmlns:v="clr-namespace:UTAU.Views"
xmlns:vm="clr-namespace:UTAU.ViewModels"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance Type={x:Type vm:LyricsBulkEditViewModel}}"
Title="{x:Static root:Texts.EditLyrics}"
Width="560" Height="320" MinWidth="360" MinHeight="220"
WindowStartupLocation="CenterOwner" ShowInTaskbar="False">
<Window.Style>
<Style TargetType="{x:Type Window}" BasedOn="{StaticResource {x:Type Window}}"/>
</Window.Style>
<v:LyricsBulkEditView x:Name="View"/>
</Window>
+23
ファイルの表示
@@ -0,0 +1,23 @@
using System.Windows;
using UTAU.ViewModels;
namespace UTAU.Views;
public partial class LyricsBulkEditWindow : Window
{
internal LyricsBulkEditWindow(LyricsBulkEditViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel;
ViewModel = viewModel;
View.Applied += OnApplied;
}
internal LyricsBulkEditViewModel ViewModel { get; }
void OnApplied(object? sender, EventArgs e)
{
DialogResult = true;
Close();
}
}
+3 -388
ファイルの表示
@@ -6,402 +6,17 @@
xmlns:root="clr-namespace:UTAU"
xmlns:vm="clr-namespace:UTAU.ViewModels"
xmlns:c="clr-namespace:YukkuriMovieMaker.Controls;assembly=YukkuriMovieMaker.Controls"
xmlns:icons="clr-namespace:YukkuriMovieMaker.Resources.Icons;assembly=YukkuriMovieMaker.Plugin"
xmlns:theme="clr-namespace:YukkuriMovieMaker.Theme;assembly=YukkuriMovieMaker.Plugin"
mc:Ignorable="d"
d:DesignHeight="440" d:DesignWidth="960"
d:DataContext="{d:DesignInstance Type={x:Type vm:NoteEditorViewModel}}">
<UserControl.Resources>
<SolidColorBrush x:Key="AccidentalRowBrush" Color="#26000000"/>
<SolidColorBrush x:Key="AccidentalKeyBrush" Color="#59000000"/>
<SolidColorBrush x:Key="NaturalKeyBrush" Color="#14FFFFFF"/>
<BooleanToVisibilityConverter x:Key="BooleanToVisibility"/>
</UserControl.Resources>
<c:PopupButton Content="{x:Static root:Texts.EditNotes}"
<c:PopupButton x:Name="PopupHost"
Content="{x:Static root:Texts.EditNotes}"
PopupWidth="980"
PopupHeight="480"
ResizeMode="Both"
BeginEdit="PopupButton_BeginEdit"
EndEdit="PopupButton_EndEdit">
<c:PopupButton.PopupContent>
<Grid UseLayoutRounding="False">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="280"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="26"/>
<RowDefinition Height="*"/>
<RowDefinition Height="72"/>
<RowDefinition Height="14"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Grid.ColumnSpan="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0" Orientation="Horizontal">
<Button Width="26" Height="26" Command="{Binding ZoomOutCommand}" ToolTip="{x:Static root:Texts.ZoomOut}"
Content="{DynamicResource {x:Static icons:IconKeys.MagnifyMinusOutline}}"/>
<Button Width="26" Height="26" Command="{Binding ZoomInCommand}" ToolTip="{x:Static root:Texts.ZoomIn}"
Content="{DynamicResource {x:Static icons:IconKeys.MagnifyPlusOutline}}"/>
<Button Width="26" Height="26" Command="{Binding ZoomVerticalOutCommand}" ToolTip="{x:Static root:Texts.ZoomVerticalOut}"
Content="{DynamicResource {x:Static icons:IconKeys.ArrowCollapseVertical}}"/>
<Button Width="26" Height="26" Command="{Binding ZoomVerticalInCommand}" ToolTip="{x:Static root:Texts.ZoomVerticalIn}"
Content="{DynamicResource {x:Static icons:IconKeys.ArrowExpandVertical}}"/>
<Button Width="26" Height="26" Command="{Binding FitCommand}" ToolTip="{x:Static root:Texts.FitToWindow}"
Content="{DynamicResource {x:Static icons:IconKeys.FitToScreenOutline}}"/>
<Button Width="26" Height="26" Command="{Binding InsertRestCommand}" ToolTip="{x:Static root:Texts.InsertRest}"
Content="{DynamicResource {x:Static icons:IconKeys.Plus}}"/>
<Button Width="26" Height="26" Command="{Binding RemoveNoteCommand}" ToolTip="{x:Static root:Texts.RemoveNote}"
Content="{DynamicResource {x:Static icons:IconKeys.Delete}}"/>
<Button Width="26" Height="26" Command="{Binding SelectAllCommand}" ToolTip="{x:Static root:Texts.SelectAllNotes}"
Content="{DynamicResource {x:Static icons:IconKeys.SelectAll}}"/>
<TextBlock Text="{x:Static root:Texts.SnapLabel}" VerticalAlignment="Center" Margin="6,0,3,0"/>
<ComboBox Width="88" Height="26" VerticalContentAlignment="Center"
ItemsSource="{Binding SnapDivisions}"
SelectedItem="{Binding SnapDivision}"
DisplayMemberPath="Name"/>
<TextBlock Text="{x:Static root:Texts.ExpressionLabel}" VerticalAlignment="Center" Margin="12,0,3,0"/>
<ComboBox Width="110" Height="26" VerticalContentAlignment="Center"
ItemsSource="{Binding Expressions}"
SelectedItem="{Binding SelectedExpression}"
DisplayMemberPath="Name"/>
<Button Width="26" Height="26" Command="{Binding ResetExpressionCommand}" ToolTip="{x:Static root:Texts.ResetExpression}"
Content="{DynamicResource {x:Static icons:IconKeys.Restore}}"/>
<TextBlock Text="{Binding SelectionText}" VerticalAlignment="Center" Margin="12,0,0,0" Opacity="0.75"/>
<TextBlock Text="{Binding GuideText}" VerticalAlignment="Center" Margin="12,0,0,0" Opacity="0.75"/>
</StackPanel>
<DockPanel Grid.Column="1">
<TextBlock DockPanel.Dock="Right" Text="{Binding RenderMessage}" VerticalAlignment="Center" Margin="12,0,0,0"
Foreground="{DynamicResource {x:Static theme:YMM4Colors.WarningBannerForegroundBrushKey}}"
TextTrimming="CharacterEllipsis"/>
<TextBlock Text="{Binding ImportMessage}" VerticalAlignment="Center" Margin="12,0,0,0" Opacity="0.75"
TextTrimming="CharacterEllipsis"/>
</DockPanel>
</Grid>
<ScrollViewer x:Name="VerticalScroller" Grid.Row="1" Grid.Column="0"
VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled"
SizeChanged="Scroller_SizeChanged">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="42"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ItemsControl Grid.Column="0" ItemsSource="{Binding Keyboard}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Height="{Binding Height}"
BorderThickness="0,0,1,1"
BorderBrush="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}"
MouseLeftButtonDown="Key_MouseLeftButtonDown"
Cursor="Hand">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Background" Value="{StaticResource NaturalKeyBrush}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsAccidental}" Value="True">
<Setter Property="Background" Value="{StaticResource AccidentalKeyBrush}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" HorizontalAlignment="Right"
Margin="0,0,3,0" FontSize="9" Opacity="0.75" IsHitTestVisible="False"/>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ScrollViewer x:Name="HorizontalScroller" Grid.Column="1"
HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Disabled"
ScrollChanged="HorizontalScroller_ScrollChanged"
SizeChanged="Scroller_SizeChanged">
<Canvas x:Name="RollCanvas"
Width="{Binding CanvasWidth}"
Height="{Binding CanvasHeight}"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Background="Transparent"
ToolTip="{x:Static root:Texts.NoteEditorHint}"
MouseMove="RollCanvas_MouseMove"
MouseLeftButtonDown="RollCanvas_MouseLeftButtonDown"
MouseLeftButtonUp="RollCanvas_MouseLeftButtonUp"
MouseLeave="RollCanvas_MouseLeave"
MouseDown="RollCanvas_MouseDown"
MouseUp="RollCanvas_MouseUp"
PreviewMouseWheel="RollCanvas_PreviewMouseWheel">
<ItemsControl ItemsSource="{Binding Keyboard}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Height="{Binding Height}" Width="{Binding RollWidth}"
BorderThickness="0,0,0,1"
BorderBrush="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}">
<Border.Style>
<Style TargetType="Border">
<Style.Triggers>
<DataTrigger Binding="{Binding IsAccidental}" Value="True">
<Setter Property="Background" Value="{StaticResource AccidentalRowBrush}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ItemsControl ItemsSource="{Binding TimeGridLines}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left" Value="{Binding Left}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Rectangle Width="1" Height="{Binding Height}"
Fill="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}">
<Rectangle.Style>
<Style TargetType="Rectangle">
<Setter Property="Opacity" Value="0.4"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsBar}" Value="True">
<Setter Property="Opacity" Value="0.9"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Rectangle.Style>
</Rectangle>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ItemsControl ItemsSource="{Binding VisibleNotes}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left" Value="{Binding Left}"/>
<Setter Property="Canvas.Top" Value="{Binding Top}"/>
<Setter Property="Panel.ZIndex" Value="1"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Width="{Binding Width}" Height="{Binding Height}"
MouseLeftButtonDown="Note_MouseLeftButtonDown"
ToolTip="{Binding ToneName}">
<Border BorderThickness="1">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
<Setter Property="BorderBrush" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
<Setter Property="Opacity" Value="0.6"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsRest}" Value="True">
<Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}"/>
<Setter Property="BorderBrush" Value="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}"/>
<Setter Property="Opacity" Value="0.35"/>
</DataTrigger>
<DataTrigger Binding="{Binding IsSelected}" Value="True">
<Setter Property="Opacity" Value="1"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
</Border>
<Border IsHitTestVisible="False"
BorderBrush="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"
Visibility="{Binding IsSelected, Converter={StaticResource BooleanToVisibility}}">
<Border.Style>
<Style TargetType="Border">
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Opacity" Value="0.55"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsPrimary}" Value="True">
<Setter Property="BorderThickness" Value="2"/>
<Setter Property="Opacity" Value="1"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
</Border>
<TextBlock Text="{Binding Display}" FontSize="10" Margin="4,0,0,0"
VerticalAlignment="Center" ClipToBounds="True" IsHitTestVisible="False"
Foreground="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
<Rectangle Width="6" HorizontalAlignment="Right" Fill="Transparent" Cursor="SizeWE"
MouseLeftButtonDown="NoteResize_MouseLeftButtonDown"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Polyline Points="{Binding PitchCurve}" StrokeThickness="1.5" Panel.ZIndex="2"
Stroke="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"
Opacity="0.85"
IsHitTestVisible="False"/>
<ItemsControl ItemsSource="{Binding PitchHandles}" Panel.ZIndex="3">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left" Value="{Binding Left}"/>
<Setter Property="Canvas.Top" Value="{Binding Top}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Rectangle Width="{Binding Size}" Height="{Binding Size}" Cursor="SizeAll"
Fill="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"
Stroke="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"
StrokeThickness="1"
ToolTip="{x:Static root:Texts.PitchHandleHint}"
MouseLeftButtonDown="PitchHandle_MouseLeftButtonDown"
MouseRightButtonDown="PitchHandle_MouseRightButtonDown"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Rectangle Width="1" Height="{Binding CanvasHeight}" Panel.ZIndex="4"
Canvas.Left="{Binding GuideLeft}"
Fill="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"
Opacity="0.6"
IsHitTestVisible="False"
Visibility="{Binding IsGuideVisible, Converter={StaticResource BooleanToVisibility}}"/>
<Rectangle Panel.ZIndex="5" IsHitTestVisible="False" StrokeThickness="1" Opacity="0.35"
Canvas.Left="{Binding SelectionBoxLeft}"
Canvas.Top="{Binding SelectionBoxTop}"
Width="{Binding SelectionBoxWidth}"
Height="{Binding SelectionBoxHeight}"
Fill="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"
Stroke="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"
Visibility="{Binding IsSelectionBoxVisible, Converter={StaticResource BooleanToVisibility}}"/>
</Canvas>
</ScrollViewer>
</Grid>
</ScrollViewer>
<Grid Grid.Row="2" Grid.Column="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="42"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding SelectedExpression.Name}" FontSize="9" Opacity="0.75"
VerticalAlignment="Center" HorizontalAlignment="Right" Margin="0,0,3,0"
TextTrimming="CharacterEllipsis"/>
<ScrollViewer x:Name="StripScroller" Grid.Column="1"
HorizontalAlignment="Left"
HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Disabled">
<Canvas x:Name="StripCanvas"
Width="{Binding CanvasWidth}"
Height="{Binding StripCanvasHeight}"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Background="Transparent"
ToolTip="{x:Static root:Texts.ExpressionHint}"
MouseLeftButtonDown="StripCanvas_MouseLeftButtonDown"
MouseLeftButtonUp="StripCanvas_MouseLeftButtonUp"
MouseMove="StripCanvas_MouseMove"
MouseLeave="StripCanvas_MouseLeave">
<ItemsControl ItemsSource="{Binding TimeGridLines}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left" Value="{Binding Left}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Rectangle Width="1" Height="72" Opacity="0.4"
Fill="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ItemsControl ItemsSource="{Binding ExpressionBars}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left" Value="{Binding Left}"/>
<Setter Property="Canvas.Top" Value="{Binding Top}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Width="{Binding Width}" Height="{Binding Height}"
Background="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"
IsHitTestVisible="False">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Opacity" Value="0.6"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Note.IsSelected}" Value="True">
<Setter Property="Opacity" Value="1"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Polyline Points="{Binding ExpressionCurvePoints}" StrokeThickness="1.5"
Stroke="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"
IsHitTestVisible="False"/>
</Canvas>
</ScrollViewer>
</Grid>
<ScrollBar x:Name="HorizontalBar" Grid.Row="3" Grid.Column="0" Orientation="Horizontal"
Margin="42,0,0,0" Scroll="HorizontalBar_Scroll"/>
<Grid Grid.Row="1" Grid.RowSpan="3" Grid.Column="1" IsEnabled="{Binding HasSelection}">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="26"/>
</Grid.RowDefinitions>
<ScrollViewer Grid.Row="0" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">
<StackPanel>
<c:PropertiesEditor Targets="{Binding SelectedNoteTargets}" IsScrollViewerEnabled="False"/>
<c:PropertiesEditor Target="{Binding SelectedPitchPoint}" IsScrollViewerEnabled="False"/>
</StackPanel>
</ScrollViewer>
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right">
<Button Width="26" Height="26" Command="{Binding AddPitchPointCommand}" ToolTip="{x:Static root:Texts.AddPitchPoint}"
Content="{DynamicResource {x:Static icons:IconKeys.Plus}}"/>
<Button Width="26" Height="26" Command="{Binding RemovePitchPointCommand}" ToolTip="{x:Static root:Texts.RemovePitchPoint}"
Content="{DynamicResource {x:Static icons:IconKeys.Minus}}"/>
<Button Width="26" Height="26" Command="{Binding ResetPitchCommand}" ToolTip="{x:Static root:Texts.ResetPitch}"
Content="{DynamicResource {x:Static icons:IconKeys.Restore}}"/>
</StackPanel>
</Grid>
</Grid>
<ContentControl x:Name="SurfaceHost"/>
</c:PopupButton.PopupContent>
</c:PopupButton>
</UserControl>
+69 -339
ファイルの表示
@@ -1,9 +1,6 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Threading;
using UTAU.Notes;
using UTAU.ViewModels;
using YukkuriMovieMaker.Commons;
@@ -11,27 +8,9 @@ namespace UTAU.Views;
public partial class NoteEditor : UserControl, IPropertyEditorControl
{
enum DragMode
{
None,
Tone,
Length,
PitchHandle,
Expression,
Select,
}
const double WheelScrollStep = 64.0;
DragMode dragMode;
NoteViewModel? dragTarget;
PitchPoint? dragPoint;
Point dragOrigin;
bool dragMoved;
bool isPanning;
Point panOrigin;
double panHorizontalOffset;
double panVerticalOffset;
readonly NoteEditorSurface surface = new();
NoteEditorWindow? detached;
NoteEditorViewModel? attached;
public event EventHandler? BeginEdit;
@@ -40,7 +19,7 @@ public partial class NoteEditor : UserControl, IPropertyEditorControl
public NoteEditor()
{
InitializeComponent();
Loaded += (_, _) => RequestFit();
SurfaceHost.Content = surface;
}
internal UTAUVoicePronounce? Pronounce
@@ -60,332 +39,83 @@ public partial class NoteEditor : UserControl, IPropertyEditorControl
if (d is not NoteEditor editor)
return;
editor.CloseDetached();
editor.Attach(null);
editor.ViewModel?.Dispose();
editor.DataContext = editor.Pronounce is null ? null : new NoteEditorViewModel(editor.Pronounce);
editor.RequestFit();
editor.surface.DataContext = editor.Pronounce is null ? null : new NoteEditorViewModel(editor.Pronounce);
editor.DataContext = editor.surface.DataContext;
editor.Attach(editor.surface.DataContext as NoteEditorViewModel);
editor.surface.RequestFit();
}
NoteEditorViewModel? ViewModel => DataContext as NoteEditorViewModel;
NoteEditorViewModel? ViewModel => surface.DataContext as NoteEditorViewModel;
void RequestFit() => Dispatcher.BeginInvoke(UpdateFit, DispatcherPriority.Loaded);
internal NoteEditorWindow? DetachedWindow => detached;
void UpdateFit()
void Attach(NoteEditorViewModel? viewModel)
{
if (ViewModel is not { } viewModel)
if (attached is not null)
attached.DetachRequested -= OnDetachRequested;
attached = viewModel;
if (attached is not null)
attached.DetachRequested += OnDetachRequested;
}
void OnDetachRequested(object? sender, EventArgs e) => Detach();
internal void Detach()
{
if (detached is not null)
{
detached.Activate();
return;
}
ClosePopup();
SurfaceHost.Content = null;
PopupHost.IsEnabled = false;
if (ViewModel is { } viewModel)
viewModel.IsDetached = true;
detached = new NoteEditorWindow(surface);
if (OwnerWindow() is { } owner)
detached.Owner = owner;
detached.Closed += OnDetachedClosed;
BeginEdit?.Invoke(this, EventArgs.Empty);
detached.Show();
surface.RequestFit();
}
internal void CloseDetached() => detached?.Close();
void OnDetachedClosed(object? sender, EventArgs e)
{
if (detached is null)
return;
viewModel.FitToViewport(HorizontalScroller.ActualWidth, VerticalScroller.ActualHeight);
viewModel.SetViewport(HorizontalScroller.HorizontalOffset, HorizontalScroller.ViewportWidth);
detached.Closed -= OnDetachedClosed;
detached.Release();
detached = null;
SurfaceHost.Content = surface;
PopupHost.IsEnabled = true;
if (ViewModel is { } viewModel)
viewModel.IsDetached = false;
EndEdit?.Invoke(this, EventArgs.Empty);
}
void Scroller_SizeChanged(object sender, SizeChangedEventArgs e) => UpdateFit();
void ClosePopup()
{
if (PopupHost.Template?.FindName("PART_Popup", PopupHost) is Popup popup)
popup.IsOpen = false;
}
static Window? OwnerWindow()
=> Application.Current?.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive)
?? Application.Current?.MainWindow;
void PopupButton_BeginEdit(object sender, EventArgs e) => BeginEdit?.Invoke(this, e);
void PopupButton_EndEdit(object sender, EventArgs e) => EndEdit?.Invoke(this, e);
void HorizontalScroller_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
HorizontalBar.Maximum = Math.Max(e.ExtentWidth - e.ViewportWidth, 0.0);
HorizontalBar.ViewportSize = e.ViewportWidth;
HorizontalBar.LargeChange = e.ViewportWidth;
HorizontalBar.SmallChange = WheelScrollStep;
HorizontalBar.Value = e.HorizontalOffset;
StripScroller.Width = e.ViewportWidth;
StripScroller.ScrollToHorizontalOffset(e.HorizontalOffset);
ViewModel?.SetViewport(e.HorizontalOffset, e.ViewportWidth);
}
void HorizontalBar_Scroll(object sender, ScrollEventArgs e)
=> HorizontalScroller.ScrollToHorizontalOffset(e.NewValue);
void RollCanvas_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
if (ViewModel is not { } viewModel)
return;
var factor = e.Delta > 0 ? NoteEditorViewModel.ZoomStep : 1.0 / NoteEditorViewModel.ZoomStep;
if (Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
{
if (Keyboard.Modifiers.HasFlag(ModifierKeys.Shift))
viewModel.ZoomVertically(factor);
else
viewModel.ZoomHorizontally(factor);
e.Handled = true;
return;
}
if (Keyboard.Modifiers.HasFlag(ModifierKeys.Shift))
{
HorizontalScroller.ScrollToHorizontalOffset(HorizontalScroller.HorizontalOffset - Math.Sign(e.Delta) * WheelScrollStep);
e.Handled = true;
return;
}
VerticalScroller.ScrollToVerticalOffset(VerticalScroller.VerticalOffset - Math.Sign(e.Delta) * WheelScrollStep);
e.Handled = true;
}
void RollCanvas_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton != MouseButton.Middle)
return;
isPanning = true;
panOrigin = e.GetPosition(RollCanvas);
panHorizontalOffset = HorizontalScroller.HorizontalOffset;
panVerticalOffset = VerticalScroller.VerticalOffset;
RollCanvas.CaptureMouse();
e.Handled = true;
}
void RollCanvas_MouseUp(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton != MouseButton.Middle)
return;
EndPan();
e.Handled = true;
}
void RollCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (ViewModel is not { } viewModel)
return;
if (e.ClickCount >= 2)
{
if (viewModel.SelectedNote is not { } selected || selected.IsRest)
return;
var position = e.GetPosition(RollCanvas);
var ticks = viewModel.TicksFromCanvasX(position.X) - selected.StartTicks;
viewModel.AddPitchPointAt(
Math.Clamp(ticks, 0, selected.Note.LengthTicks),
viewModel.CentsFromCanvasY(position.Y, selected.Note.Tone));
e.Handled = true;
return;
}
dragMode = DragMode.Select;
dragOrigin = e.GetPosition(RollCanvas);
viewModel.UpdateSelectionBox(dragOrigin, dragOrigin);
RollCanvas.CaptureMouse();
e.Handled = true;
}
void EndPan()
{
if (!isPanning)
return;
isPanning = false;
RollCanvas.ReleaseMouseCapture();
}
void Key_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (sender is not FrameworkElement { DataContext: KeyRowViewModel row } || ViewModel is not { } viewModel)
return;
viewModel.SelectToneCommand.Execute(row);
e.Handled = true;
}
void Note_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (sender is not FrameworkElement { DataContext: NoteViewModel note } || ViewModel is not { } viewModel)
return;
e.Handled = true;
if (Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
{
viewModel.ToggleSelection(note);
return;
}
if (Keyboard.Modifiers.HasFlag(ModifierKeys.Shift))
{
viewModel.SelectRange(note);
return;
}
viewModel.MakePrimary(note);
BeginDrag(note, DragMode.Tone, e);
}
void NoteResize_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (sender is not FrameworkElement { DataContext: NoteViewModel note } || ViewModel is not { } viewModel)
return;
viewModel.MakePrimary(note);
BeginDrag(note, DragMode.Length, e);
e.Handled = true;
}
void PitchHandle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (sender is not FrameworkElement { DataContext: PitchHandleViewModel handle } || ViewModel is not { } viewModel)
return;
viewModel.SelectedPitchPoint = handle.Point;
dragMode = DragMode.PitchHandle;
dragPoint = handle.Point;
RollCanvas.CaptureMouse();
e.Handled = true;
}
void PitchHandle_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
if (sender is not FrameworkElement { DataContext: PitchHandleViewModel handle } || ViewModel is not { } viewModel)
return;
viewModel.RemovePitchPoint(handle.Point);
e.Handled = true;
}
void BeginDrag(NoteViewModel note, DragMode mode, MouseButtonEventArgs e)
{
dragMode = mode;
dragTarget = note;
dragOrigin = e.GetPosition(RollCanvas);
dragMoved = false;
ViewModel?.BeginTransform();
RollCanvas.CaptureMouse();
}
void RollCanvas_MouseMove(object sender, MouseEventArgs e)
{
if (ViewModel is not { } viewModel)
return;
var position = e.GetPosition(RollCanvas);
viewModel.UpdateGuide(position);
if (isPanning)
{
HorizontalScroller.ScrollToHorizontalOffset(panHorizontalOffset - (position.X - panOrigin.X));
VerticalScroller.ScrollToVerticalOffset(panVerticalOffset - (position.Y - panOrigin.Y));
return;
}
if (dragMode == DragMode.Select)
{
viewModel.UpdateSelectionBox(dragOrigin, position);
return;
}
if (dragMode == DragMode.PitchHandle && dragPoint is not null && viewModel.SelectedNote is { } owner)
{
var ticks = viewModel.TicksFromCanvasX(position.X) - owner.StartTicks;
viewModel.MovePitchPoint(
dragPoint,
Math.Clamp(ticks, 0, owner.Note.LengthTicks),
viewModel.CentsFromCanvasY(position.Y, owner.Note.Tone));
viewModel.ShowPitchGuide(dragPoint);
return;
}
if (dragMode == DragMode.None || dragTarget is null)
return;
if (dragMode == DragMode.Tone)
{
var delta = (int)Math.Round((dragOrigin.Y - position.Y) / viewModel.SemitoneHeight);
dragMoved |= delta != 0;
viewModel.TransformTones(delta);
return;
}
var deltaTicks = viewModel.TicksFromCanvasX(position.X - dragOrigin.X);
dragMoved |= deltaTicks != 0;
viewModel.TransformLengths(deltaTicks);
}
void RollCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) => EndDrag();
void RollCanvas_MouseLeave(object sender, MouseEventArgs e)
{
ViewModel?.HideGuide();
if (e.MiddleButton != MouseButtonState.Pressed)
EndPan();
if (e.LeftButton != MouseButtonState.Pressed)
EndDrag();
}
void EndDrag()
{
if (dragMode is DragMode.None or DragMode.Expression)
return;
if (dragMode == DragMode.Select)
{
dragMode = DragMode.None;
RollCanvas.ReleaseMouseCapture();
ViewModel?.CommitSelectionBox(Keyboard.Modifiers.HasFlag(ModifierKeys.Control));
return;
}
var shouldRelayout = dragMode is DragMode.Tone or DragMode.Length;
var collapseTarget = dragMode == DragMode.Tone && !dragMoved && ViewModel is { SelectedCount: > 1 }
? dragTarget
: null;
dragMode = DragMode.None;
dragTarget = null;
dragPoint = null;
dragMoved = false;
RollCanvas.ReleaseMouseCapture();
ViewModel?.EndTransform();
if (collapseTarget is not null)
ViewModel?.Select(collapseTarget);
if (shouldRelayout)
ViewModel?.InvalidateLayout();
}
void StripCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (ViewModel is null)
return;
dragMode = DragMode.Expression;
StripCanvas.CaptureMouse();
ApplyExpression(e.GetPosition(StripCanvas));
e.Handled = true;
}
void StripCanvas_MouseMove(object sender, MouseEventArgs e)
{
if (dragMode != DragMode.Expression || e.LeftButton != MouseButtonState.Pressed)
return;
ApplyExpression(e.GetPosition(StripCanvas));
}
void StripCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) => EndExpressionDrag();
void StripCanvas_MouseLeave(object sender, MouseEventArgs e)
{
if (e.LeftButton != MouseButtonState.Pressed)
EndExpressionDrag();
}
void EndExpressionDrag()
{
if (dragMode != DragMode.Expression)
return;
dragMode = DragMode.None;
StripCanvas.ReleaseMouseCapture();
ViewModel?.CommitExpression();
}
void ApplyExpression(Point position)
{
if (ViewModel is not { } viewModel)
return;
var ticks = Math.Max(viewModel.TicksFromCanvasX(position.X), 0);
viewModel.SetExpressionAt(ticks, 1.0 - position.Y / NoteEditorViewModel.StripHeight);
}
}
+434
ファイルの表示
@@ -0,0 +1,434 @@
<UserControl x:Class="UTAU.Views.NoteEditorSurface"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:root="clr-namespace:UTAU"
xmlns:vm="clr-namespace:UTAU.ViewModels"
xmlns:v="clr-namespace:UTAU.Views"
xmlns:c="clr-namespace:YukkuriMovieMaker.Controls;assembly=YukkuriMovieMaker.Controls"
xmlns:icons="clr-namespace:YukkuriMovieMaker.Resources.Icons;assembly=YukkuriMovieMaker.Plugin"
xmlns:theme="clr-namespace:YukkuriMovieMaker.Theme;assembly=YukkuriMovieMaker.Plugin"
mc:Ignorable="d"
d:DesignHeight="440" d:DesignWidth="960"
d:DataContext="{d:DesignInstance Type={x:Type vm:NoteEditorViewModel}}">
<UserControl.Resources>
<SolidColorBrush x:Key="AccidentalRowBrush" Color="#26000000"/>
<SolidColorBrush x:Key="AccidentalKeyBrush" Color="#59000000"/>
<SolidColorBrush x:Key="NaturalKeyBrush" Color="#14FFFFFF"/>
<BooleanToVisibilityConverter x:Key="BooleanToVisibility"/>
</UserControl.Resources>
<Grid UseLayoutRounding="False">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="280"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="26"/>
<RowDefinition Height="*"/>
<RowDefinition Height="72"/>
<RowDefinition Height="14"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Grid.ColumnSpan="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0" Orientation="Horizontal">
<Button Width="26" Height="26" Command="{Binding ZoomOutCommand}" ToolTip="{x:Static root:Texts.ZoomOut}"
Content="{DynamicResource {x:Static icons:IconKeys.MagnifyMinusOutline}}"/>
<Button Width="26" Height="26" Command="{Binding ZoomInCommand}" ToolTip="{x:Static root:Texts.ZoomIn}"
Content="{DynamicResource {x:Static icons:IconKeys.MagnifyPlusOutline}}"/>
<Button Width="26" Height="26" Command="{Binding ZoomVerticalOutCommand}" ToolTip="{x:Static root:Texts.ZoomVerticalOut}"
Content="{DynamicResource {x:Static icons:IconKeys.ArrowCollapseVertical}}"/>
<Button Width="26" Height="26" Command="{Binding ZoomVerticalInCommand}" ToolTip="{x:Static root:Texts.ZoomVerticalIn}"
Content="{DynamicResource {x:Static icons:IconKeys.ArrowExpandVertical}}"/>
<Button Width="26" Height="26" Command="{Binding FitCommand}" ToolTip="{x:Static root:Texts.FitToWindow}"
Content="{DynamicResource {x:Static icons:IconKeys.FitToScreenOutline}}"/>
<Button Width="26" Height="26" Command="{Binding InsertRestCommand}" ToolTip="{x:Static root:Texts.InsertRest}"
Content="{DynamicResource {x:Static icons:IconKeys.Plus}}"/>
<Button Width="26" Height="26" Command="{Binding RemoveNoteCommand}" ToolTip="{x:Static root:Texts.RemoveNote}"
Content="{DynamicResource {x:Static icons:IconKeys.Delete}}"/>
<Button Width="26" Height="26" Command="{Binding SelectAllCommand}" ToolTip="{x:Static root:Texts.SelectAllNotes}"
Content="{DynamicResource {x:Static icons:IconKeys.SelectAll}}"/>
<TextBlock Text="{x:Static root:Texts.SnapLabel}" VerticalAlignment="Center" Margin="6,0,3,0"/>
<ComboBox Width="88" Height="26" VerticalContentAlignment="Center"
ItemsSource="{Binding SnapDivisions}"
SelectedItem="{Binding SnapDivision}"
DisplayMemberPath="Name"/>
<TextBlock Text="{x:Static root:Texts.ExpressionLabel}" VerticalAlignment="Center" Margin="12,0,3,0"/>
<ComboBox Width="110" Height="26" VerticalContentAlignment="Center"
ItemsSource="{Binding Expressions}"
SelectedItem="{Binding SelectedExpression}"
DisplayMemberPath="Name"/>
<Button Width="26" Height="26" Command="{Binding ResetExpressionCommand}" ToolTip="{x:Static root:Texts.ResetExpression}"
Content="{DynamicResource {x:Static icons:IconKeys.Restore}}"/>
<TextBlock Text="{Binding SelectionText}" VerticalAlignment="Center" Margin="12,0,0,0" Opacity="0.75"/>
<TextBlock Text="{Binding GuideText}" VerticalAlignment="Center" Margin="12,0,0,0" Opacity="0.75"/>
</StackPanel>
<DockPanel Grid.Column="1">
<v:ScrollingText DockPanel.Dock="Right" Text="{Binding RenderMessage}" VerticalAlignment="Center" Margin="12,0,0,0"
Foreground="{DynamicResource {x:Static theme:YMM4Colors.WarningBannerForegroundBrushKey}}"/>
<v:ScrollingText Text="{Binding ImportMessage}" VerticalAlignment="Center" Margin="12,0,0,0" Opacity="0.75"/>
</DockPanel>
</Grid>
<ScrollViewer x:Name="VerticalScroller" Grid.Row="1" Grid.Column="0"
VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled"
SizeChanged="Scroller_SizeChanged">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="42"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ItemsControl Grid.Column="0" ItemsSource="{Binding Keyboard}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Height="{Binding Height}"
BorderThickness="0,0,1,1"
BorderBrush="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}"
MouseLeftButtonDown="Key_MouseLeftButtonDown"
Cursor="Hand">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Background" Value="{StaticResource NaturalKeyBrush}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsAccidental}" Value="True">
<Setter Property="Background" Value="{StaticResource AccidentalKeyBrush}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" HorizontalAlignment="Right"
Margin="0,0,3,0" FontSize="9" Opacity="0.75" IsHitTestVisible="False"/>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ScrollViewer x:Name="HorizontalScroller" Grid.Column="1"
HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Disabled"
ScrollChanged="HorizontalScroller_ScrollChanged"
SizeChanged="Scroller_SizeChanged">
<Canvas x:Name="RollCanvas"
Width="{Binding CanvasWidth}"
Height="{Binding CanvasHeight}"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Background="Transparent"
ToolTip="{x:Static root:Texts.NoteEditorHint}"
MouseMove="RollCanvas_MouseMove"
MouseLeftButtonDown="RollCanvas_MouseLeftButtonDown"
MouseLeftButtonUp="RollCanvas_MouseLeftButtonUp"
MouseLeave="RollCanvas_MouseLeave"
MouseDown="RollCanvas_MouseDown"
MouseUp="RollCanvas_MouseUp"
PreviewMouseWheel="RollCanvas_PreviewMouseWheel">
<Canvas.ContextMenu>
<ContextMenu>
<MenuItem Header="{x:Static root:Texts.NoteContextCopy}" Command="{Binding CopyNotesCommand}"
Icon="{DynamicResource {x:Static icons:IconKeys.ContentCopy}}"/>
<MenuItem Header="{x:Static root:Texts.NoteContextPaste}" Command="{Binding PasteNotesCommand}"
Icon="{DynamicResource {x:Static icons:IconKeys.ContentPaste}}"/>
<Separator/>
<MenuItem Header="{x:Static root:Texts.SelectAllNotes}" Command="{Binding SelectAllCommand}"
Icon="{DynamicResource {x:Static icons:IconKeys.SelectAll}}"/>
<Separator/>
<MenuItem Header="{x:Static root:Texts.OctaveUp}" Command="{Binding OctaveUpCommand}"
Icon="{DynamicResource {x:Static icons:IconKeys.ArrowUp}}"/>
<MenuItem Header="{x:Static root:Texts.OctaveDown}" Command="{Binding OctaveDownCommand}"
Icon="{DynamicResource {x:Static icons:IconKeys.ArrowDown}}"/>
<MenuItem Header="{x:Static root:Texts.QuantizeLength}" Command="{Binding QuantizeLengthCommand}"
Icon="{DynamicResource {x:Static icons:IconKeys.Magnet}}"/>
<Separator/>
<MenuItem Header="{x:Static root:Texts.ResetGroup}"
Icon="{DynamicResource {x:Static icons:IconKeys.Restore}}">
<MenuItem Header="{x:Static root:Texts.ResetPitch}" Command="{Binding ResetPitchCommand}"
Icon="{DynamicResource {x:Static icons:IconKeys.VectorCurve}}"/>
<MenuItem Header="{x:Static root:Texts.ResetVibrato}" Command="{Binding ResetVibratoCommand}"
Icon="{DynamicResource {x:Static icons:IconKeys.SineWave}}"/>
<MenuItem Header="{x:Static root:Texts.ResetTiming}" Command="{Binding ResetTimingCommand}"
Icon="{DynamicResource {x:Static icons:IconKeys.TimerOutline}}"/>
<MenuItem Header="{x:Static root:Texts.ResetNote}" Command="{Binding ResetNoteCommand}"
Icon="{DynamicResource {x:Static icons:IconKeys.BackupRestore}}"/>
</MenuItem>
<Separator/>
<MenuItem Header="{x:Static root:Texts.EditLyrics}" Command="{Binding EditLyricsCommand}"
Icon="{DynamicResource {x:Static icons:IconKeys.TextBoxEdit}}"/>
<MenuItem Header="{x:Static root:Texts.DetachEditor}" Command="{Binding DetachCommand}"
Icon="{DynamicResource {x:Static icons:IconKeys.OpenInNew}}"
Visibility="{Binding CanDetach, Converter={StaticResource BooleanToVisibility}}"/>
</ContextMenu>
</Canvas.ContextMenu>
<ItemsControl ItemsSource="{Binding Keyboard}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Height="{Binding Height}" Width="{Binding RollWidth}"
BorderThickness="0,0,0,1"
BorderBrush="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}">
<Border.Style>
<Style TargetType="Border">
<Style.Triggers>
<DataTrigger Binding="{Binding IsAccidental}" Value="True">
<Setter Property="Background" Value="{StaticResource AccidentalRowBrush}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ItemsControl ItemsSource="{Binding TimeGridLines}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left" Value="{Binding Left}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Rectangle Width="1" Height="{Binding Height}"
Fill="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}">
<Rectangle.Style>
<Style TargetType="Rectangle">
<Setter Property="Opacity" Value="0.4"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsBar}" Value="True">
<Setter Property="Opacity" Value="0.9"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Rectangle.Style>
</Rectangle>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ItemsControl ItemsSource="{Binding VisibleNotes}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left" Value="{Binding Left}"/>
<Setter Property="Canvas.Top" Value="{Binding Top}"/>
<Setter Property="Panel.ZIndex" Value="1"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Width="{Binding Width}" Height="{Binding Height}"
MouseLeftButtonDown="Note_MouseLeftButtonDown"
MouseRightButtonDown="Note_MouseRightButtonDown"
ToolTip="{Binding ToneName}">
<Border BorderThickness="1">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
<Setter Property="BorderBrush" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
<Setter Property="Opacity" Value="0.6"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsRest}" Value="True">
<Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}"/>
<Setter Property="BorderBrush" Value="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}"/>
<Setter Property="Opacity" Value="0.35"/>
</DataTrigger>
<DataTrigger Binding="{Binding IsSelected}" Value="True">
<Setter Property="Opacity" Value="1"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
</Border>
<Border IsHitTestVisible="False"
BorderBrush="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"
Visibility="{Binding IsSelected, Converter={StaticResource BooleanToVisibility}}">
<Border.Style>
<Style TargetType="Border">
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Opacity" Value="0.55"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsPrimary}" Value="True">
<Setter Property="BorderThickness" Value="2"/>
<Setter Property="Opacity" Value="1"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
</Border>
<TextBlock Text="{Binding Display}" FontSize="10" Margin="4,0,0,0"
VerticalAlignment="Center" ClipToBounds="True" IsHitTestVisible="False"
Foreground="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
<Rectangle Width="6" HorizontalAlignment="Right" Fill="Transparent" Cursor="SizeWE"
MouseLeftButtonDown="NoteResize_MouseLeftButtonDown"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Polyline Points="{Binding PitchCurve}" StrokeThickness="1.5" Panel.ZIndex="2"
Stroke="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"
Opacity="0.85"
IsHitTestVisible="False"/>
<ItemsControl ItemsSource="{Binding PitchHandles}" Panel.ZIndex="3">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left" Value="{Binding Left}"/>
<Setter Property="Canvas.Top" Value="{Binding Top}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Rectangle Width="{Binding Size}" Height="{Binding Size}" Cursor="SizeAll"
Fill="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"
Stroke="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"
StrokeThickness="1"
ToolTip="{x:Static root:Texts.PitchHandleHint}"
MouseLeftButtonDown="PitchHandle_MouseLeftButtonDown"
MouseRightButtonDown="PitchHandle_MouseRightButtonDown"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Rectangle Width="1" Height="{Binding CanvasHeight}" Panel.ZIndex="4"
Canvas.Left="{Binding GuideLeft}"
Fill="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"
Opacity="0.6"
IsHitTestVisible="False"
Visibility="{Binding IsGuideVisible, Converter={StaticResource BooleanToVisibility}}"/>
<Rectangle Panel.ZIndex="5" IsHitTestVisible="False" StrokeThickness="1" Opacity="0.35"
Canvas.Left="{Binding SelectionBoxLeft}"
Canvas.Top="{Binding SelectionBoxTop}"
Width="{Binding SelectionBoxWidth}"
Height="{Binding SelectionBoxHeight}"
Fill="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"
Stroke="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"
Visibility="{Binding IsSelectionBoxVisible, Converter={StaticResource BooleanToVisibility}}"/>
</Canvas>
</ScrollViewer>
</Grid>
</ScrollViewer>
<Grid Grid.Row="2" Grid.Column="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="42"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding SelectedExpression.Name}" FontSize="9" Opacity="0.75"
VerticalAlignment="Center" HorizontalAlignment="Right" Margin="0,0,3,0"
TextTrimming="CharacterEllipsis"/>
<ScrollViewer x:Name="StripScroller" Grid.Column="1"
HorizontalAlignment="Left"
HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Disabled">
<Canvas x:Name="StripCanvas"
Width="{Binding CanvasWidth}"
Height="{Binding StripCanvasHeight}"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Background="Transparent"
ToolTip="{x:Static root:Texts.ExpressionHint}"
MouseLeftButtonDown="StripCanvas_MouseLeftButtonDown"
MouseLeftButtonUp="StripCanvas_MouseLeftButtonUp"
MouseMove="StripCanvas_MouseMove"
MouseLeave="StripCanvas_MouseLeave">
<ItemsControl ItemsSource="{Binding TimeGridLines}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left" Value="{Binding Left}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Rectangle Width="1" Height="72" Opacity="0.4"
Fill="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ItemsControl ItemsSource="{Binding ExpressionBars}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left" Value="{Binding Left}"/>
<Setter Property="Canvas.Top" Value="{Binding Top}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Width="{Binding Width}" Height="{Binding Height}"
Background="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"
IsHitTestVisible="False">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Opacity" Value="0.6"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Note.IsSelected}" Value="True">
<Setter Property="Opacity" Value="1"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Polyline Points="{Binding ExpressionCurvePoints}" StrokeThickness="1.5"
Stroke="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"
IsHitTestVisible="False"/>
</Canvas>
</ScrollViewer>
</Grid>
<ScrollBar x:Name="HorizontalBar" Grid.Row="3" Grid.Column="0" Orientation="Horizontal"
Margin="42,0,0,0" Scroll="HorizontalBar_Scroll"/>
<Grid Grid.Row="1" Grid.RowSpan="3" Grid.Column="1" IsEnabled="{Binding HasSelection}">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="26"/>
</Grid.RowDefinitions>
<ScrollViewer Grid.Row="0" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">
<StackPanel>
<c:PropertiesEditor Targets="{Binding SelectedNoteTargets}" IsScrollViewerEnabled="False"/>
<c:PropertiesEditor Target="{Binding SelectedPitchPoint}" IsScrollViewerEnabled="False"/>
</StackPanel>
</ScrollViewer>
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right">
<Button Width="26" Height="26" Command="{Binding AddPitchPointCommand}" ToolTip="{x:Static root:Texts.AddPitchPoint}"
Content="{DynamicResource {x:Static icons:IconKeys.Plus}}"/>
<Button Width="26" Height="26" Command="{Binding RemovePitchPointCommand}" ToolTip="{x:Static root:Texts.RemovePitchPoint}"
Content="{DynamicResource {x:Static icons:IconKeys.Minus}}"/>
<Button Width="26" Height="26" Command="{Binding ResetPitchCommand}" ToolTip="{x:Static root:Texts.ResetPitch}"
Content="{DynamicResource {x:Static icons:IconKeys.Restore}}"/>
</StackPanel>
</Grid>
</Grid>
</UserControl>
+402
ファイルの表示
@@ -0,0 +1,402 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Threading;
using UTAU.Notes;
using UTAU.ViewModels;
namespace UTAU.Views;
public partial class NoteEditorSurface : UserControl
{
enum DragMode
{
None,
Tone,
Length,
PitchHandle,
Expression,
Select,
}
const double WheelScrollStep = 64.0;
DragMode dragMode;
NoteViewModel? dragTarget;
PitchPoint? dragPoint;
Point dragOrigin;
bool dragMoved;
bool isPanning;
Point panOrigin;
double panHorizontalOffset;
double panVerticalOffset;
NoteEditorViewModel? attached;
public NoteEditorSurface()
{
InitializeComponent();
Loaded += (_, _) => RequestFit();
DataContextChanged += OnDataContextChanged;
OnDataContextChanged(this, default);
}
void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (attached is not null)
attached.LyricsEditRequested -= OnLyricsEditRequested;
attached = DataContext as NoteEditorViewModel;
if (attached is not null)
attached.LyricsEditRequested += OnLyricsEditRequested;
if (RollCanvas.ContextMenu is { } menu)
menu.DataContext = DataContext;
}
void OnLyricsEditRequested(object? sender, EventArgs e)
{
if (ViewModel is not { } viewModel || viewModel.SelectedCount == 0)
return;
var dialog = new LyricsBulkEditWindow(new LyricsBulkEditViewModel(viewModel.ReadSelectedLyrics(), viewModel.SelectedCount));
if (OwnerWindow() is { } owner && !ReferenceEquals(owner, dialog))
dialog.Owner = owner;
if (dialog.ShowDialog() == true)
viewModel.ApplyLyrics(dialog.ViewModel.Lyrics);
}
static Window? OwnerWindow()
=> Application.Current?.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive)
?? Application.Current?.MainWindow;
NoteEditorViewModel? ViewModel => DataContext as NoteEditorViewModel;
internal void RequestFit() => Dispatcher.BeginInvoke(UpdateFit, DispatcherPriority.Loaded);
void UpdateFit()
{
if (ViewModel is not { } viewModel)
return;
viewModel.FitToViewport(HorizontalScroller.ActualWidth, VerticalScroller.ActualHeight);
viewModel.SetViewport(HorizontalScroller.HorizontalOffset, HorizontalScroller.ViewportWidth);
}
void Scroller_SizeChanged(object sender, SizeChangedEventArgs e) => UpdateFit();
void HorizontalScroller_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
HorizontalBar.Maximum = Math.Max(e.ExtentWidth - e.ViewportWidth, 0.0);
HorizontalBar.ViewportSize = e.ViewportWidth;
HorizontalBar.LargeChange = e.ViewportWidth;
HorizontalBar.SmallChange = WheelScrollStep;
HorizontalBar.Value = e.HorizontalOffset;
StripScroller.Width = e.ViewportWidth;
StripScroller.ScrollToHorizontalOffset(e.HorizontalOffset);
ViewModel?.SetViewport(e.HorizontalOffset, e.ViewportWidth);
}
void HorizontalBar_Scroll(object sender, ScrollEventArgs e)
=> HorizontalScroller.ScrollToHorizontalOffset(e.NewValue);
void RollCanvas_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
if (ViewModel is not { } viewModel)
return;
var factor = e.Delta > 0 ? NoteEditorViewModel.ZoomStep : 1.0 / NoteEditorViewModel.ZoomStep;
if (Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
{
if (Keyboard.Modifiers.HasFlag(ModifierKeys.Shift))
viewModel.ZoomVertically(factor);
else
viewModel.ZoomHorizontally(factor);
e.Handled = true;
return;
}
if (Keyboard.Modifiers.HasFlag(ModifierKeys.Shift))
{
HorizontalScroller.ScrollToHorizontalOffset(HorizontalScroller.HorizontalOffset - Math.Sign(e.Delta) * WheelScrollStep);
e.Handled = true;
return;
}
VerticalScroller.ScrollToVerticalOffset(VerticalScroller.VerticalOffset - Math.Sign(e.Delta) * WheelScrollStep);
e.Handled = true;
}
void RollCanvas_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton != MouseButton.Middle)
return;
isPanning = true;
panOrigin = e.GetPosition(RollCanvas);
panHorizontalOffset = HorizontalScroller.HorizontalOffset;
panVerticalOffset = VerticalScroller.VerticalOffset;
RollCanvas.CaptureMouse();
e.Handled = true;
}
void RollCanvas_MouseUp(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton != MouseButton.Middle)
return;
EndPan();
e.Handled = true;
}
void RollCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (ViewModel is not { } viewModel)
return;
if (e.ClickCount >= 2)
{
if (viewModel.SelectedNote is not { } selected || selected.IsRest)
return;
var position = e.GetPosition(RollCanvas);
var ticks = viewModel.TicksFromCanvasX(position.X) - selected.StartTicks;
viewModel.AddPitchPointAt(
Math.Clamp(ticks, 0, selected.Note.LengthTicks),
viewModel.CentsFromCanvasY(position.Y, selected.Note.Tone));
e.Handled = true;
return;
}
dragMode = DragMode.Select;
dragOrigin = e.GetPosition(RollCanvas);
viewModel.UpdateSelectionBox(dragOrigin, dragOrigin);
RollCanvas.CaptureMouse();
e.Handled = true;
}
void EndPan()
{
if (!isPanning)
return;
isPanning = false;
RollCanvas.ReleaseMouseCapture();
}
void Key_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (sender is not FrameworkElement { DataContext: KeyRowViewModel row } || ViewModel is not { } viewModel)
return;
viewModel.SelectToneCommand.Execute(row);
e.Handled = true;
}
void Note_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (sender is not FrameworkElement { DataContext: NoteViewModel note } || ViewModel is not { } viewModel)
return;
e.Handled = true;
if (Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
{
viewModel.ToggleSelection(note);
return;
}
if (Keyboard.Modifiers.HasFlag(ModifierKeys.Shift))
{
viewModel.SelectRange(note);
return;
}
viewModel.MakePrimary(note);
BeginDrag(note, DragMode.Tone, e);
}
void Note_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
if (sender is not FrameworkElement { DataContext: NoteViewModel note } || ViewModel is not { } viewModel)
return;
if (!note.IsSelected)
viewModel.Select(note);
}
void NoteResize_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (sender is not FrameworkElement { DataContext: NoteViewModel note } || ViewModel is not { } viewModel)
return;
viewModel.MakePrimary(note);
BeginDrag(note, DragMode.Length, e);
e.Handled = true;
}
void PitchHandle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (sender is not FrameworkElement { DataContext: PitchHandleViewModel handle } || ViewModel is not { } viewModel)
return;
viewModel.SelectedPitchPoint = handle.Point;
dragMode = DragMode.PitchHandle;
dragPoint = handle.Point;
RollCanvas.CaptureMouse();
e.Handled = true;
}
void PitchHandle_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
if (sender is not FrameworkElement { DataContext: PitchHandleViewModel handle } || ViewModel is not { } viewModel)
return;
viewModel.RemovePitchPoint(handle.Point);
e.Handled = true;
}
void BeginDrag(NoteViewModel note, DragMode mode, MouseButtonEventArgs e)
{
dragMode = mode;
dragTarget = note;
dragOrigin = e.GetPosition(RollCanvas);
dragMoved = false;
ViewModel?.BeginTransform();
RollCanvas.CaptureMouse();
}
void RollCanvas_MouseMove(object sender, MouseEventArgs e)
{
if (ViewModel is not { } viewModel)
return;
var position = e.GetPosition(RollCanvas);
viewModel.UpdateGuide(position);
if (isPanning)
{
HorizontalScroller.ScrollToHorizontalOffset(panHorizontalOffset - (position.X - panOrigin.X));
VerticalScroller.ScrollToVerticalOffset(panVerticalOffset - (position.Y - panOrigin.Y));
return;
}
if (dragMode == DragMode.Select)
{
viewModel.UpdateSelectionBox(dragOrigin, position);
return;
}
if (dragMode == DragMode.PitchHandle && dragPoint is not null && viewModel.SelectedNote is { } owner)
{
var ticks = viewModel.TicksFromCanvasX(position.X) - owner.StartTicks;
viewModel.MovePitchPoint(
dragPoint,
Math.Clamp(ticks, 0, owner.Note.LengthTicks),
viewModel.CentsFromCanvasY(position.Y, owner.Note.Tone));
viewModel.ShowPitchGuide(dragPoint);
return;
}
if (dragMode == DragMode.None || dragTarget is null)
return;
if (dragMode == DragMode.Tone)
{
var delta = (int)Math.Round((dragOrigin.Y - position.Y) / viewModel.SemitoneHeight);
dragMoved |= delta != 0;
viewModel.TransformTones(delta);
return;
}
var deltaTicks = viewModel.TicksFromCanvasX(position.X - dragOrigin.X);
dragMoved |= deltaTicks != 0;
viewModel.TransformLengths(deltaTicks);
}
void RollCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) => EndDrag();
void RollCanvas_MouseLeave(object sender, MouseEventArgs e)
{
ViewModel?.HideGuide();
if (e.MiddleButton != MouseButtonState.Pressed)
EndPan();
if (e.LeftButton != MouseButtonState.Pressed)
EndDrag();
}
void EndDrag()
{
if (dragMode is DragMode.None or DragMode.Expression)
return;
if (dragMode == DragMode.Select)
{
dragMode = DragMode.None;
RollCanvas.ReleaseMouseCapture();
ViewModel?.CommitSelectionBox(Keyboard.Modifiers.HasFlag(ModifierKeys.Control));
return;
}
var shouldRelayout = dragMode is DragMode.Tone or DragMode.Length;
var collapseTarget = dragMode == DragMode.Tone && !dragMoved && ViewModel is { SelectedCount: > 1 }
? dragTarget
: null;
dragMode = DragMode.None;
dragTarget = null;
dragPoint = null;
dragMoved = false;
RollCanvas.ReleaseMouseCapture();
ViewModel?.EndTransform();
if (collapseTarget is not null)
ViewModel?.Select(collapseTarget);
if (shouldRelayout)
ViewModel?.InvalidateLayout();
}
void StripCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (ViewModel is null)
return;
dragMode = DragMode.Expression;
StripCanvas.CaptureMouse();
ApplyExpression(e.GetPosition(StripCanvas));
e.Handled = true;
}
void StripCanvas_MouseMove(object sender, MouseEventArgs e)
{
if (dragMode != DragMode.Expression || e.LeftButton != MouseButtonState.Pressed)
return;
ApplyExpression(e.GetPosition(StripCanvas));
}
void StripCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) => EndExpressionDrag();
void StripCanvas_MouseLeave(object sender, MouseEventArgs e)
{
if (e.LeftButton != MouseButtonState.Pressed)
EndExpressionDrag();
}
void EndExpressionDrag()
{
if (dragMode != DragMode.Expression)
return;
dragMode = DragMode.None;
StripCanvas.ReleaseMouseCapture();
ViewModel?.CommitExpression();
}
void ApplyExpression(Point position)
{
if (ViewModel is not { } viewModel)
return;
var ticks = Math.Max(viewModel.TicksFromCanvasX(position.X), 0);
viewModel.SetExpressionAt(ticks, 1.0 - position.Y / NoteEditorViewModel.StripHeight);
}
}
+17
ファイルの表示
@@ -0,0 +1,17 @@
<Window x:Class="UTAU.Views.NoteEditorWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:root="clr-namespace:UTAU"
xmlns:vm="clr-namespace:UTAU.ViewModels"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance Type={x:Type vm:NoteEditorViewModel}}"
Title="{x:Static root:Texts.EditNotes}"
Width="1180" Height="640" MinWidth="640" MinHeight="360"
WindowStartupLocation="CenterOwner" ShowInTaskbar="False">
<Window.Style>
<Style TargetType="{x:Type Window}" BasedOn="{StaticResource {x:Type Window}}"/>
</Window.Style>
<ContentControl x:Name="SurfaceHost"/>
</Window>
+21
ファイルの表示
@@ -0,0 +1,21 @@
using System.Windows;
namespace UTAU.Views;
public partial class NoteEditorWindow : Window
{
internal NoteEditorWindow(NoteEditorSurface surface)
{
InitializeComponent();
SurfaceHost.Content = surface;
}
internal NoteEditorSurface? Surface => SurfaceHost.Content as NoteEditorSurface;
internal NoteEditorSurface? Release()
{
var surface = SurfaceHost.Content as NoteEditorSurface;
SurfaceHost.Content = null;
return surface;
}
}
+103
ファイルの表示
@@ -0,0 +1,103 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
namespace UTAU.Views;
internal sealed class ScrollingText : Control
{
public const double PixelsPerSecond = 40.0;
public const double HoldSeconds = 2.0;
readonly TextBlock block = new();
readonly TranslateTransform offset = new();
public ScrollingText()
{
block.RenderTransform = offset;
AddVisualChild(block);
AddLogicalChild(block);
ClipToBounds = true;
SizeChanged += (_, _) => Restart();
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
nameof(Text),
typeof(string),
typeof(ScrollingText),
new PropertyMetadata(string.Empty, OnTextChanged));
public string Text
{
get => (string)GetValue(TextProperty);
set => SetValue(TextProperty, value);
}
public double HiddenWidth => Math.Max(block.DesiredSize.Width - ActualWidth, 0.0);
public bool IsScrolling { get; private set; }
protected override int VisualChildrenCount => 1;
protected override Visual GetVisualChild(int index) => block;
static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is not ScrollingText control)
return;
control.block.Text = e.NewValue as string ?? string.Empty;
control.InvalidateMeasure();
control.Restart();
}
protected override Size MeasureOverride(Size constraint)
{
block.FontFamily = FontFamily;
block.FontSize = FontSize;
block.FontStyle = FontStyle;
block.FontWeight = FontWeight;
block.FontStretch = FontStretch;
block.Foreground = Foreground;
block.Measure(new Size(double.PositiveInfinity, constraint.Height));
return new Size(
double.IsInfinity(constraint.Width) ? block.DesiredSize.Width : Math.Min(block.DesiredSize.Width, constraint.Width),
block.DesiredSize.Height);
}
protected override Size ArrangeOverride(Size size)
{
block.Arrange(new Rect(0.0, 0.0, block.DesiredSize.Width, size.Height));
return size;
}
void Restart()
{
offset.BeginAnimation(TranslateTransform.XProperty, null);
offset.X = 0.0;
IsScrolling = false;
var hidden = HiddenWidth;
if (hidden <= 1.0 || ActualWidth <= 0.0)
return;
var travel = TimeSpan.FromSeconds(hidden / PixelsPerSecond);
var hold = TimeSpan.FromSeconds(HoldSeconds);
var frames = new DoubleAnimationUsingKeyFrames
{
RepeatBehavior = RepeatBehavior.Forever,
KeyFrames =
{
new LinearDoubleKeyFrame(0.0, KeyTime.FromTimeSpan(hold)),
new LinearDoubleKeyFrame(-hidden, KeyTime.FromTimeSpan(hold + travel)),
new LinearDoubleKeyFrame(-hidden, KeyTime.FromTimeSpan(hold + travel + hold)),
new LinearDoubleKeyFrame(0.0, KeyTime.FromTimeSpan(hold + travel + hold + travel)),
},
};
IsScrolling = true;
offset.BeginAnimation(TranslateTransform.XProperty, frames);
}
}
サブモジュール
+1
サブモジュール YMM4-Telemetry が 04010903ca で追加されました。
バイナリ
ファイルの表示
バイナリファイルは表示されません。

変更後

幅:  |  高さ:  |  サイズ: 650 KiB