From 1e7fbde35904f3e417b58c23041aea8e98b23a42 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 15:32:56 +0800 Subject: [PATCH 01/13] feat: add custom resampler management page to Options Add a "Custom resamplers" entry in Options (hidden on iOS/browser) that opens a page matching the Plugin manager layout. Users can add an external resampler (with its sibling .yaml manifest) after a trust confirmation, replace an existing one, or remove one. The engine registry is rescanned afterwards so the resampler appears in track render settings. Changes are blocked while a project is open. Strings added for en, zh-Hans, ja, ru and uk. Not built or run locally (no .NET SDK available in the authoring environment). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Lxd33Mk18eZmnG4beNc2DE --- OpenUtauMobile/Assets/Lang/Strings.en.resx | 93 +++++++ OpenUtauMobile/Assets/Lang/Strings.ja.resx | 93 +++++++ OpenUtauMobile/Assets/Lang/Strings.ru.resx | 93 +++++++ OpenUtauMobile/Assets/Lang/Strings.uk.resx | 93 +++++++ .../Assets/Lang/Strings.zh-Hans.resx | 93 +++++++ .../Services/ResamplerManagementService.cs | 228 ++++++++++++++++++ OpenUtauMobile/ViewLocator.cs | 1 + OpenUtauMobile/ViewModels/OptionsViewModel.cs | 7 +- .../ViewModels/ResamplerCardViewModel.cs | 18 ++ .../ViewModels/ResamplerManagerViewModel.cs | 200 +++++++++++++++ OpenUtauMobile/Views/OptionsView.axaml | 33 +++ .../Views/ResamplerManagerView.axaml | 92 +++++++ .../Views/ResamplerManagerView.axaml.cs | 11 + 13 files changed, 1054 insertions(+), 1 deletion(-) create mode 100644 OpenUtauMobile/Services/ResamplerManagementService.cs create mode 100644 OpenUtauMobile/ViewModels/ResamplerCardViewModel.cs create mode 100644 OpenUtauMobile/ViewModels/ResamplerManagerViewModel.cs create mode 100644 OpenUtauMobile/Views/ResamplerManagerView.axaml create mode 100644 OpenUtauMobile/Views/ResamplerManagerView.axaml.cs diff --git a/OpenUtauMobile/Assets/Lang/Strings.en.resx b/OpenUtauMobile/Assets/Lang/Strings.en.resx index 01956d6d..c68e052c 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.en.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.en.resx @@ -2275,6 +2275,99 @@ Failed to undo deletion + + Custom resamplers + + + Add and remove external resamplers + + + Custom resamplers + + + Add resampler + + + No custom resamplers yet. Tap + to add one. + + + Supported files: {0}. Added resamplers appear in track render settings. Being listed doesn't guarantee a program runs on this device. + + + no extension + + + Select a resampler + + + Failed to read resamplers: {0} + + + Available in track render settings + + + Not loaded on this device + + + This device can't load this file type. + + + This name is reserved by a built-in resampler. Rename the file and try again. + + + This file is already in the resampler folder. + + + Add resampler? + + + Add “{0}”? + + + Resamplers are external programs that run on your device. Only add files from sources you trust. + + + Add + + + Replace resampler? + + + “{0}” is already added. Replace it with the selected file? + + + Replace + + + Adding resampler… + + + Done + + + Failed to add the resampler + + + Resampler added + + + Remove resampler? + + + Remove “{0}” and its manifest? Projects that use it will fall back to the default resampler. + + + Failed to remove the resampler + + + Removing resampler… + + + Resampler removed + + + Close the open project before changing resamplers. + Workspace Arrangement Piano roll diff --git a/OpenUtauMobile/Assets/Lang/Strings.ja.resx b/OpenUtauMobile/Assets/Lang/Strings.ja.resx index 3fe53108..eb2b619b 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.ja.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.ja.resx @@ -2271,6 +2271,99 @@ 削除予定の取り消しに失敗しました + + カスタムリサンプラー + + + 外部リサンプラーの追加と削除 + + + カスタムリサンプラー + + + リサンプラーを追加 + + + カスタムリサンプラーはまだありません。+ をタップして追加します。 + + + 対応ファイル:{0}。追加したリサンプラーはトラックのレンダリング設定で選べます。一覧に表示されても、このデバイスで実行できるとは限りません。 + + + 拡張子なし + + + リサンプラーを選択 + + + リサンプラーを読み込めませんでした:{0} + + + トラックのレンダリング設定で選択できます + + + このデバイスでは読み込まれていません + + + このデバイスでは、この種類のファイルを読み込めません。 + + + この名前は内蔵リサンプラーが使用しています。ファイル名を変更してもう一度お試しください。 + + + このファイルはすでにリサンプラーのフォルダーにあります。 + + + リサンプラーを追加しますか? + + + 「{0}」を追加しますか? + + + リサンプラーはデバイス上で実行される外部プログラムです。信頼できる入手元のファイルだけを追加してください。 + + + 追加 + + + リサンプラーを置き換えますか? + + + 「{0}」はすでに追加されています。選択したファイルで置き換えますか? + + + 置き換え + + + リサンプラーを追加しています… + + + 完了 + + + リサンプラーを追加できませんでした + + + リサンプラーを追加しました + + + リサンプラーを削除しますか? + + + 「{0}」とそのマニフェストを削除しますか?使用しているプロジェクトは既定のリサンプラーに戻ります。 + + + リサンプラーを削除できませんでした + + + リサンプラーを削除しています… + + + リサンプラーを削除しました + + + リサンプラーを変更する前に、開いているプロジェクトを閉じてください。 + ワークスペース アレンジ ピアノロール diff --git a/OpenUtauMobile/Assets/Lang/Strings.ru.resx b/OpenUtauMobile/Assets/Lang/Strings.ru.resx index fc8e0567..6c1fc816 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.ru.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.ru.resx @@ -2230,6 +2230,99 @@ Не удалось отменить удаление + + Пользовательские ресемплеры + + + Добавление и удаление внешних ресемплеров + + + Пользовательские ресемплеры + + + Добавить ресемплер + + + Пользовательских ресемплеров пока нет. Нажмите +, чтобы добавить. + + + Поддерживаемые файлы: {0}. Добавленные ресемплеры доступны в настройках рендеринга дорожки. Наличие в списке не гарантирует, что программа запустится на этом устройстве. + + + без расширения + + + Выберите ресемплер + + + Не удалось прочитать ресемплеры: {0} + + + Доступен в настройках рендеринга дорожки + + + Не загружен на этом устройстве + + + Это устройство не может загрузить файл такого типа. + + + Это имя занято встроенным ресемплером. Переименуйте файл и повторите попытку. + + + Этот файл уже находится в папке ресемплеров. + + + Добавить ресемплер? + + + Добавить «{0}»? + + + Ресемплеры — это внешние программы, которые запускаются на вашем устройстве. Добавляйте только файлы из надёжных источников. + + + Добавить + + + Заменить ресемплер? + + + «{0}» уже добавлен. Заменить его выбранным файлом? + + + Заменить + + + Добавление ресемплера… + + + Готово + + + Не удалось добавить ресемплер + + + Ресемплер добавлен + + + Удалить ресемплер? + + + Удалить «{0}» и его манифест? Проекты, которые его используют, перейдут на ресемплер по умолчанию. + + + Не удалось удалить ресемплер + + + Удаление ресемплера… + + + Ресемплер удалён + + + Закройте открытый проект, прежде чем менять ресемплеры. + Рабочая область Аранжировка Пианоролл diff --git a/OpenUtauMobile/Assets/Lang/Strings.uk.resx b/OpenUtauMobile/Assets/Lang/Strings.uk.resx index 63b584dc..61013761 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.uk.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.uk.resx @@ -2230,6 +2230,99 @@ Не вдалося скасувати видалення + + Користувацькі ресемплери + + + Додавання та видалення зовнішніх ресемплерів + + + Користувацькі ресемплери + + + Додати ресемплер + + + Користувацьких ресемплерів ще немає. Натисніть +, щоб додати. + + + Підтримувані файли: {0}. Додані ресемплери доступні в налаштуваннях рендерингу доріжки. Наявність у списку не гарантує, що програма запуститься на цьому пристрої. + + + без розширення + + + Виберіть ресемплер + + + Не вдалося прочитати ресемплери: {0} + + + Доступний у налаштуваннях рендерингу доріжки + + + Не завантажено на цьому пристрої + + + Цей пристрій не може завантажити файл такого типу. + + + Цю назву займає вбудований ресемплер. Перейменуйте файл і спробуйте ще раз. + + + Цей файл уже є в теці ресемплерів. + + + Додати ресемплер? + + + Додати «{0}»? + + + Ресемплери — це зовнішні програми, що запускаються на вашому пристрої. Додавайте лише файли з надійних джерел. + + + Додати + + + Замінити ресемплер? + + + «{0}» уже додано. Замінити його вибраним файлом? + + + Замінити + + + Додавання ресемплера… + + + Готово + + + Не вдалося додати ресемплер + + + Ресемплер додано + + + Видалити ресемплер? + + + Видалити «{0}» та його маніфест? Проєкти, які його використовують, перейдуть на ресемплер за замовчуванням. + + + Не вдалося видалити ресемплер + + + Видалення ресемплера… + + + Ресемплер видалено + + + Закрийте відкритий проєкт, перш ніж змінювати ресемплери. + Робоча область Аранжування Піанорол diff --git a/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx b/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx index a9a003cb..52d2f484 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx @@ -2275,6 +2275,99 @@ 取消删除标记失败 + + 自定义重采样器 + + + 添加和移除外部重采样器 + + + 自定义重采样器 + + + 添加重采样器 + + + 还没有自定义重采样器,点按 + 添加。 + + + 支持的文件:{0}。添加后可在轨道渲染设置中选用。列入此处不代表程序一定能在本设备上运行。 + + + 无扩展名 + + + 选择重采样器 + + + 读取重采样器失败:{0} + + + 可在轨道渲染设置中选用 + + + 本设备未能加载 + + + 本设备无法加载此类型的文件。 + + + 该名称已被内置重采样器占用,请重命名文件后重试。 + + + 该文件已位于重采样器目录中。 + + + 添加重采样器? + + + 要添加“{0}”吗? + + + 重采样器是会在你的设备上运行的外部程序,请仅添加来源可信的文件。 + + + 添加 + + + 替换重采样器? + + + “{0}”已存在,要用所选文件替换吗? + + + 替换 + + + 正在添加重采样器… + + + 完成 + + + 添加重采样器失败 + + + 已添加重采样器 + + + 移除重采样器? + + + 要移除“{0}”及其清单吗?使用它的工程将回退到默认重采样器。 + + + 移除重采样器失败 + + + 正在移除重采样器… + + + 已移除重采样器 + + + 请先关闭当前打开的工程,再修改重采样器。 + 工作区 编曲 钢琴卷帘 diff --git a/OpenUtauMobile/Services/ResamplerManagementService.cs b/OpenUtauMobile/Services/ResamplerManagementService.cs new file mode 100644 index 00000000..d5429122 --- /dev/null +++ b/OpenUtauMobile/Services/ResamplerManagementService.cs @@ -0,0 +1,228 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using OpenUtau.Classic; +using OpenUtau.Core; +using OpenUtau.Core.Util; +using OpenUtauMobile.Helpers; +using OpenUtauMobile.ViewModels; + +namespace OpenUtauMobile.Services; + +/// 重采样器目录中的一个文件,以及引擎当前是否已将其注册为可选重采样器。 +public sealed record ResamplerFileEntry(string RelativePath, long Size, bool IsAvailable) +{ + /// 不含目录的文件名。 + public string FileName => Path.GetFileName(RelativePath); + + /// 以 KB 表示的文件大小。 + public string SizeText => $"{Size / 1024d:N1} KB"; +} + +/// +/// 管理自定义重采样器文件。安装和移除后重新扫描引擎注册表; +/// “可用”只表示引擎已识别该文件,不代表程序能在当前设备上实际运行。 +/// +public static class ResamplerManagementService +{ + // 内置重采样器在 Core 中是 internal 类型,Mobile 层无法引用其常量,只能按名称保留。 + private static readonly string[] BuiltinNames = ["worldline", "hifisampler"]; + + private static StringComparer PathComparer => OperatingSystem.IsWindows() + ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; + + private static StringComparison PathComparison => OperatingSystem.IsWindows() + ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + + private static string Root => Path.GetFullPath(PathManager.Inst.ResamplersPath); + + /// 文件选择器的过滤器。内置选择器无法匹配无扩展名文件,非 Windows 平台因此不加过滤。 + public static string[] PickerFilters => OperatingSystem.IsWindows() ? ["*.exe", "*.bat"] : []; + + /// 当前设备可添加的文件类型,供界面提示使用。 + public static string DescribeSupportedTypes() + { + List types; + if (OperatingSystem.IsWindows()) + { + types = [".exe", ".bat"]; + } + else + { + types = [".sh", L.S("ResamplerManager.NoExtension")]; + if (!string.IsNullOrEmpty(Preferences.Default.WinePath)) types.AddRange([".exe", ".bat"]); + } + return string.Join(", ", types); + } + + /// 按引擎扫描重采样器时相同的规则,判断当前设备能否加载该文件类型。 + public static bool IsLoadableFile(string path) + { + string extension = Path.GetExtension(path).ToLowerInvariant(); + if (extension is ".exe" or ".bat") + return OperatingSystem.IsWindows() || !string.IsNullOrEmpty(Preferences.Default.WinePath); + return !OperatingSystem.IsWindows() && (extension == ".sh" || extension.Length == 0); + } + + /// 目录中可能是重采样器的文件;不含配置文件和安装中的临时文件。 + private static bool IsCandidate(string path) + { + string fileName = Path.GetFileName(path); + if (fileName.StartsWith('.')) return false; + return Path.GetExtension(fileName).ToLowerInvariant() is ".exe" or ".bat" or ".sh" or ""; + } + + /// 列出重采样器目录中的文件,并标出引擎已注册的项。 + public static IReadOnlyList ListFiles() + { + string root = Root; + Directory.CreateDirectory(root); + // 内置重采样器位于应用根目录,不会与此目录下的文件重合。 + HashSet registered = new( + ToolsManager.Inst.Resamplers + .Select(resampler => resampler.FilePath) + .Where(path => !string.IsNullOrEmpty(path)) + .Select(Path.GetFullPath), + PathComparer); + EnumerationOptions options = new() + { + RecurseSubdirectories = true, + IgnoreInaccessible = false, + AttributesToSkip = FileAttributes.ReparsePoint, + }; + return + [ + .. Directory.EnumerateFiles(root, "*", options) + .Where(IsCandidate) + .Select(path => new ResamplerFileEntry( + Path.GetRelativePath(root, path), + new FileInfo(path).Length, + registered.Contains(Path.GetFullPath(path)))) + .OrderBy(entry => entry.RelativePath, StringComparer.OrdinalIgnoreCase) + ]; + } + + /// 在询问信任前检查所选文件,不写入重采样器目录。 + public static void ValidateForInstall(string sourcePath) + { + if (!File.Exists(sourcePath) || !IsLoadableFile(sourcePath)) + throw new InvalidDataException(L.S("ResamplerManager.UnsupportedFile")); + // 与内置重采样器同名的文件会在引擎扫描时被忽略,提前拒绝以免出现安装成功却不可用的文件。 + if (BuiltinNames.Contains(Path.GetFileName(sourcePath), StringComparer.OrdinalIgnoreCase)) + throw new InvalidDataException(L.S("ResamplerManager.BuiltinNotAllowed")); + if (PathComparer.Equals(Path.GetFullPath(sourcePath), GetDestination(sourcePath))) + throw new InvalidDataException(L.S("ResamplerManager.AlreadyInstalled")); + } + + /// 安装该文件会覆盖已有的同名重采样器。 + public static bool WillReplace(string sourcePath) => File.Exists(GetDestination(sourcePath)); + + private static string GetDestination(string sourcePath) => Path.Combine(Root, Path.GetFileName(sourcePath)); + + /// + /// 复制重采样器及其同名 YAML 清单到重采样器目录。 + /// 先复制到临时文件,全部成功后再发布;清单先于程序发布,失败时不会留下半个安装。 + /// + public static async Task InstallAsync(string sourcePath, LoadingPopupViewModel loading) + { + // 确认期间文件或目录状态可能变化,复制前再次检查。 + ValidateForInstall(sourcePath); + string root = Root; + Directory.CreateDirectory(root); + + string destination = GetDestination(sourcePath); + // 清单约定与引擎一致:与程序同名、扩展名为 .yaml。 + string manifestSource = Path.ChangeExtension(sourcePath, ".yaml"); + string manifestDestination = Path.ChangeExtension(destination, ".yaml"); + bool hasManifest = File.Exists(manifestSource); + bool manifestExisted = File.Exists(manifestDestination); + + List temporaryFiles = []; + bool manifestPublished = false; + try + { + loading.UpdateProgress(5, L.S("ResamplerManager.Installing")); + string programTemporary = await CopyToTemporaryAsync(sourcePath, root, temporaryFiles); + // 引擎不会调用 CheckPermissions,从选择器复制来的文件没有执行位,需在此补上。 + if (!OperatingSystem.IsWindows() && !OperatingSystem.IsBrowser()) + { + File.SetUnixFileMode(programTemporary, + UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute + | UnixFileMode.GroupRead | UnixFileMode.GroupExecute + | UnixFileMode.OtherRead | UnixFileMode.OtherExecute); + } + loading.UpdateProgress(70); + + string? manifestTemporary = hasManifest + ? await CopyToTemporaryAsync(manifestSource, root, temporaryFiles) + : null; + loading.UpdateProgress(85); + + if (manifestTemporary != null) + { + File.Move(manifestTemporary, manifestDestination, overwrite: true); + manifestPublished = true; + } + File.Move(programTemporary, destination, overwrite: true); + loading.UpdateProgress(95); + } + catch + { + // 程序未能发布时,撤销本次新增的清单,避免遗留无主文件。 + if (manifestPublished && !manifestExisted) DeleteFile(manifestDestination); + throw; + } + finally + { + foreach (string temporary in temporaryFiles) + { + if (File.Exists(temporary)) File.Delete(temporary); + } + } + } + + /// 复制到目录内的临时文件;临时文件以点开头且无可识别扩展名,不会进入列表或被引擎加载。 + private static async Task CopyToTemporaryAsync(string sourcePath, string root, List temporaryFiles) + { + string temporary = Path.Combine(root, $".{Guid.NewGuid():N}.installing"); + temporaryFiles.Add(temporary); + await using FileStream source = new(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read); + await using FileStream target = new(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None); + await source.CopyToAsync(target); + await target.FlushAsync(); + return temporary; + } + + /// 删除重采样器及其同名清单;相对路径必须位于重采样器目录内。 + public static void Uninstall(string relativePath) + { + string path = ResolvePath(relativePath); + DeleteFile(path); + DeleteFile(Path.ChangeExtension(path, ".yaml")); + } + + /// 重新扫描引擎注册表。Initialize 自带锁,渲染线程不会读到半更新的映射。 + public static Task RescanAsync() => Task.Run(() => ToolsManager.Inst.Initialize()); + + private static void DeleteFile(string path) + { + if (!File.Exists(path)) return; + // 用户已确认删除;只读属性不应阻止删除。 + FileAttributes attributes = File.GetAttributes(path); + if ((attributes & FileAttributes.ReadOnly) != 0) File.SetAttributes(path, attributes & ~FileAttributes.ReadOnly); + File.Delete(path); + } + + private static string ResolvePath(string relativePath) + { + ArgumentException.ThrowIfNullOrWhiteSpace(relativePath); + string root = Root; + string path = Path.GetFullPath(Path.Combine(root, relativePath)); + string prefix = Path.TrimEndingDirectorySeparator(root) + Path.DirectorySeparatorChar; + if (Path.IsPathRooted(relativePath) || !path.StartsWith(prefix, PathComparison) || !IsCandidate(path)) + throw new InvalidDataException("Invalid resampler path."); + return path; + } +} diff --git a/OpenUtauMobile/ViewLocator.cs b/OpenUtauMobile/ViewLocator.cs index 28af6de3..9bdfdac4 100644 --- a/OpenUtauMobile/ViewLocator.cs +++ b/OpenUtauMobile/ViewLocator.cs @@ -28,6 +28,7 @@ public class ViewLocator : IDataTemplate [typeof(PluginManagerViewModel)] = static () => new PluginManagerView(), [typeof(PluginSingerSetupViewModel)] = static () => new PluginSingerSetupView(), [typeof(PluginWebSettingsViewModel)] = static () => new PluginWebSettingsView(), + [typeof(ResamplerManagerViewModel)] = static () => new ResamplerManagerView(), [typeof(SandboxFileManagerViewModel)] = static () => new SandboxFileManagerView(), [typeof(SettingsViewModel)] = static () => new SettingsView(), [typeof(SingerDetailViewModel)] = static () => new SingerDetailView(), diff --git a/OpenUtauMobile/ViewModels/OptionsViewModel.cs b/OpenUtauMobile/ViewModels/OptionsViewModel.cs index f69729bb..511357ea 100644 --- a/OpenUtauMobile/ViewModels/OptionsViewModel.cs +++ b/OpenUtauMobile/ViewModels/OptionsViewModel.cs @@ -1,4 +1,5 @@ -using System.Reactive; +using System; +using System.Reactive; using OpenUtauMobile.Helpers; using OpenUtauMobile.Services; using OpenUtauMobile.Services.Dialogs; @@ -12,6 +13,9 @@ public class OptionsViewModel : NavigateViewModelBase public ReactiveCommand OpenSettingsCommand { get; } public ReactiveCommand OpenDependencyManagerCommand { get; } public ReactiveCommand OpenPluginManagerCommand { get; } + /// iOS 与浏览器无法启动外部程序,不提供自定义重采样器入口。 + public bool IsResamplerManagerAvailable => !OperatingSystem.IsIOS() && !OperatingSystem.IsBrowser(); + public ReactiveCommand OpenResamplerManagerCommand { get; } /// 仅在平台注册了沙箱传输能力时显示文件管理入口。 public bool IsSandboxFileManagerAvailable => ServiceHub.SandboxFileTransferService != null; public ReactiveCommand OpenSandboxFileManagerCommand { get; } @@ -25,6 +29,7 @@ public OptionsViewModel(MainViewModel navigator) : base(navigator) OpenSettingsCommand = ReactiveCommand.Create(OnOpenSettings); OpenDependencyManagerCommand = ReactiveCommand.Create(OnOpenDependencyManager); OpenPluginManagerCommand = ReactiveCommand.Create(() => Navigator.Navigate(new PluginManagerViewModel(Navigator))); + OpenResamplerManagerCommand = ReactiveCommand.Create(() => Navigator.Navigate(new ResamplerManagerViewModel(Navigator))); OpenSandboxFileManagerCommand = ReactiveCommand.Create(() => Navigator.Navigate(new SandboxFileManagerViewModel(Navigator))); OpenHelpCommand = ReactiveCommand.Create(OnOpenHelp); OpenExportLogsCommand = ReactiveCommand.Create(OnOpenExportLogs); diff --git a/OpenUtauMobile/ViewModels/ResamplerCardViewModel.cs b/OpenUtauMobile/ViewModels/ResamplerCardViewModel.cs new file mode 100644 index 00000000..f9c55e98 --- /dev/null +++ b/OpenUtauMobile/ViewModels/ResamplerCardViewModel.cs @@ -0,0 +1,18 @@ +using OpenUtauMobile.Helpers; +using OpenUtauMobile.Services; +using ReactiveUI; + +namespace OpenUtauMobile.ViewModels; + +/// 列表仅展示文件和引擎识别状态,移除操作由页面命令负责。 +public sealed class ResamplerCardViewModel(ResamplerFileEntry entry) : ReactiveObject +{ + public string FileName => entry.FileName; + public string RelativePath => entry.RelativePath; + /// 位于子目录时才单独显示相对路径,避免与文件名重复。 + public bool HasFolder => entry.RelativePath != entry.FileName; + public string SizeText => entry.SizeText; + /// 引擎已识别该文件;不代表程序一定能在当前设备上运行。 + public bool IsAvailable => entry.IsAvailable; + public string StatusText => L.S(IsAvailable ? "ResamplerManager.Available" : "ResamplerManager.Unavailable"); +} diff --git a/OpenUtauMobile/ViewModels/ResamplerManagerViewModel.cs b/OpenUtauMobile/ViewModels/ResamplerManagerViewModel.cs new file mode 100644 index 00000000..ff16c13d --- /dev/null +++ b/OpenUtauMobile/ViewModels/ResamplerManagerViewModel.cs @@ -0,0 +1,200 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reactive; +using System.Threading.Tasks; +using DynamicData.Binding; +using OpenUtau.Core; +using OpenUtauMobile.Helpers; +using OpenUtauMobile.Services; +using OpenUtauMobile.Services.Dialogs; +using OpenUtauMobile.Storage; +using ReactiveUI; +using ReactiveUI.Fody.Helpers; +using Serilog; + +namespace OpenUtauMobile.ViewModels; + +/// 自定义重采样器管理页:添加、移除,并在变更后刷新引擎注册表。 +public sealed class ResamplerManagerViewModel : NavigateViewModelBase, IDisposable +{ + public ObservableCollectionExtended Resamplers { get; } = []; + private bool disposed; + [Reactive] public bool IsBusy { get; private set; } + [Reactive] public bool IsEmpty { get; private set; } + [Reactive] public bool HasError { get; private set; } + [Reactive] public string ErrorMessage { get; private set; } = string.Empty; + /// 当前设备支持的文件类型提示;Wine 路径可能在设置中变化,因此每次刷新时重新生成。 + [Reactive] public string Hint { get; private set; } = string.Empty; + + public ReactiveCommand BackCommand { get; } + public ReactiveCommand RefreshCommand { get; } + public ReactiveCommand AddCommand { get; } + public ReactiveCommand RemoveCommand { get; } + + public ResamplerManagerViewModel(MainViewModel navigator) : base(navigator) + { + IObservable canOperate = this.WhenAnyValue(vm => vm.IsBusy, busy => !busy); + BackCommand = ReactiveCommand.Create(() => Navigator.NavigateBack(this), canOperate); + RefreshCommand = ReactiveCommand.CreateFromTask(RefreshAsync, canOperate); + AddCommand = ReactiveCommand.CreateFromTask(AddAsync, canOperate); + RemoveCommand = ReactiveCommand.CreateFromTask(RemoveAsync, canOperate); + } + + public override void OnNavigatedTo() => _ = RefreshAsync(); + + public override void OnBackRequested() + { + if (!IsBusy) base.OnBackRequested(); + } + + private async Task RefreshAsync() + { + if (IsBusy) return; + IsBusy = true; + try { await RefreshEntriesAsync(); } + finally { IsBusy = false; } + } + + private async Task RefreshEntriesAsync() + { + Hint = string.Format(L.S("ResamplerManager.Hint"), ResamplerManagementService.DescribeSupportedTypes()); + try + { + IReadOnlyList entries = await Task.Run(ResamplerManagementService.ListFiles); + Resamplers.Load([.. entries.Select(entry => new ResamplerCardViewModel(entry))]); + IsEmpty = entries.Count == 0; + HasError = false; + ErrorMessage = string.Empty; + } + catch (Exception exception) + { + Log.Error(exception, "Failed to list resamplers"); + IsEmpty = false; + HasError = true; + ErrorMessage = string.Format(L.S("ResamplerManager.RefreshFailed"), exception.Message); + } + } + + /// 引擎没有全局的渲染空闲边界,工程打开期间不修改重采样器注册表。 + private bool EnsureNoOpenProject() + { + if (Navigator.ActiveEditor == null) return true; + ToastService.Enqueue(L.S("ResamplerManager.CloseProjectFirst")); + return false; + } + + private async Task AddAsync() + { + if (IsBusy || !EnsureNoOpenProject()) return; + IsBusy = true; + try + { + bool installed = false; + try + { + string path = await FilePicker.PickSingleFileAsync( + L.S("ResamplerManager.SelectFile"), ResamplerManagementService.PickerFilters); + if (string.IsNullOrEmpty(path)) return; + ResamplerManagementService.ValidateForInstall(path); + string fileName = Path.GetFileName(path); + + // 重采样器是由应用直接执行的外部程序,添加前需要用户确认信任来源。 + string? answer = await OptionConfirmPopupService.ShowAsync( + L.S("ResamplerManager.TrustTitle"), + string.Format(L.S("ResamplerManager.TrustQuestion"), fileName) + + Environment.NewLine + Environment.NewLine + L.S("ResamplerManager.TrustMessage"), + [ + new OptionConfirmOption(L.S("Common.Cancel"), "cancel", isDefault: true), + new OptionConfirmOption(L.S("ResamplerManager.Continue"), "continue", isDestructive: true), + ]); + if (answer != "continue") return; + + if (ResamplerManagementService.WillReplace(path)) + { + answer = await OptionConfirmPopupService.ShowAsync( + L.S("ResamplerManager.ReplaceTitle"), + string.Format(L.S("ResamplerManager.ReplaceMessage"), fileName), + [ + new OptionConfirmOption(L.S("Common.Cancel"), "cancel", isDefault: true), + new OptionConfirmOption(L.S("ResamplerManager.Replace"), "replace", isDestructive: true), + ]); + if (answer != "replace") return; + } + + await LoadingPopupService.RunAsync(L.S("ResamplerManager.Installing"), 0, async loading => + { + await ResamplerManagementService.InstallAsync(path, loading); + await ResamplerManagementService.RescanAsync(); + await ServiceHub.FlushFileSystemAsync(); + loading.UpdateProgress(100, L.S("ResamplerManager.Completed")); + }); + installed = true; + } + catch (Exception exception) + { + ShowError("ResamplerManager.InstallFailed", exception); + } + finally + { + await RefreshEntriesAsync(); + } + if (installed) ToastService.Enqueue(L.S("ResamplerManager.Installed")); + } + finally { IsBusy = false; } + } + + private async Task RemoveAsync(ResamplerCardViewModel card) + { + if (IsBusy || !EnsureNoOpenProject()) return; + IsBusy = true; + try + { + bool removed = false; + try + { + string? answer = await OptionConfirmPopupService.ShowAsync( + L.S("ResamplerManager.DeleteTitle"), + string.Format(L.S("ResamplerManager.DeleteMessage"), card.FileName), + [ + new OptionConfirmOption(L.S("Common.Cancel"), "cancel", isDefault: true), + new OptionConfirmOption(L.S("Common.Delete"), "delete", isDestructive: true), + ]); + if (answer != "delete") return; + + await LoadingPopupService.RunAsync(L.S("ResamplerManager.Removing"), async _ => + { + await Task.Run(() => ResamplerManagementService.Uninstall(card.RelativePath)); + await ResamplerManagementService.RescanAsync(); + await ServiceHub.FlushFileSystemAsync(); + }); + removed = true; + } + catch (Exception exception) + { + ShowError("ResamplerManager.DeleteFailed", exception); + } + finally + { + await RefreshEntriesAsync(); + } + if (removed) ToastService.Enqueue(L.S("ResamplerManager.Removed")); + } + finally { IsBusy = false; } + } + + private static void ShowError(string key, Exception exception) + { + Log.Error(exception, "Resampler management operation failed: {Operation}", key); + ErrorDialogService.Show(new ErrorDialogViewModel(new ErrorMessageNotification(L.S(key), exception))); + } + + public void Dispose() + { + if (disposed) return; + disposed = true; + BackCommand.Dispose(); RefreshCommand.Dispose(); AddCommand.Dispose(); + RemoveCommand.Dispose(); + } +} diff --git a/OpenUtauMobile/Views/OptionsView.axaml b/OpenUtauMobile/Views/OptionsView.axaml index 4216cab4..a06c2e9b 100644 --- a/OpenUtauMobile/Views/OptionsView.axaml +++ b/OpenUtauMobile/Views/OptionsView.axaml @@ -148,6 +148,39 @@ + + + + + + + + + + + + + + + + +