コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
92e8aace30
|
||
|
|
767ac2d9de
|
||
|
|
7e6e78cd82
|
||
|
|
66abdacb91
|
||
|
|
779b6b8b0d
|
||
|
|
53461b59f4
|
||
|
|
0fc1456b3e
|
||
|
|
294d3475de
|
||
|
|
3971c60295
|
||
|
|
7e3715d423
|
||
|
|
d7b4bfe431
|
||
|
|
1d7644de97
|
||
|
|
9030fe55a8
|
||
|
|
3fbfeaa514
|
||
|
|
4bea943cf3
|
||
|
|
1824f9faaf
|
||
|
|
41b813e2bb
|
||
|
|
e1fa384f83
|
||
|
|
d455ed4659
|
||
|
|
eb90cfd9c6
|
||
|
|
eaaebb43fe | ||
|
|
2baedff12c
|
||
|
|
9e114cc414
|
||
|
|
316b4fe1b6
|
||
|
|
0a2a9a2bf6
|
||
|
|
fa1758de0d
|
||
|
|
fe5801cefe
|
||
|
|
63198039dc
|
||
|
|
ba001e1d23
|
||
|
|
26d3f2007e
|
||
|
|
5328d1efe3
|
||
|
|
6dc3b7f4f7
|
||
|
|
36169bc285
|
||
|
|
b997849ece
|
||
|
|
fbf5745ff7 | ||
|
|
9b9b922164
|
||
|
|
703bb6b3a4
|
||
|
|
5b599a7f25
|
||
|
|
b4455e3252
|
||
|
|
aca86e31b7
|
検索条件に一致するファイルはありません
@@ -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.
|
||||
+29
-6
@@ -1,5 +1,5 @@
|
||||
========================================
|
||||
UTAU for YMM4 v1.2.0
|
||||
UTAU for YMM4 v1.7.0
|
||||
========================================
|
||||
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 の書き出しにも
|
||||
対応していません。
|
||||
@@ -105,10 +125,13 @@ WorldNet で分析して合成し直します。
|
||||
本プラグインは音声の分析と合成に WorldNet(MIT License)を同梱しています。
|
||||
WorldNet は M. Morise 氏の WORLD(修正 BSD License)を C# へ移植した物で、
|
||||
高速フーリエ変換には Takuya OOURA 氏の FFT パッケージを用いています。
|
||||
ライセンスの全文は同梱の LICENSE フォルダー(WorldNet.txt)に収録しています。
|
||||
歌詞をまとめて編集するときの区切り方は OpenUtau(MIT License)の規約に
|
||||
合わせています。
|
||||
ライセンスの全文は同梱の LICENSE フォルダーに収録しています。
|
||||
WorldNet : Copyright (c) 2026 routersys
|
||||
WORLD : Copyright (c) 2010 M. Morise
|
||||
Ooura FFT : Copyright Takuya OOURA, 1996-2001
|
||||
OpenUtau : Copyright (c) 2014 StAkira
|
||||
--------------------------------------------------------------------------------
|
||||
■ ライセンス
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
@@ -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: |
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@ YukkuriMovieMaker4(YMM4)上で動作する、UTAU 音源から歌声を合
|
||||
単独音・連続音・CVVC のいずれの音源にも対応し、UST ファイルの読み込みにも対応します。
|
||||
セリフのかなから組み立てたノートは、ピアノロールのノートエディターで編集できます。
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
## 目次
|
||||
@@ -24,7 +26,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、UTAU 音源から歌声を合
|
||||
- [3. UST ファイルの読み込み](#3-ust-ファイルの読み込み)
|
||||
- [4. ノートエディター](#4-ノートエディター)
|
||||
- [5. WORLD による合成](#5-world-による合成)
|
||||
- [6. 解析キャッシュ](#6-解析キャッシュ)
|
||||
- [6. 解析と合成の再利用](#6-解析と合成の再利用)
|
||||
5. [音程記法](#音程記法)
|
||||
6. [パラメータ一覧](#パラメータ一覧)
|
||||
7. [ノートの項目一覧](#ノートの項目一覧)
|
||||
@@ -46,7 +48,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、UTAU 音源から歌声を合
|
||||
|
||||
セリフに書いたかなからノート列を組み立てるほか、UST ファイルのパスを書くとその譜面をそのまま読み込みます。組み立てたノートはノートエディターで編集でき、音程・長さ・ビブラート・ポルタメント・表現曲線を調整できます。
|
||||
|
||||
音声ファイルの分析結果と、合成した音を区間ごとにメモリへ保持するため、2 回目以降の合成が速くなります。1 つのノートを直したときは、そのノートを含む区間だけを合成し直します。
|
||||
音声ファイルの分析結果と、合成した音を区間ごとにメモリへ保持するため、2 回目以降の合成が速くなります。1 つのノートを直したときは、その周りの区間だけを合成し直します。
|
||||
|
||||
画面の表示は日本語のほか、英語、簡体字と繁体字の中国語、韓国語、スペイン語、アラビア語、インドネシア語に対応します。
|
||||
|
||||
@@ -120,8 +122,15 @@ YukkuriMovieMaker4(YMM4)上で動作する、UTAU 音源から歌声を合
|
||||
- ノートを 2 回押すと音程の制御点を追加し、制御点を引くと動かし、右で押すと削除します。制御点の間の曲線は S 字・直線・R 字・J 字から選べます。
|
||||
- 下の帯では、子音速度・音量・モジュレーションをノートごとの棒として、フォルマントと息の量を曲線として引いて編集できます。
|
||||
- 休符の挿入、ノートの削除、すべてのノートの選択、表示範囲に合わせる操作をボタンから行えます。
|
||||
- ノートを右で押すと品書きが出ます。押したノートが選択に入っていないときは、そのノートだけを選び直します。選択の中を押したときは選択をそのまま保ちます。
|
||||
- 品書きからは、選んだノートすべてに対してオクターブ上げとオクターブ下げ、長さを吸着に合わせる操作を行えます。オクターブの上げ下げは、端に当たるノートがあるときは選択全体の移動量を縮めるため、ノートどうしの音程差は変わりません。長さを吸着に合わせる操作は、吸着なしのときは行いません。
|
||||
- 品書きの「戻す」からは、選んだノートすべての音程曲線・ビブラート・発声タイミング・ノート全体を既定へ戻せます。歌詞と音程と長さは残ります。
|
||||
- 品書きからノートをコピーして貼り付けられます。貼り付けたノートは選択の後ろに入り、そのまま選択されます。コピーした内容は別のアイテムの編集画面へも貼り付けられます。
|
||||
- 品書きの「歌詞をまとめて編集」では、選んだノートの歌詞を別の窓で一度に書き換えられます。空白と改行で区切り、漢字とかなは 1 文字ずつ、引用符で囲んだ部分はまとめて 1 つのノートになります。歌詞の数とノートの数を窓に表示し、歌詞の方が多いときは余りを捨て、ノートの方が多いときは残りのノートをそのままにします。
|
||||
- 品書きの「別ウィンドウで編集」では、編集画面をそのまま別の窓へ移せます。窓を閉じると元の位置へ戻り、編集した内容はそのまま残ります。窓を開いている間は「ノートを編集」のボタンを押せません。
|
||||
- ノートは隙間なく並びます。間を空けるときは休符を挿入します。
|
||||
- 原音設定に見つからなかった歌詞があるときは、工具列の右端に警告として並びます。ノートエディターを開いたままでも、合成をやり直すたびに書き換わります。
|
||||
- 工具列の文言が幅に収まらないときは、2 秒おいてから端まで送り、2 秒おいて戻ります。収まっているときは動きません。
|
||||
- 編集内容は YMM4 の取り消しとやり直しに対応します。合成の結果として作られる情報は取り消しの対象になりません。
|
||||
|
||||
### 5. WORLD による合成
|
||||
@@ -134,11 +143,13 @@ YukkuriMovieMaker4(YMM4)上で動作する、UTAU 音源から歌声を合
|
||||
|
||||
出力は 16 ビットのモノラル WAV です。ノートの母音から口パクに使う情報も作ります。
|
||||
|
||||
### 6. 解析キャッシュ
|
||||
### 6. 解析と合成の再利用
|
||||
|
||||
分析結果は、音声ファイルの場所と更新日時と読み込む範囲と推定方法を鍵にしてメモリへ保持します。2 回目以降の合成では分析をやり直しません。上限は既定で 512MB で、64MB から 4096MB まで設定できます。上限を超えると古い物から捨てます。設定画面から破棄することもできます。複数の音声ファイルの分析は複数のコアで並列に行います。
|
||||
|
||||
合成した音そのものも区間ごとに保持します。区間は休符で切れる塊で、50 ミリ秒より離れたノートの間で分かれます。鍵には、その区間の合成に使う値をすべて入れます。原音の場所と切り出す範囲、ノートの音程・長さ・子音速度・音量・モジュレーション・ビブラート・音程曲線、合成の設定、区間の位置と長さです。1 つのノートを直すと、そのノートを含む区間だけを合成し直し、残りはそのまま使います。上限は既定で 256MB で、64MB から 4096MB まで設定できます。超えると古い物から捨てます。設定画面の破棄は分析と区間の両方を消します。表現の帯でフォルマントか息の量の曲線を引いているときは、曲線が時刻ごとに変わるため区間の再利用を行いません。
|
||||
区間ごとの合成は複数のコアで並列に行います。区間は互いに独立しているため、並列にしても結果は変わりません。同時に使うコアの数は、区間の大きさから必要な作業領域を見積もり、合計が 768MB に収まる範囲で決めます。
|
||||
|
||||
合成した音そのものも区間ごとに保持します。区間は休符で切れる塊で、50 ミリ秒より離れたノートの間で分かれます。鍵には、その区間の合成に使う値をすべて入れます。原音の場所と切り出す範囲、ノートの音程・長さ・子音速度・音量・モジュレーション・ビブラート・音程曲線、合成の設定、区間の位置と長さです。鍵は区間の中での相対的な位置で作るため、後ろのノートが前後へ動いただけの区間はそのまま使います。音程や音量のように位置が動かない編集では、直したノートを含む区間だけを合成し直します。ノートの長さを変えたときは、区間の切れ目がフレームの丸めでずれる分だけ、いくつかの区間を合成し直します。上限は既定で 256MB で、64MB から 4096MB まで設定できます。超えると古い物から捨てます。設定画面の破棄は分析と区間の両方を消します。表現の帯でフォルマントか息の量の曲線を引いているときは、曲線が時刻ごとに変わるため区間の再利用を行いません。
|
||||
|
||||
---
|
||||
|
||||
@@ -271,13 +282,14 @@ 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 |
|
||||
| [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 |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -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++)
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,542 @@
|
||||
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 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));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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,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]
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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()
|
||||
{
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
+180
-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)
|
||||
|
||||
+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
|
||||
|
+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>
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
<UseWPF>true</UseWPF>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<Version>1.4.1</Version>
|
||||
<Version>1.7.0</Version>
|
||||
<Platforms>AnyCPU;x64;x64</Platforms>
|
||||
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
|
||||
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -90,9 +89,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);
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -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>
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
バイナリ
バイナリファイルは表示されません。
|
変更後 幅: | 高さ: | サイズ: 650 KiB |
新しいイシューから参照
ユーザーをブロックする