From e2c559f6e4f67bcd46c9d42816b059d860b499b9 Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Thu, 29 Oct 2026 17:38:58 +0800 Subject: [PATCH 01/45] =?UTF-8?q?feature:=20=E5=88=9D=E6=AD=A5=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=E4=BB=8E=E6=8F=92=E4=BB=B6=E5=8A=A0=E8=BD=BD=E6=AD=8C?= =?UTF-8?q?=E6=89=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Views/DesktopTrackInspector.cs | 2 +- .../Services/ExternalSingerPluginService.cs | 75 +++++++++++++++++++ .../Services/Tracks/TrackImportService.cs | 1 + OpenUtauMobile/ViewModels/EditorViewModel.cs | 1 + .../ViewModels/RendererPickerViewModel.cs | 2 +- .../ViewModels/SingerDetailViewModel.cs | 3 +- .../ViewModels/SplashScreenViewModel.cs | 1 + .../ViewModels/TrackHeaderViewModel.cs | 6 +- .../ViewModels/TrackSettingsPopupViewModel.cs | 6 +- 9 files changed, 88 insertions(+), 9 deletions(-) create mode 100644 OpenUtauMobile/Services/ExternalSingerPluginService.cs diff --git a/OpenUtauMobile.DesktopUI/Views/DesktopTrackInspector.cs b/OpenUtauMobile.DesktopUI/Views/DesktopTrackInspector.cs index 9ba00df7..206c13e9 100644 --- a/OpenUtauMobile.DesktopUI/Views/DesktopTrackInspector.cs +++ b/OpenUtauMobile.DesktopUI/Views/DesktopTrackInspector.cs @@ -118,7 +118,7 @@ void CommitName() phonemizer.CommandParameter = phonemizer; body.Children.Add(DesktopInspectorControls.FieldRow(DesktopUi.Label("TrackSettings.Phonemizer"), phonemizer)); TrackHeaderViewModel rendererVm = _trackVm; - string[] renderers = track.Singer is { Found: true } singerModel ? Renderers.GetSupportedRenderers(singerModel.SingerType) : []; + string[] renderers = track.Singer is { Found: true } singerModel ? ExternalSingerPluginService.GetSupportedRenderers(singerModel) : []; ComboBox renderer = new() { Name = "TrackRendererPicker", ItemsSource = renderers, SelectedItem = track.RendererSettings.renderer, HorizontalAlignment = HorizontalAlignment.Stretch, IsEnabled = renderers.Length > 0 }; renderer.Classes.Add("DesktopTrackChoice"); renderer.SelectionChanged += (_, _) => diff --git a/OpenUtauMobile/Services/ExternalSingerPluginService.cs b/OpenUtauMobile/Services/ExternalSingerPluginService.cs new file mode 100644 index 00000000..5bdeea35 --- /dev/null +++ b/OpenUtauMobile/Services/ExternalSingerPluginService.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using OpenUtau.Core.Ustx; +using Serilog; + +namespace OpenUtauMobile.Services; + +/// 初始化声明启动入口的外部插件,并集中筛选具体歌手的渲染器。 +public static class ExternalSingerPluginService +{ + private static readonly List> policies = []; + private static readonly HashSet initialized = []; + private static readonly List refreshers = []; + private static readonly List> normalizers = []; + + /// 在核心歌手首次扫描后、工程载入前调用插件的约定入口。 + public static void Initialize() + { + foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) + { + if (initialized.Contains(assembly)) continue; + string? entry = assembly.GetCustomAttributes() + .FirstOrDefault(attribute => attribute.Key == "OpumPluginStartup")?.Value; + if (entry == null) continue; + try + { + Type type = assembly.GetType(entry, true)!; + MethodInfo method = type.GetMethod("Initialize", [typeof(Action>)]) + ?? throw new MissingMethodException(entry, "Initialize"); + List> pending = []; + method.Invoke(null, [new Action>(pending.Add)]); + policies.AddRange(pending); + if (type.GetMethod("RefreshSingers", Type.EmptyTypes) is { } refresh) + refreshers.Add(() => refresh.Invoke(null, null)); + if (type.GetMethod("NormalizeProject", [typeof(UProject)]) is { } normalize) + normalizers.Add(project => (bool)normalize.Invoke(null, [project])!); + initialized.Add(assembly); + } + catch (Exception exception) { Log.Error(exception, "Failed to initialize singer plugin {Assembly}", assembly.FullName); } + } + } + + /// 在没有发布歌手变更通知的直接重扫之后恢复外部注册。 + public static void RefreshSingers() + { + foreach (Action refresh in refreshers) + try { refresh(); } catch (Exception exception) { Log.Error(exception, "Failed to refresh external singers"); } + } + + /// 按实际歌手实例筛选可用渲染器。 + public static string[] GetSupportedRenderers(USinger singer) + { + foreach (Func policy in policies) + if (policy(singer) is { } options) return options; + return OpenUtau.Core.Render.Renderers.GetSupportedRenderers(singer.SingerType); + } + + /// 返回具体歌手的默认渲染器。 + public static string GetDefaultRenderer(USinger singer) + { + string[] options = GetSupportedRenderers(singer); + string preferred = OpenUtau.Core.Render.Renderers.GetDefaultRenderer(singer.SingerType); + return options.Contains(preferred) ? preferred : options.FirstOrDefault() ?? string.Empty; + } + + /// 在载入及轨道导入时补正外部 renderer,并重新校验快照。 + public static void NormalizeProject(UProject project) + { + bool changed = false; + foreach (Func normalize in normalizers) changed |= normalize(project); + if (changed) project.ValidateFull(); + } +} diff --git a/OpenUtauMobile/Services/Tracks/TrackImportService.cs b/OpenUtauMobile/Services/Tracks/TrackImportService.cs index c81b16c5..ab9b3004 100644 --- a/OpenUtauMobile/Services/Tracks/TrackImportService.cs +++ b/OpenUtauMobile/Services/Tracks/TrackImportService.cs @@ -24,6 +24,7 @@ public static IReadOnlyList ReadFiles(IEnumerable pat { UProject project = Formats.ReadProject([path]) ?? throw new InvalidDataException("Empty project."); NotePhonemizerResolver.Normalize(project); + ExternalSingerPluginService.NormalizeProject(project); if (project.parts.Any(part => part.trackNo < 0 || part.trackNo >= project.tracks.Count)) { throw new InvalidDataException("Invalid source track index."); diff --git a/OpenUtauMobile/ViewModels/EditorViewModel.cs b/OpenUtauMobile/ViewModels/EditorViewModel.cs index 8165d674..22c6a8be 100644 --- a/OpenUtauMobile/ViewModels/EditorViewModel.cs +++ b/OpenUtauMobile/ViewModels/EditorViewModel.cs @@ -507,6 +507,7 @@ internal static async Task PrepareProjectAsync(ProjectOpenOptio break; } bool repairedPhonemizers = NotePhonemizerResolver.Normalize(project); + ExternalSingerPluginService.NormalizeProject(project); return new PreparedProject(project, repairedPhonemizers); } diff --git a/OpenUtauMobile/ViewModels/RendererPickerViewModel.cs b/OpenUtauMobile/ViewModels/RendererPickerViewModel.cs index b8a83263..9abf7cf6 100644 --- a/OpenUtauMobile/ViewModels/RendererPickerViewModel.cs +++ b/OpenUtauMobile/ViewModels/RendererPickerViewModel.cs @@ -94,7 +94,7 @@ public RendererPickerViewModel(UProject project, UTrack track) _originalGraph = track.ExpressionGraph; if (_original.renderer != null) _graphDrafts[RendererRegistry.GetExpressionGraphSlot(_original.renderer)] = _originalGraph; - if (_singer is { Found: true }) Renderers.Load(RendererRegistry.GetSupportedRenderers(_singer.SingerType)); + if (_singer is { Found: true }) Renderers.Load(OpenUtauMobile.Services.ExternalSingerPluginService.GetSupportedRenderers(_singer)); _selectedRenderer = _original.renderer != null && Renderers.Contains(_original.renderer) ? _original.renderer : null; _selectedResampler = _original.resampler; _selectedWavtool = _original.wavtool; diff --git a/OpenUtauMobile/ViewModels/SingerDetailViewModel.cs b/OpenUtauMobile/ViewModels/SingerDetailViewModel.cs index 1cf9126d..aafb79e5 100644 --- a/OpenUtauMobile/ViewModels/SingerDetailViewModel.cs +++ b/OpenUtauMobile/ViewModels/SingerDetailViewModel.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Reactive; @@ -148,6 +148,7 @@ await LoadingPopupService.RunAsync( { ToastService.Enqueue(string.Format(L.S("SingerDetail.UninstallSucceeded"), SingerName)); } + Services.ExternalSingerPluginService.RefreshSingers(); SingerUninstalled?.Invoke(_singer); Navigator.NavigateBack(this); } diff --git a/OpenUtauMobile/ViewModels/SplashScreenViewModel.cs b/OpenUtauMobile/ViewModels/SplashScreenViewModel.cs index 4f7ebaab..01724b4e 100644 --- a/OpenUtauMobile/ViewModels/SplashScreenViewModel.cs +++ b/OpenUtauMobile/ViewModels/SplashScreenViewModel.cs @@ -126,6 +126,7 @@ await Task.Run(() => ct.ThrowIfCancellationRequested(); PostToUI(() => { InitState = L.S("Splash.SingerManager"); ProgressPercent = 85; }); SingerManager.Inst.Initialize(); + ExternalSingerPluginService.Initialize(); Stopwatch avatarStopwatch = Stopwatch.StartNew(); int singerCount = 0; foreach (List group in SingerManager.Inst.SingerGroups.Values) diff --git a/OpenUtauMobile/ViewModels/TrackHeaderViewModel.cs b/OpenUtauMobile/ViewModels/TrackHeaderViewModel.cs index c30ea5d8..43d83679 100644 --- a/OpenUtauMobile/ViewModels/TrackHeaderViewModel.cs +++ b/OpenUtauMobile/ViewModels/TrackHeaderViewModel.cs @@ -177,11 +177,11 @@ private void ApplySinger(UProject project, USinger singer) URenderSettings settings = new(); DocManager.Inst.ExecuteCmd(new TrackChangeRenderSettingCommand(DocManager.Inst.Project, _track, settings)); } - else if (singer.SingerType != _track.RendererSettings.Renderer?.SingerType) + else if (!OpenUtauMobile.Services.ExternalSingerPluginService.GetSupportedRenderers(singer).Contains(_track.RendererSettings.renderer)) { URenderSettings settings = new() { - renderer = Renderers.GetDefaultRenderer(singer.SingerType), // 根据歌手类型 + renderer = OpenUtauMobile.Services.ExternalSingerPluginService.GetDefaultRenderer(singer), // 根据歌手类型 }; DocManager.Inst.ExecuteCmd(new TrackChangeRenderSettingCommand(DocManager.Inst.Project, _track, settings)); } @@ -255,7 +255,7 @@ private async Task SelectRenderer() public void SetRenderer(string renderer) { if (!DocManager.Inst.Project.tracks.Contains(_track) || DocManager.Inst.HasOpenUndoGroup || _track.Singer is not { Found: true } singer || - !Renderers.GetSupportedRenderers(singer.SingerType).Contains(renderer) || _track.RendererSettings.renderer == renderer) return; + !OpenUtauMobile.Services.ExternalSingerPluginService.GetSupportedRenderers(singer).Contains(renderer) || _track.RendererSettings.renderer == renderer) return; URenderSettings settings = _track.RendererSettings.Clone(); settings.renderer = renderer; DocManager.Inst.StartUndoGroup(); diff --git a/OpenUtauMobile/ViewModels/TrackSettingsPopupViewModel.cs b/OpenUtauMobile/ViewModels/TrackSettingsPopupViewModel.cs index fd749b43..8d070f29 100644 --- a/OpenUtauMobile/ViewModels/TrackSettingsPopupViewModel.cs +++ b/OpenUtauMobile/ViewModels/TrackSettingsPopupViewModel.cs @@ -229,7 +229,7 @@ public bool TryPrepareApply(out List commands, out bool singerChanged, } else if (singerChanged || IsRenderSettingsDirty) { - string[] supportedRenderers = CoreRenderers.GetSupportedRenderers(singer.SingerType); + string[] supportedRenderers = OpenUtauMobile.Services.ExternalSingerPluginService.GetSupportedRenderers(singer); if (supportedRenderers.Length == 0 || !supportedRenderers.Contains(DraftRenderer, StringComparer.Ordinal)) { error = L.S("TrackSettings.Error.Renderer"); @@ -294,7 +294,7 @@ private void RebuildRendererChoices(bool chooseCompatibleDefault) { Renderers.Clear(); string[] supported = DraftSinger is { Found: true } singer - ? CoreRenderers.GetSupportedRenderers(singer.SingerType) + ? OpenUtauMobile.Services.ExternalSingerPluginService.GetSupportedRenderers(singer) : []; HasNoSupportedRenderers = DraftSinger is { Found: true } && supported.Length == 0; IsRendererEnabled = DraftSinger is { Found: true } && supported.Length > 0; @@ -318,7 +318,7 @@ private void RebuildRendererChoices(bool chooseCompatibleDefault) return; } string preferred; - try { preferred = CoreRenderers.GetDefaultRenderer(DraftSinger!.SingerType); } + try { preferred = OpenUtauMobile.Services.ExternalSingerPluginService.GetDefaultRenderer(DraftSinger!); } catch { preferred = string.Empty; } string fallback = supported.Contains(preferred, StringComparer.Ordinal) ? preferred : supported[0]; DraftRenderer = fallback; From 8885a5713caf676f52687c9077bd430f497ee3c0 Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:00:06 +0800 Subject: [PATCH 02/45] =?UTF-8?q?chore:=20=E6=96=B0=E5=A2=9E=E6=8F=92?= =?UTF-8?q?=E4=BB=B6=E5=A5=91=E7=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 1 + .../Discovery/SingerDiscovery.cs | 63 ++++ .../Forms/PluginFields.cs | 34 ++ .../Forms/PluginValue.cs | 29 ++ .../Installation/ISingerInstallSession.cs | 20 ++ .../Installation/ISingerPackageInstaller.cs | 23 ++ .../Installation/InstallResults.cs | 53 +++ .../Installation/InstallServices.cs | 75 +++++ .../Installation/InstallView.cs | 29 ++ .../OpenUtauMobile.Plugin.Abstractions.csproj | 13 + .../PluginContracts.cs | 51 +++ .../PluginDiagnostic.cs | 25 ++ OpenUtauMobile.Plugin.Abstractions/README.md | 11 + .../Settings/PluginSettings.cs | 60 ++++ .../SingerTypeDescriptor.cs | 20 ++ OpenUtauMobile.sln | 6 + OpenUtauMobile/OpenUtauMobile.csproj | 1 + .../Services/ExternalSingerPluginService.cs | 7 +- .../Services/PluginLoadErrorReporter.cs | 5 + .../SingerPlugins/SingerPluginRegistration.cs | 304 ++++++++++++++++++ .../SingerPlugins/SingerPluginRegistry.cs | 125 +++++++ .../SingerPlugins/SingerPluginService.cs | 96 ++++++ .../SingerPlugins/SingerPluginSnapshot.cs | 30 ++ .../ViewModels/SplashScreenViewModel.cs | 3 + 24 files changed, 1082 insertions(+), 2 deletions(-) create mode 100644 OpenUtauMobile.Plugin.Abstractions/Discovery/SingerDiscovery.cs create mode 100644 OpenUtauMobile.Plugin.Abstractions/Forms/PluginFields.cs create mode 100644 OpenUtauMobile.Plugin.Abstractions/Forms/PluginValue.cs create mode 100644 OpenUtauMobile.Plugin.Abstractions/Installation/ISingerInstallSession.cs create mode 100644 OpenUtauMobile.Plugin.Abstractions/Installation/ISingerPackageInstaller.cs create mode 100644 OpenUtauMobile.Plugin.Abstractions/Installation/InstallResults.cs create mode 100644 OpenUtauMobile.Plugin.Abstractions/Installation/InstallServices.cs create mode 100644 OpenUtauMobile.Plugin.Abstractions/Installation/InstallView.cs create mode 100644 OpenUtauMobile.Plugin.Abstractions/OpenUtauMobile.Plugin.Abstractions.csproj create mode 100644 OpenUtauMobile.Plugin.Abstractions/PluginContracts.cs create mode 100644 OpenUtauMobile.Plugin.Abstractions/PluginDiagnostic.cs create mode 100644 OpenUtauMobile.Plugin.Abstractions/README.md create mode 100644 OpenUtauMobile.Plugin.Abstractions/Settings/PluginSettings.cs create mode 100644 OpenUtauMobile.Plugin.Abstractions/SingerTypeDescriptor.cs create mode 100644 OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistration.cs create mode 100644 OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistry.cs create mode 100644 OpenUtauMobile/Services/SingerPlugins/SingerPluginService.cs create mode 100644 OpenUtauMobile/Services/SingerPlugins/SingerPluginSnapshot.cs diff --git a/AGENTS.md b/AGENTS.md index aef7bb2e..0b9ee714 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,6 +11,7 @@ - Place plans documents in `/plans` where git can ignore them. Do not place plans in the source tree or in the `docs` directory. ## Boundaries and style +- Keep singer plugin infrastructure generic. Do not name or describe specific external plugins or add their dedicated behavior in host code, documentation, or UI. Keep README and UI text concise and actionable. - Forbid modifications to `OpenUtau.Core/Ustx`, which could break compatibility with universal USTX files. - Avoid unnecessary changes to upstream-derived `OpenUtau.Core`; keep application orchestration in the Mobile layer. Always ask for permission before modifying upstream-derived code. - `OpenUtau.Core/Util/Preferences.cs#OpenUtau Mobile特定选项` can be modified. diff --git a/OpenUtauMobile.Plugin.Abstractions/Discovery/SingerDiscovery.cs b/OpenUtauMobile.Plugin.Abstractions/Discovery/SingerDiscovery.cs new file mode 100644 index 00000000..8dd9e8d6 --- /dev/null +++ b/OpenUtauMobile.Plugin.Abstractions/Discovery/SingerDiscovery.cs @@ -0,0 +1,63 @@ +using System.Collections.Immutable; +using System.Globalization; +using OpenUtau.Core.Ustx; + +namespace OpenUtauMobile.Plugin.Abstractions +{ + /// 宿主配置的歌手根目录;读写能力由宿主提供。 + public sealed record SingerRoot(string Id, string Path, bool CanWrite); + + /// 发现项的状态,独立于 USinger.Found/Loaded。 + public enum SingerAvailability + { + Ready, + Unsupported, + Invalid, + MissingResources, + Unavailable, + } + + /// 一次发现的条目;未知稳定身份时 Singer 可为空,但位置与诊断仍可展示。 + public sealed record SingerDiscoveryEntry( + string Location, + string DisplayName, + SingerAvailability Availability, + USinger? Singer = null, + ImmutableArray Diagnostics = default); + + /// 提供方的一次完整或部分发现结果,不要求声库具有统一磁盘清单。 + public sealed record SingerDiscoveryResult( + ImmutableArray Entries, + ImmutableArray Diagnostics = default, + bool IsComplete = true); + + /// 发现阶段的进度;总量未知时 Total 为空。 + public sealed record SingerDiscoveryProgress(string Message, long Completed = 0, long? Total = null); + + /// 发现上下文;具体扫描深度和目录结构由提供方决定。 + public sealed record SingerDiscoveryContext( + ImmutableArray Roots, + CultureInfo Culture, + IPluginSettingsReader Settings, + IPluginLog Log); + + /// 一个由提供方明确允许的维护操作。 + public sealed record SingerMaintenanceAction(string Id, string DisplayName, bool IsDestructive = false); + + /// 提供歌手发现和可选维护能力,不直接修改宿主歌手字典。 + public interface ISingerProvider + { + /// 提供方稳定 ID,使用插件自己的命名空间。 + string Id { get; } + /// 该提供方可能返回的类型 ID。 + ImmutableArray SingerTypeIds { get; } + /// 发现根目录中的条目,按项返回错误,响应取消。 + ValueTask DiscoverAsync(SingerDiscoveryContext context, + IProgress progress, CancellationToken cancellationToken); + /// 声明当前条目的维护能力;默认不允许删除外部目录。 + ImmutableArray GetMaintenanceActions(SingerDiscoveryEntry entry) => []; + /// 执行已由宿主确认的维护操作,默认不提供任何操作。 + ValueTask ExecuteMaintenanceAsync(SingerDiscoveryEntry entry, string actionId, + CancellationToken cancellationToken) => ValueTask.FromException(new NotSupportedException("此提供方没有维护操作。")); + } +} diff --git a/OpenUtauMobile.Plugin.Abstractions/Forms/PluginFields.cs b/OpenUtauMobile.Plugin.Abstractions/Forms/PluginFields.cs new file mode 100644 index 00000000..aa0a8f24 --- /dev/null +++ b/OpenUtauMobile.Plugin.Abstractions/Forms/PluginFields.cs @@ -0,0 +1,34 @@ +using System.Collections.Immutable; + +namespace OpenUtauMobile.Plugin.Abstractions +{ + /// 由宿主现有控件承载的输入种类。 + public enum PluginFieldKind + { + Text, + Boolean, + Number, + Selection, + MultipleSelection, + File, + Directory, + } + + /// 字段选项,身份不随显示语言变化。 + public sealed record PluginFieldOption(string Id, string Label); + + /// 声明式字段;可见状态由插件计算,不解释任意脚本。 + public sealed record PluginFieldDescriptor( + string Id, + string Label, + PluginFieldKind Kind, + PluginValue? DefaultValue = null, + string? Description = null, + bool IsRequired = false, + bool IsVisible = true, + bool IsEnabled = true, + ImmutableArray Options = default, + decimal? Minimum = null, + decimal? Maximum = null, + ImmutableArray FileExtensions = default); +} diff --git a/OpenUtauMobile.Plugin.Abstractions/Forms/PluginValue.cs b/OpenUtauMobile.Plugin.Abstractions/Forms/PluginValue.cs new file mode 100644 index 00000000..d174cf2f --- /dev/null +++ b/OpenUtauMobile.Plugin.Abstractions/Forms/PluginValue.cs @@ -0,0 +1,29 @@ +using System.Collections.Immutable; +using System.Text.Json.Serialization; + +namespace OpenUtauMobile.Plugin.Abstractions +{ + /// 安装表单与设置共享的类型化值,不接受任意 CLR 对象或界面类型。 + [JsonPolymorphic(TypeDiscriminatorPropertyName = "kind")] + [JsonDerivedType(typeof(PluginValue.Text), "text")] + [JsonDerivedType(typeof(PluginValue.Boolean), "boolean")] + [JsonDerivedType(typeof(PluginValue.Number), "number")] + [JsonDerivedType(typeof(PluginValue.Selection), "selection")] + [JsonDerivedType(typeof(PluginValue.MultipleSelection), "multipleSelection")] + [JsonDerivedType(typeof(PluginValue.Path), "path")] + public abstract record PluginValue + { + /// 普通文本。 + public sealed record Text(string Value) : PluginValue; + /// 布尔选择。 + public sealed record Boolean(bool Value) : PluginValue; + /// 有限精度数值。 + public sealed record Number(decimal Value) : PluginValue; + /// 选项稳定 ID。 + public sealed record Selection(string Value) : PluginValue; + /// 多个选项稳定 ID。 + public sealed record MultipleSelection(ImmutableArray Values) : PluginValue; + /// 经宿主选择器解析的本地文件或目录。 + public sealed record Path(string Value, bool IsDirectory) : PluginValue; + } +} diff --git a/OpenUtauMobile.Plugin.Abstractions/Installation/ISingerInstallSession.cs b/OpenUtauMobile.Plugin.Abstractions/Installation/ISingerInstallSession.cs new file mode 100644 index 00000000..99fd52b3 --- /dev/null +++ b/OpenUtauMobile.Plugin.Abstractions/Installation/ISingerInstallSession.cs @@ -0,0 +1,20 @@ +namespace OpenUtauMobile.Plugin.Abstractions +{ + /// 宿主串行驱动的安装会话;临时目录最终由宿主统一清理。 + public interface ISingerInstallSession : IAsyncDisposable + { + /// 初始化分析或返回首个输入步骤,不写正式目录。 + ValueTask AnalyzeAsync(IProgress progress, CancellationToken cancellationToken); + /// 校验当前步骤并前进,错误返回到同一步骤。 + ValueTask NextAsync(InstallSubmission submission, IProgress progress, + CancellationToken cancellationToken); + /// 恢复上一步;过期状态版本必须被拒绝。 + ValueTask BackAsync(long expectedRevision, CancellationToken cancellationToken); + /// 验证最终身份、目标和输入,生成可消费一次的安装计划。 + ValueTask PrepareAsync(InstallTargetSelection target, long expectedRevision, + IProgress progress, CancellationToken cancellationToken); + /// 只提交已经校验的当前计划,不能重新解包替换预检内容。 + ValueTask InstallAsync(Guid planId, IProgress progress, + CancellationToken cancellationToken); + } +} diff --git a/OpenUtauMobile.Plugin.Abstractions/Installation/ISingerPackageInstaller.cs b/OpenUtauMobile.Plugin.Abstractions/Installation/ISingerPackageInstaller.cs new file mode 100644 index 00000000..5cdceba2 --- /dev/null +++ b/OpenUtauMobile.Plugin.Abstractions/Installation/ISingerPackageInstaller.cs @@ -0,0 +1,23 @@ +using System.Collections.Immutable; + +namespace OpenUtauMobile.Plugin.Abstractions +{ + /// 用户手选的安装器描述;扩展名仅用于其文件选择器,可与其他安装器重叠。 + public sealed record SingerInstallerDescriptor( + string Id, + string DisplayName, + ImmutableArray SingerTypeIds, + ImmutableArray Extensions, + string? IconKey = null, + ImmutableArray MimeTypes = default); + + /// 文件包安装器;先选安装器再选文件,不提供自动探测接口。 + public interface ISingerPackageInstaller + { + /// 菜单信息和文件过滤器。 + SingerInstallerDescriptor Descriptor { get; } + /// 在宿主已创建的工作区内创建安装会话。 + ValueTask CreateSessionAsync(SingerInstallContext context, + CancellationToken cancellationToken); + } +} diff --git a/OpenUtauMobile.Plugin.Abstractions/Installation/InstallResults.cs b/OpenUtauMobile.Plugin.Abstractions/Installation/InstallResults.cs new file mode 100644 index 00000000..8be13598 --- /dev/null +++ b/OpenUtauMobile.Plugin.Abstractions/Installation/InstallResults.cs @@ -0,0 +1,53 @@ +using System.Collections.Immutable; + +namespace OpenUtauMobile.Plugin.Abstractions +{ + /// 操作进度的业务阶段,不将未知总量伪造成精确百分比。 + public enum InstallPhase + { + Analyzing, + Extracting, + Validating, + Preparing, + Publishing, + Refreshing, + } + + /// 本会话的进度,总量可以未知。 + public sealed record InstallProgress(InstallPhase Phase, string Message, long Completed = 0, long? Total = null); + + /// 用于刷新后定位歌手的稳定引用。 + public sealed record SingerReference(string ProviderId, string SingerId); + + /// 用户选中的配置内目标,不接受任意绝对路径。 + public sealed record InstallTargetSelection(string TargetId); + + /// 宿主提供的可写安装根目录。 + public sealed record InstallTarget(string Id, string Path, string DisplayName); + + /// 可展示摘要和会话私有计划标识;不序列化插件原生对象。 + public sealed record PreparedInstall(Guid PlanId, long Revision, string InstallerId, string TargetId, + string Summary, ImmutableArray DestinationPaths, ImmutableArray Singers, + ImmutableArray Diagnostics = default, long? RequiredBytes = null); + + /// 提交后状态;未提交的校验失败通过异常返回。 + public enum InstallResultStatus + { + Committed, + PartialFailure, + } + + /// 提交结果;刷新失败不能将已提交文件伪装成没有安装。 + public sealed record InstallResult(InstallResultStatus Status, ImmutableArray Locations, + ImmutableArray Singers, ImmutableArray Diagnostics = default); + + /// 可诊断的安装失败,区别于正常取消。 + public sealed class SingerInstallException(string code, string message, Exception? innerException = null, + string? fieldId = null) : Exception(message, innerException) + { + /// 稳定错误代码,不通过本地化消息判断逻辑。 + public string Code { get; } = code; + /// 可以定位到具体输入字段。 + public string? FieldId { get; } = fieldId; + } +} diff --git a/OpenUtauMobile.Plugin.Abstractions/Installation/InstallServices.cs b/OpenUtauMobile.Plugin.Abstractions/Installation/InstallServices.cs new file mode 100644 index 00000000..b1d040b9 --- /dev/null +++ b/OpenUtauMobile.Plugin.Abstractions/Installation/InstallServices.cs @@ -0,0 +1,75 @@ +using System.Collections.Immutable; +using System.Globalization; + +namespace OpenUtauMobile.Plugin.Abstractions +{ + /// 会话内稳定的包来源;原生读取器只接收物化后的本机路径。 + public interface IInstallSource + { + /// 展示名称,不用于推导歌手身份。 + string DisplayName { get; } + /// 已知长度,无法取得时为空。 + long? Length { get; } + /// 返回独立读取流,调用方负责释放。 + ValueTask OpenReadAsync(CancellationToken cancellationToken); + /// 按需物化一次本地文件,不将 content URI 传入原生代码。 + ValueTask GetLocalPathAsync(CancellationToken cancellationToken); + } + + /// 宿主创建并在 finally 释放的会话缓存。 + public interface IInstallWorkspace + { + /// CachePath/SingerInstall/SessionId 的绝对路径。 + string RootPath { get; } + /// 解析并验证相对路径,不自动创建文件。 + string GetPath(string relativePath); + /// 创建会话内子目录并返回绝对路径。 + string CreateDirectory(string relativePath); + } + + /// 已发现歌手的位置,不代替最终目标文件冲突检查。 + public sealed record InstalledSingerLocation(SingerReference Singer, string Location, SingerAvailability Availability); + + /// 用于安装前身份提示的只读目录查询。 + public interface IInstalledSingerLookup + { + /// 查询全部同身份位置,重复身份按既有 warning 处理。 + ValueTask> FindAsync(SingerReference singer, + CancellationToken cancellationToken); + } + + /// 发布源的种类,不强制插件采用目录型声库。 + public enum InstallArtifactKind + { + File, + Directory, + } + + /// 移动本会话内已校验内容到配置目标;首版不允许覆盖。 + public sealed record PublishRequest(string SourceRelativePath, string TargetId, + string DestinationRelativePath, InstallArtifactKind Kind); + + /// 已完成的正式发布回执,不属于 finally 的临时清理范围。 + public sealed record PublishedLocation(string Path, InstallArtifactKind Kind); + + /// 宿主文件帮助器,不解释专有包格式或声库结构。 + public interface IInstallFileOperations + { + /// 验证解压项只能写入指定会话子目录。 + string ResolveEntryPath(string workspaceDirectory, string entryPath); + /// 同卷移动,跨卷复制校验后移动,记录最终提交回执。 + ValueTask PublishAsync(PublishRequest request, IProgress progress, + CancellationToken cancellationToken); + /// 登记插件额外产生的会话临时路径,由宿主验证范围并清理。 + void RegisterTemporaryPath(string path); + /// 登记插件自行完成的正式发布,用于异常后的真实结果展示。 + void RecordPublishedLocation(PublishedLocation location); + } + + /// 安装器使用的宿主能力;不公开页面或服务容器。 + public sealed record SingerInstallContext(Guid SessionId, CultureInfo Culture, IInstallSource Source, + IInstallWorkspace Workspace, ImmutableArray SingerRoots, + ImmutableArray InstallTargets, string DefaultTargetId, + IInstalledSingerLookup InstalledSingers, IInstallFileOperations Files, + IPluginSettingsReader Settings, IPluginLog Log); +} diff --git a/OpenUtauMobile.Plugin.Abstractions/Installation/InstallView.cs b/OpenUtauMobile.Plugin.Abstractions/Installation/InstallView.cs new file mode 100644 index 00000000..8fdddc9c --- /dev/null +++ b/OpenUtauMobile.Plugin.Abstractions/Installation/InstallView.cs @@ -0,0 +1,29 @@ +using System.Collections.Immutable; + +namespace OpenUtauMobile.Plugin.Abstractions +{ + /// 步骤内容的宿主展示方式。 + public enum InstallContentKind + { + Information, + Image, + License, + FilePreview, + } + + /// 只读内容;图片位置引用会话内相对路径。 + public sealed record InstallContent(InstallContentKind Kind, string Title, string Value); + + /// 动态步骤,数量和分支由安装器决定。 + public sealed record InstallStep(string Id, string Title, ImmutableArray Content, + ImmutableArray Fields, bool IsComplete = false); + + /// 页面数据快照;修改输入会使旧 Revision 和 PlanId 失效。 + public sealed record InstallView(long Revision, ImmutableArray Steps, string CurrentStepId, + bool CanGoBack, bool CanGoNext, bool CanPrepare, + ImmutableArray Diagnostics = default); + + /// 提交指定状态版本的字段值。 + public sealed record InstallSubmission(string StepId, long ExpectedRevision, + ImmutableDictionary Values); +} diff --git a/OpenUtauMobile.Plugin.Abstractions/OpenUtauMobile.Plugin.Abstractions.csproj b/OpenUtauMobile.Plugin.Abstractions/OpenUtauMobile.Plugin.Abstractions.csproj new file mode 100644 index 00000000..d976f81d --- /dev/null +++ b/OpenUtauMobile.Plugin.Abstractions/OpenUtauMobile.Plugin.Abstractions.csproj @@ -0,0 +1,13 @@ + + + net10.0 + enable + enable + 1.0.0 + 1.0.0.0 + OPUM 歌手插件的类型、发现、安装和设置契约。 + + + + + diff --git a/OpenUtauMobile.Plugin.Abstractions/PluginContracts.cs b/OpenUtauMobile.Plugin.Abstractions/PluginContracts.cs new file mode 100644 index 00000000..2032c0ed --- /dev/null +++ b/OpenUtauMobile.Plugin.Abstractions/PluginContracts.cs @@ -0,0 +1,51 @@ +using System.Diagnostics.CodeAnalysis; + +namespace OpenUtauMobile.Plugin.Abstractions +{ + /// 宿主与歌手插件共同遵循的契约版本和数值边界。 + public static class SingerPluginContract + { + /// 当前支持的契约版本。 + public const int Version = 1; + /// 外部类型数值的起点;数值只用于桥接,不作为位标志。 + public const int ExternalTypeMinimum = 0x10000000; + } + + /// 在程序集上声明歌手插件入口;宿主先检查版本,再创建入口实例。 + [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] + public sealed class SingerPluginAttribute( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type entryPoint, + int contractVersion = SingerPluginContract.Version) : Attribute + { + /// 实现 ISingerPlugin 的公开无参入口。 + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] + public Type EntryPoint { get; } = entryPoint; + /// 该入口要求的契约版本。 + public int ContractVersion { get; } = contractVersion; + } + + /// 插件的稳定身份与展示名称。 + public sealed record SingerPluginDescriptor(string Id, string DisplayName); + + /// 只登记能力的插件入口;不得在登记阶段扫描目录或修改工程。 + public interface ISingerPlugin + { + /// 插件身份,不因语言或显示名称改变。 + SingerPluginDescriptor Descriptor { get; } + /// 提交本插件的能力描述;宿主验证全部登记后统一发布。 + void Register(ISingerPluginRegistrar registrar); + } + + /// 宿主收集插件本轮登记,不向插件公开宿主服务容器。 + public interface ISingerPluginRegistrar + { + /// 登记一个独立类型及 renderer 关联。 + void RegisterSingerType(SingerTypeDescriptor descriptor); + /// 登记目录发现提供方,不立即执行发现。 + void RegisterProvider(ISingerProvider provider); + /// 登记由用户手选的文件安装器,不自动探测包内容。 + void RegisterInstaller(ISingerPackageInstaller installer); + /// 登记设置描述和设置操作处理器。 + void RegisterSettings(IPluginSettingsHandler settings); + } +} diff --git a/OpenUtauMobile.Plugin.Abstractions/PluginDiagnostic.cs b/OpenUtauMobile.Plugin.Abstractions/PluginDiagnostic.cs new file mode 100644 index 00000000..e9c89d60 --- /dev/null +++ b/OpenUtauMobile.Plugin.Abstractions/PluginDiagnostic.cs @@ -0,0 +1,25 @@ +namespace OpenUtauMobile.Plugin.Abstractions +{ + /// 诊断的展示级别。 + public enum PluginDiagnosticSeverity + { + Information, + Warning, + Error, + } + + /// 可展示的诊断;代码稳定,消息由插件按当前文化信息生成。 + public sealed record PluginDiagnostic( + string Code, + string Message, + PluginDiagnosticSeverity Severity = PluginDiagnosticSeverity.Error, + string? Location = null, + string? FieldId = null); + + /// 宿主提供的日志入口,自动关联插件及会话身份。 + public interface IPluginLog + { + /// 记录诊断和可选原始异常,不替代界面中的错误展示。 + void Write(PluginDiagnostic diagnostic, Exception? exception = null); + } +} diff --git a/OpenUtauMobile.Plugin.Abstractions/README.md b/OpenUtauMobile.Plugin.Abstractions/README.md new file mode 100644 index 00000000..58c4d7c6 --- /dev/null +++ b/OpenUtauMobile.Plugin.Abstractions/README.md @@ -0,0 +1,11 @@ +# 歌手插件契约 v1 + +插件引用本程序集与 `OpenUtau.Core` 时设置 `Private="false"`,安装包只携带插件自身文件。 + +使用 `[assembly: SingerPlugin(typeof(PluginEntry))]` 声明实现 `ISingerPlugin` 的公开无参入口。在 `Register` 内同步登记类型、发现提供方、安装器和设置,不执行扫描或安装。 + +- 插件 ID 使用小写字母开头,允许数字、点、下划线和短横线;`opum.` 为保留前缀。能力 ID 使用 `:<名称>`。 +- 类型桥接值固定在 `0x10000000` 至 `int.MaxValue` 内,宿主检查冲突。 +- 可用类型的 renderer 工厂须与入口同程序集;类型值、renderer 集合和默认值须与 Core 一致。不可用类型填写原因,renderer 集合与默认值留空。 +- 安装器声明文件后缀,由用户先选安装器再选包;后缀允许重叠。 +- 可选集合的默认值按空集合处理。登记失败不发布本批能力;替换插件需要重启。 diff --git a/OpenUtauMobile.Plugin.Abstractions/Settings/PluginSettings.cs b/OpenUtauMobile.Plugin.Abstractions/Settings/PluginSettings.cs new file mode 100644 index 00000000..45974d9e --- /dev/null +++ b/OpenUtauMobile.Plugin.Abstractions/Settings/PluginSettings.cs @@ -0,0 +1,60 @@ +using System.Collections.Immutable; + +namespace OpenUtauMobile.Plugin.Abstractions +{ + /// 设置成功保存后的实际生效方式。 + public enum PluginSettingApplication + { + Immediate, + ReloadResources, + Restart, + } + + /// 设置字段及其生效策略,与临时安装输入分离。 + public sealed record PluginSettingDescriptor(PluginFieldDescriptor Field, + PluginSettingApplication Application = PluginSettingApplication.Restart); + + /// 明确执行的设置操作,不作为持久化字段值。 + public sealed record PluginSettingsAction(string Id, string DisplayName, bool IsDestructive = false, + ImmutableArray Fields = default); + + /// 插件设置描述,配置按插件隔离并携带数据版本。 + public sealed record PluginSettingsDescriptor(int SchemaVersion, string DisplayName, + ImmutableArray Fields, ImmutableArray Actions = default); + + /// 只读设置快照,安装及发现不能借此改动全局配置。 + public interface IPluginSettingsReader + { + /// 已保存配置的数据版本。 + int SchemaVersion { get; } + /// 获取当前插件的类型化设置。 + bool TryGet(string key, out PluginValue? value); + } + + /// 设置保存或操作的校验结果。 + public sealed record PluginSettingsValidation(ImmutableArray Diagnostics) + { + /// 存在错误时宿主不能提交草稿。 + public bool IsValid => Diagnostics.IsDefaultOrEmpty || Diagnostics.All(item => item.Severity != PluginDiagnosticSeverity.Error); + } + + /// 插件提供的设置校验及操作,不自行持久化宿主设置文件。 + public interface IPluginSettingsHandler + { + /// 设置分组、字段与操作。 + PluginSettingsDescriptor Descriptor { get; } + /// 保存前校验完整草稿,实际持久化由宿主完成。 + ValueTask ValidateAsync(ImmutableDictionary values, + CancellationToken cancellationToken); + /// 将旧数据转换到当前版本,保留需要延续的未知字段。 + ImmutableDictionary Upgrade(int previousVersion, + ImmutableDictionary values); + /// 执行用户明确触发的导入、检查等操作,资源上下文由宿主提供。 + ValueTask ExecuteAsync(string actionId, PluginSettingsOperationContext context, + IProgress progress, CancellationToken cancellationToken); + } + + /// 设置操作的输入与资源目录;文件输入由宿主按声明字段选择。 + public sealed record PluginSettingsOperationContext(string ResourceDirectory, IInstallWorkspace Workspace, + ImmutableDictionary Values, IPluginLog Log); +} diff --git a/OpenUtauMobile.Plugin.Abstractions/SingerTypeDescriptor.cs b/OpenUtauMobile.Plugin.Abstractions/SingerTypeDescriptor.cs new file mode 100644 index 00000000..4482bab6 --- /dev/null +++ b/OpenUtauMobile.Plugin.Abstractions/SingerTypeDescriptor.cs @@ -0,0 +1,20 @@ +using System.Collections.Immutable; +using OpenUtau.Core.Ustx; + +namespace OpenUtauMobile.Plugin.Abstractions +{ + /// 类型标识的明暗颜色;采用 ARGB 数值,不依赖界面画刷。 + public sealed record SingerTypeColor(uint LightArgb, uint DarkArgb); + + /// 可动态登记的类型;不可用占位类型不得发布可合成歌手。 + public sealed record SingerTypeDescriptor( + string Id, + USingerType BridgeValue, + string DisplayName, + ImmutableArray RendererIds, + string? DefaultRendererId, + SingerTypeColor? Color = null, + bool IsAvailable = true, + string? UnavailableReason = null, + ImmutableDictionary? LocalizedNames = null); +} diff --git a/OpenUtauMobile.sln b/OpenUtauMobile.sln index a864508f..959e507b 100644 --- a/OpenUtauMobile.sln +++ b/OpenUtauMobile.sln @@ -31,6 +31,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenUtauMobile.Linux", "Ope EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenUtauMobile.DesktopUI", "OpenUtauMobile.DesktopUI\OpenUtauMobile.DesktopUI.csproj", "{65E3BDF7-152B-4109-A38C-4A7B9BF4C28B}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenUtauMobile.Plugin.Abstractions", "OpenUtauMobile.Plugin.Abstractions\OpenUtauMobile.Plugin.Abstractions.csproj", "{CCE36B7B-66C7-4C10-A819-CB23490885B5}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -97,6 +99,10 @@ Global {65E3BDF7-152B-4109-A38C-4A7B9BF4C28B}.Debug|Any CPU.Build.0 = Debug|Any CPU {65E3BDF7-152B-4109-A38C-4A7B9BF4C28B}.Release|Any CPU.ActiveCfg = Release|Any CPU {65E3BDF7-152B-4109-A38C-4A7B9BF4C28B}.Release|Any CPU.Build.0 = Release|Any CPU + {CCE36B7B-66C7-4C10-A819-CB23490885B5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CCE36B7B-66C7-4C10-A819-CB23490885B5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CCE36B7B-66C7-4C10-A819-CB23490885B5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CCE36B7B-66C7-4C10-A819-CB23490885B5}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/OpenUtauMobile/OpenUtauMobile.csproj b/OpenUtauMobile/OpenUtauMobile.csproj index 7c446f2a..3f17832c 100644 --- a/OpenUtauMobile/OpenUtauMobile.csproj +++ b/OpenUtauMobile/OpenUtauMobile.csproj @@ -45,5 +45,6 @@ + diff --git a/OpenUtauMobile/Services/ExternalSingerPluginService.cs b/OpenUtauMobile/Services/ExternalSingerPluginService.cs index 5bdeea35..4dd7b3d6 100644 --- a/OpenUtauMobile/Services/ExternalSingerPluginService.cs +++ b/OpenUtauMobile/Services/ExternalSingerPluginService.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Reflection; using OpenUtau.Core.Ustx; +using OpenUtauMobile.Services.SingerPlugins; using Serilog; namespace OpenUtauMobile.Services; @@ -18,6 +19,7 @@ public static class ExternalSingerPluginService /// 在核心歌手首次扫描后、工程载入前调用插件的约定入口。 public static void Initialize() { + SingerPluginService.Initialize(); foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (initialized.Contains(assembly)) continue; @@ -54,14 +56,15 @@ public static string[] GetSupportedRenderers(USinger singer) { foreach (Func policy in policies) if (policy(singer) is { } options) return options; - return OpenUtau.Core.Render.Renderers.GetSupportedRenderers(singer.SingerType); + return SingerPluginService.Registry.GetSupportedRenderers(singer.SingerType); } /// 返回具体歌手的默认渲染器。 public static string GetDefaultRenderer(USinger singer) { string[] options = GetSupportedRenderers(singer); - string preferred = OpenUtau.Core.Render.Renderers.GetDefaultRenderer(singer.SingerType); + if (options.Length == 0) return string.Empty; + string preferred = SingerPluginService.Registry.GetDefaultRenderer(singer.SingerType); return options.Contains(preferred) ? preferred : options.FirstOrDefault() ?? string.Empty; } diff --git a/OpenUtauMobile/Services/PluginLoadErrorReporter.cs b/OpenUtauMobile/Services/PluginLoadErrorReporter.cs index f199a294..03e16f89 100644 --- a/OpenUtauMobile/Services/PluginLoadErrorReporter.cs +++ b/OpenUtauMobile/Services/PluginLoadErrorReporter.cs @@ -42,6 +42,11 @@ public void Emit(LogEvent logEvent) case "Failed to search plugins.": _pendingErrors.Enqueue(new IOException(PathManager.Inst.PluginsPath, logEvent.Exception)); break; + case "Failed to initialize singer plugin {Assembly}": + string location = logEvent.Properties.TryGetValue("Assembly", out LogEventPropertyValue? assembly) + && assembly is ScalarValue { Value: string path } ? path : PathManager.Inst.PluginsPath; + _pendingErrors.Enqueue(new IOException(location, logEvent.Exception)); + break; } } diff --git a/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistration.cs b/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistration.cs new file mode 100644 index 00000000..f9040a36 --- /dev/null +++ b/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistration.cs @@ -0,0 +1,304 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection; +using OpenUtau.Core.Render; +using OpenUtau.Core.Ustx; +using OpenUtauMobile.Plugin.Abstractions; + +namespace OpenUtauMobile.Services.SingerPlugins +{ + /// 短生命周期登记收集器;关闭后拒绝插件保留引用继续追加。 + internal sealed class SingerPluginRegistration : ISingerPluginRegistrar + { + private readonly SingerPluginDescriptor plugin; + private readonly Assembly assembly; + private readonly Dictionary types = new(StringComparer.Ordinal); + private readonly Dictionary providers = new(StringComparer.Ordinal); + private readonly Dictionary installers = new(StringComparer.Ordinal); + private readonly int registrationThread = Environment.CurrentManagedThreadId; + private bool closed; + + internal IReadOnlyCollection Types => types.Values; + internal IReadOnlyCollection Providers => providers.Values; + internal IReadOnlyCollection Installers => installers.Values; + internal RegisteredPluginSettings? Settings { get; private set; } + + internal SingerPluginRegistration(SingerPluginDescriptor plugin, Assembly assembly) + { + RequireId(plugin.Id); + RequireText(plugin.DisplayName, "插件名称"); + if (plugin.Id.Contains(':') || plugin.Id.StartsWith("opum.", StringComparison.Ordinal)) + { + throw new InvalidOperationException("插件 ID 不能包含冒号或使用宿主保留前缀 opum.。"); + } + this.plugin = plugin; + this.assembly = assembly; + } + + /// 固定类型描述;值类型集合不会随插件后续代码改变。 + public void RegisterSingerType(SingerTypeDescriptor descriptor) + { + RequireOpen(); + ArgumentNullException.ThrowIfNull(descriptor); + RequireOwnedId(descriptor.Id); + RequireText(descriptor.DisplayName, "类型名称"); + if ((int)descriptor.BridgeValue < SingerPluginContract.ExternalTypeMinimum) + { + throw new InvalidOperationException($"类型 {descriptor.Id} 的桥接值不在外部区间。"); + } + descriptor = descriptor with + { + RendererIds = OrEmpty(descriptor.RendererIds), + LocalizedNames = descriptor.LocalizedNames?.WithComparers(StringComparer.OrdinalIgnoreCase), + }; + Add(types, descriptor.Id, new(plugin.Id, descriptor)); + } + + /// 捕获提供方身份,不在登记阶段扫描声库。 + public void RegisterProvider(ISingerProvider provider) + { + RequireOpen(); + ArgumentNullException.ThrowIfNull(provider); + string id = provider.Id; + RequireOwnedId(id); + Add(providers, id, new(plugin.Id, id, OrEmpty(provider.SingerTypeIds), provider)); + } + + /// 捕获文件选择器描述,允许不同安装器使用相同后缀。 + public void RegisterInstaller(ISingerPackageInstaller installer) + { + RequireOpen(); + ArgumentNullException.ThrowIfNull(installer); + SingerInstallerDescriptor descriptor = installer.Descriptor + ?? throw new InvalidOperationException("安装器缺少描述。"); + RequireOwnedId(descriptor.Id); + RequireText(descriptor.DisplayName, "安装器名称"); + ImmutableArray extensions = OrEmpty(descriptor.Extensions); + if (extensions.IsEmpty || extensions.Any(extension => !IsValidExtension(extension))) + { + throw new InvalidOperationException($"安装器 {descriptor.Id} 的文件后缀无效。"); + } + descriptor = descriptor with + { + Extensions = extensions.Select(extension => extension.ToLowerInvariant()).Distinct(StringComparer.Ordinal).ToImmutableArray(), + SingerTypeIds = OrEmpty(descriptor.SingerTypeIds), + MimeTypes = OrEmpty(descriptor.MimeTypes), + }; + foreach (string mime in descriptor.MimeTypes) + { + RequireText(mime, "MIME 类型"); + if (!mime.Contains('/') || mime.Any(char.IsWhiteSpace)) + { + throw new InvalidOperationException($"无效的 MIME 类型:{mime}"); + } + } + Add(installers, descriptor.Id, new(plugin.Id, descriptor, installer)); + } + + /// 每个插件登记一个设置分组;描述中没有任意控件或脚本。 + public void RegisterSettings(IPluginSettingsHandler settings) + { + RequireOpen(); + ArgumentNullException.ThrowIfNull(settings); + if (Settings != null) + { + throw new InvalidOperationException("同一插件只能登记一个设置分组。"); + } + PluginSettingsDescriptor descriptor = settings.Descriptor + ?? throw new InvalidOperationException("设置缺少描述。"); + RequireText(descriptor.DisplayName, "设置名称"); + if (descriptor.SchemaVersion < 1) + { + throw new InvalidOperationException("设置数据版本必须为正整数。"); + } + ImmutableArray fields = OrEmpty(descriptor.Fields); + ValidateFields(fields.Select(field => field.Field)); + if (fields.Any(field => !Enum.IsDefined(field.Application))) + { + throw new InvalidOperationException("设置包含未知生效方式。"); + } + ImmutableArray actions = OrEmpty(descriptor.Actions); + RequireDistinct(actions.Select(action => action.Id), "设置操作"); + foreach (PluginSettingsAction action in actions) + { + RequireId(action.Id); + RequireText(action.DisplayName, "设置操作名称"); + ValidateFields(OrEmpty(action.Fields)); + } + Settings = new(plugin.Id, descriptor with { Fields = fields, Actions = actions }, settings); + } + + internal void Close() => closed = true; + + /// 校验整批引用与工厂;允许先登记提供方再登记类型。 + internal void Validate() + { + RequireDistinct(types.Values.Select(type => type.Descriptor.BridgeValue), "类型桥接值"); + foreach (RegisteredSingerType type in types.Values) + { + ValidateRenderers(type.Descriptor); + } + foreach (RegisteredSingerProvider provider in providers.Values) + { + ValidateTypeReferences(provider.SingerTypeIds, provider.Id); + } + foreach (RegisteredSingerInstaller installer in installers.Values) + { + ValidateTypeReferences(installer.Descriptor.SingerTypeIds, installer.Descriptor.Id); + } + } + + /// Core 默认选择不能被宿主描述覆盖,因此登记时要求二者一致。 + private void ValidateRenderers(SingerTypeDescriptor type) + { + RequireDistinct(type.RendererIds, "渲染器 ID"); + if (!type.IsAvailable) + { + RequireText(type.UnavailableReason, "不可用原因"); + if (!type.RendererIds.IsEmpty || type.DefaultRendererId != null) + { + throw new InvalidOperationException($"不可用类型 {type.Id} 不能声明可选渲染器。"); + } + return; + } + if (type.RendererIds.IsEmpty || type.DefaultRendererId == null || !type.RendererIds.Contains(type.DefaultRendererId)) + { + throw new InvalidOperationException($"类型 {type.Id} 缺少有效默认渲染器。"); + } + string[] coreIds = Renderers.GetSupportedRenderers(type.BridgeValue); + if (!coreIds.ToHashSet(StringComparer.Ordinal).SetEquals(type.RendererIds) + || Renderers.GetDefaultRenderer(type.BridgeValue) != type.DefaultRendererId) + { + throw new InvalidOperationException($"类型 {type.Id} 的渲染器声明与 Core 工厂或默认顺序不一致。"); + } + foreach (string id in type.RendererIds) + { + RequireText(id, "渲染器 ID"); + IRenderer renderer = Renderers.GetOrCreate(id) + ?? throw new InvalidOperationException($"无法创建渲染器 {id}。"); + if (renderer.SingerType != type.BridgeValue || renderer.GetType().Assembly != assembly) + { + throw new InvalidOperationException($"渲染器 {id} 的类型值或所属程序集与插件不一致。"); + } + } + } + + private void ValidateTypeReferences(ImmutableArray ids, string owner) + { + if (ids.IsEmpty || ids.Any(id => id == null || !types.ContainsKey(id))) + { + throw new InvalidOperationException($"{owner} 必须引用本插件已登记的歌手类型。"); + } + RequireDistinct(ids, "引用类型 ID"); + } + + private void RequireOwnedId(string id) + { + RequireId(id); + if (!id.StartsWith(plugin.Id + ":", StringComparison.Ordinal) || id.Length == plugin.Id.Length + 1) + { + throw new InvalidOperationException($"能力 ID {id} 必须位于 {plugin.Id}: 命名空间。"); + } + } + + private void RequireOpen() + { + if (closed || Environment.CurrentManagedThreadId != registrationThread) + { + throw new InvalidOperationException("只能在 Register 的同步调用范围内登记能力。"); + } + } + + private static void RequireId(string id) + { + if (string.IsNullOrEmpty(id) || id.Length > 160 || !char.IsAsciiLetterLower(id[0]) + || id.Any(character => !char.IsAsciiLetterLower(character) && !char.IsAsciiDigit(character) + && character is not '.' and not '-' and not '_' and not ':')) + { + throw new InvalidOperationException($"无效的稳定 ID:{id}"); + } + } + + private static void RequireText(string? text, string name) + { + if (string.IsNullOrWhiteSpace(text)) + { + throw new InvalidOperationException($"{name} 不能为空。"); + } + } + + private static void RequireDistinct(IEnumerable values, string name) + { + HashSet seen = []; + foreach (T value in values) + { + if (!seen.Add(value)) + { + throw new InvalidOperationException($"{name} 重复:{value}"); + } + } + } + + private static void Add(Dictionary items, string id, T value) + { + if (!items.TryAdd(id, value)) + { + throw new InvalidOperationException($"同批能力 ID 重复:{id}"); + } + } + + private static ImmutableArray OrEmpty(ImmutableArray items) => items.IsDefault ? [] : items; + + private static bool IsValidExtension(string extension) + { + return !string.IsNullOrWhiteSpace(extension) && extension.StartsWith('.') + && extension[1..].Split('.').All(part => part.Length > 0 && part.All(char.IsAsciiLetterOrDigit)); + } + + /// 在注册边界拒绝无法由宿主表单表达的字段描述。 + private static void ValidateFields(IEnumerable fields) + { + HashSet ids = new(StringComparer.Ordinal); + foreach (PluginFieldDescriptor field in fields) + { + RequireId(field.Id); + RequireText(field.Label, "字段名称"); + if (!ids.Add(field.Id) || !Enum.IsDefined(field.Kind) || field.Minimum > field.Maximum) + { + throw new InvalidOperationException($"无效或重复的字段:{field.Id}"); + } + ImmutableArray options = OrEmpty(field.Options); + if (OrEmpty(field.FileExtensions).Any(extension => !IsValidExtension(extension))) + { + throw new InvalidOperationException($"字段 {field.Id} 包含无效文件后缀。"); + } + RequireDistinct(options.Select(option => option.Id), "选项 ID"); + foreach (PluginFieldOption option in options) + { + RequireText(option.Id, "选项 ID"); + RequireText(option.Label, "选项名称"); + } + bool valueMatches = field.DefaultValue switch + { + null => true, + PluginValue.Text => field.Kind == PluginFieldKind.Text, + PluginValue.Boolean => field.Kind == PluginFieldKind.Boolean, + PluginValue.Number number => field.Kind == PluginFieldKind.Number + && (!field.Minimum.HasValue || number.Value >= field.Minimum.Value) + && (!field.Maximum.HasValue || number.Value <= field.Maximum.Value), + PluginValue.Selection selection => field.Kind == PluginFieldKind.Selection && options.Any(option => option.Id == selection.Value), + PluginValue.MultipleSelection selection => field.Kind == PluginFieldKind.MultipleSelection + && OrEmpty(selection.Values).All(value => options.Any(option => option.Id == value)), + PluginValue.Path path => path.IsDirectory ? field.Kind == PluginFieldKind.Directory : field.Kind == PluginFieldKind.File, + _ => false, + }; + if (!valueMatches || (field.Kind is PluginFieldKind.Selection or PluginFieldKind.MultipleSelection && options.IsEmpty)) + { + throw new InvalidOperationException($"字段 {field.Id} 的默认值或选项与类型不符。"); + } + } + } + } +} diff --git a/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistry.cs b/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistry.cs new file mode 100644 index 00000000..1353cc66 --- /dev/null +++ b/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistry.cs @@ -0,0 +1,125 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection; +using System.Threading; +using OpenUtau.Core.Render; +using OpenUtau.Core.Ustx; +using OpenUtauMobile.Plugin.Abstractions; + +namespace OpenUtauMobile.Services.SingerPlugins +{ + /// 持有歌手能力快照,单个插件通过全部校验后才发布登记。 + public sealed class SingerPluginRegistry + { + private readonly object gate = new(); + private SingerPluginSnapshot snapshot = CreateBuiltinSnapshot(); + + /// 不可变的当前能力目录;不会暴露尚未提交的插件。 + public SingerPluginSnapshot Snapshot => Volatile.Read(ref snapshot); + + /// 收集并提交插件;插件代码在提交锁之外执行,避免锁内回调。 + internal void Register(ISingerPlugin plugin, Assembly assembly) + { + SingerPluginDescriptor descriptor = plugin.Descriptor + ?? throw new InvalidOperationException("插件没有身份描述。"); + SingerPluginRegistration batch = new(descriptor, assembly); + try + { + plugin.Register(batch); + } + finally + { + batch.Close(); + } + batch.Validate(); + lock (gate) + { + SingerPluginSnapshot current = snapshot; + RequireUnique(current.Plugins.ContainsKey(descriptor.Id), "插件 ID", descriptor.Id); + foreach (RegisteredSingerType type in batch.Types) + { + RequireUnique(current.Types.ContainsKey(type.Descriptor.Id), "类型 ID", type.Descriptor.Id); + RequireUnique(current.TypesByBridge.ContainsKey(type.Descriptor.BridgeValue), + "类型桥接值", ((int)type.Descriptor.BridgeValue).ToString()); + } + foreach (RegisteredSingerProvider provider in batch.Providers) + { + RequireUnique(current.Providers.ContainsKey(provider.Id), "提供方 ID", provider.Id); + } + foreach (RegisteredSingerInstaller installer in batch.Installers) + { + RequireUnique(current.Installers.ContainsKey(installer.Descriptor.Id), "安装器 ID", installer.Descriptor.Id); + } + + // 所有构造都成功后才替换快照,失败不会遗留半个插件的能力。 + SingerPluginSnapshot next = new( + current.Plugins.Add(descriptor.Id, descriptor), + current.Types.AddRange(batch.Types.Select(type => new KeyValuePair(type.Descriptor.Id, type))), + current.TypesByBridge.AddRange(batch.Types.Select(type => new KeyValuePair(type.Descriptor.BridgeValue, type))), + current.Providers.AddRange(batch.Providers.Select(provider => new KeyValuePair(provider.Id, provider))), + current.Installers.AddRange(batch.Installers.Select(installer => new KeyValuePair(installer.Descriptor.Id, installer))), + batch.Settings is { } settings ? current.Settings.Add(descriptor.Id, settings) : current.Settings); + Volatile.Write(ref snapshot, next); + } + } + + /// 按已验证类型返回渲染器;不可用或未登记类型返回空数组。 + public string[] GetSupportedRenderers(USingerType bridge) + { + if (!Snapshot.TypesByBridge.TryGetValue(bridge, out RegisteredSingerType? type) || !type.Descriptor.IsAvailable) + { + return []; + } + return type.PluginId == "opum.builtin" + ? Renderers.GetSupportedRenderers(bridge).ToArray() + : type.Descriptor.RendererIds.ToArray(); + } + + /// 安全取得默认渲染器,保留 Classic 的宿主偏好。 + public string GetDefaultRenderer(USingerType bridge) + { + SingerPluginSnapshot current = Snapshot; + if (!current.TypesByBridge.TryGetValue(bridge, out RegisteredSingerType? type) || !type.Descriptor.IsAvailable) + { + return string.Empty; + } + return type.PluginId == "opum.builtin" + ? Renderers.GetDefaultRenderer(bridge) + : type.Descriptor.DefaultRendererId ?? string.Empty; + } + + private static void RequireUnique(bool exists, string kind, string id) + { + if (exists) + { + throw new InvalidOperationException($"{kind} 冲突:{id}"); + } + } + + /// 固定内置身份,不把已加载的第三方 renderer 纳入内置描述。 + private static SingerPluginSnapshot CreateBuiltinSnapshot() + { + SingerTypeDescriptor[] descriptors = + [ + new("builtin:utau", USingerType.Classic, "UTAU", + [Renderers.WORLDLINE_R, Renderers.WORLDLINE_R11, Renderers.WORLDLINE_R2, Renderers.CLASSIC], Renderers.WORLDLINE_R), + new("builtin:enunu", USingerType.Enunu, "ENUNU", [Renderers.ENUNU], Renderers.ENUNU), + new("builtin:vogen", USingerType.Vogen, "Vogen", [Renderers.VOGEN], Renderers.VOGEN), + new("builtin:diffsinger", USingerType.DiffSinger, "DiffSinger", [Renderers.DIFFSINGER], Renderers.DIFFSINGER), + new("builtin:voicevox", USingerType.Voicevox, "VOICEVOX", [Renderers.VOICEVOX], Renderers.VOICEVOX), + new("builtin:neutrino", USingerType.Neutrino, "NEUTRINO", [Renderers.NEUTRINO], Renderers.NEUTRINO), + ]; + RegisteredSingerType[] types = descriptors.Select(descriptor => new RegisteredSingerType("opum.builtin", descriptor)).ToArray(); + return new( + ImmutableDictionary.Empty.WithComparers(StringComparer.Ordinal) + .Add("opum.builtin", new("opum.builtin", "OpenUtau Mobile")), + types.ToImmutableDictionary(type => type.Descriptor.Id, StringComparer.Ordinal), + types.ToImmutableDictionary(type => type.Descriptor.BridgeValue), + ImmutableDictionary.Empty.WithComparers(StringComparer.Ordinal), + ImmutableDictionary.Empty.WithComparers(StringComparer.Ordinal), + ImmutableDictionary.Empty.WithComparers(StringComparer.Ordinal)); + } + } +} diff --git a/OpenUtauMobile/Services/SingerPlugins/SingerPluginService.cs b/OpenUtauMobile/Services/SingerPlugins/SingerPluginService.cs new file mode 100644 index 00000000..2ce020de --- /dev/null +++ b/OpenUtauMobile/Services/SingerPlugins/SingerPluginService.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reflection; +using OpenUtauMobile.Plugin.Abstractions; +using Serilog; + +namespace OpenUtauMobile.Services.SingerPlugins +{ + /// 加载版本化歌手入口,隔离失败插件,不执行发现、安装或设置操作。 + public static class SingerPluginService + { + private static readonly object gate = new(); + private static readonly HashSet attempted = []; + private static ImmutableArray diagnostics = []; + + /// 供 Mobile 各子系统读取的统一能力目录。 + public static SingerPluginRegistry Registry { get; } = new(); + + /// 登记失败的诊断快照,保留程序集位置与原始错误消息。 + public static ImmutableArray Diagnostics + { + get + { + lock (gate) + { + return diagnostics; + } + } + } + + /// 在 Core 扫描外部 DLL 前固定契约依赖的程序集身份。 + public static void EnsureContractsLoaded() + { + _ = typeof(ISingerPlugin).Assembly.GetName(); + } + + /// 在歌手首次发现及工程恢复之前调用;重复调用不会重新实例化入口。 + public static void Initialize() + { + EnsureContractsLoaded(); + foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) + { + if (assembly.IsDynamic) + { + continue; + } + lock (gate) + { + if (!attempted.Add(assembly)) + { + continue; + } + } + try + { + SingerPluginAttribute? attribute = assembly.GetCustomAttribute(); + if (attribute == null) + { + if (assembly.GetCustomAttributesData().Any(data => data.AttributeType.FullName == typeof(SingerPluginAttribute).FullName)) + { + throw new InvalidOperationException("插件使用了另一份契约程序集,请引用宿主提供的 OpenUtauMobile.Plugin.Abstractions。"); + } + continue; + } + // 必须在创建插件实例和调用任何插件方法之前验证契约版本。 + if (attribute.ContractVersion != SingerPluginContract.Version) + { + throw new NotSupportedException($"歌手插件契约版本 {attribute.ContractVersion} 不受支持,宿主版本为 {SingerPluginContract.Version}。"); + } + Type entry = attribute.EntryPoint; + if (entry.Assembly != assembly || !entry.IsVisible || entry.IsAbstract || entry.ContainsGenericParameters + || !typeof(ISingerPlugin).IsAssignableFrom(entry) || entry.GetConstructor(Type.EmptyTypes) == null) + { + throw new InvalidOperationException("歌手插件入口必须是当前程序集内实现 ISingerPlugin 的公开非抽象类型,并有公开无参构造函数。"); + } + ISingerPlugin plugin = (ISingerPlugin)Activator.CreateInstance(entry)!; + Registry.Register(plugin, assembly); + } + catch (Exception exception) + { + Exception error = exception is TargetInvocationException { InnerException: { } inner } ? inner : exception; + string location = assembly.Location; + PluginDiagnostic diagnostic = new("plugin.registration.failed", error.Message, + Location: string.IsNullOrEmpty(location) ? assembly.FullName : location); + lock (gate) + { + diagnostics = diagnostics.Add(diagnostic); + } + Log.Error(error, "Failed to initialize singer plugin {Assembly}", diagnostic.Location); + } + } + } + } +} diff --git a/OpenUtauMobile/Services/SingerPlugins/SingerPluginSnapshot.cs b/OpenUtauMobile/Services/SingerPlugins/SingerPluginSnapshot.cs new file mode 100644 index 00000000..06657fa9 --- /dev/null +++ b/OpenUtauMobile/Services/SingerPlugins/SingerPluginSnapshot.cs @@ -0,0 +1,30 @@ +using System.Collections.Immutable; +using OpenUtau.Core.Ustx; +using OpenUtauMobile.Plugin.Abstractions; + +namespace OpenUtauMobile.Services.SingerPlugins +{ + /// 归属明确的歌手类型;内置类型的 PluginId 固定为 opum.builtin。 + public sealed record RegisteredSingerType(string PluginId, SingerTypeDescriptor Descriptor); + + /// 登记时固定身份与类型范围的发现提供方。 + public sealed record RegisteredSingerProvider(string PluginId, string Id, + ImmutableArray SingerTypeIds, ISingerProvider Instance); + + /// 登记时固定描述的文件安装器。 + public sealed record RegisteredSingerInstaller(string PluginId, SingerInstallerDescriptor Descriptor, + ISingerPackageInstaller Instance); + + /// 登记时固定描述的插件设置处理器。 + public sealed record RegisteredPluginSettings(string PluginId, PluginSettingsDescriptor Descriptor, + IPluginSettingsHandler Instance); + + /// 一次性发布的能力目录;消费者应持有同一快照完成查询。 + public sealed record SingerPluginSnapshot( + ImmutableDictionary Plugins, + ImmutableDictionary Types, + ImmutableDictionary TypesByBridge, + ImmutableDictionary Providers, + ImmutableDictionary Installers, + ImmutableDictionary Settings); +} diff --git a/OpenUtauMobile/ViewModels/SplashScreenViewModel.cs b/OpenUtauMobile/ViewModels/SplashScreenViewModel.cs index 01724b4e..7f81d199 100644 --- a/OpenUtauMobile/ViewModels/SplashScreenViewModel.cs +++ b/OpenUtauMobile/ViewModels/SplashScreenViewModel.cs @@ -16,6 +16,7 @@ using OpenUtauMobile.Helpers; using OpenUtauMobile.Services; using OpenUtauMobile.Services.Dialogs; +using OpenUtauMobile.Services.SingerPlugins; using OpenUtauMobile.Themes.OpenUtauMobile.Runtime; using ReactiveUI.Fody.Helpers; using Serilog; @@ -106,6 +107,7 @@ await Task.Run(() => ct.ThrowIfCancellationRequested(); PostToUI(() => { InitState = L.S("Splash.DocManager"); ProgressPercent = 42; }); int pendingDeletionFailures = PluginManagementService.ApplyPendingDeletions(); + SingerPluginService.EnsureContractsLoaded(); DocManager.Inst.Initialize(mainThread, mainScheduler); GlobalErrorSubscriber.Instance.Register(); Log.Information("DocManager初始化完成"); @@ -114,6 +116,7 @@ await Task.Run(() => ct.ThrowIfCancellationRequested(); PostToUI(() => { InitState = L.S("Splash.Phonemizer"); ProgressPercent = 57; }); EnsureBuiltinLoaded(); + SingerPluginService.Initialize(); Log.Information("插件加载完成"); // ---- 阶段 5:ToolManager ---- From 845ab23cba217dea27deb8e1e735bf7276a3e0df Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Sun, 1 Nov 2026 00:52:59 +0800 Subject: [PATCH 03/45] =?UTF-8?q?chore:=20=E9=87=8D=E6=9E=84=E6=AD=8C?= =?UTF-8?q?=E6=89=8B=E5=AE=89=E8=A3=85=E6=B5=81=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 2 + OpenUtau.Core/Vogen/VogenSingerLoader.cs | 2 +- .../Views/DesktopPageLocator.cs | 4 +- .../Views/DesktopPresentationCatalog.cs | 10 +- .../Views/DesktopShell.cs | 7 +- .../Views/DesktopSingerDetailPage.axaml | 2 +- .../Views/DesktopSingerPage.cs | 14 +- .../Views/DesktopSingerSetupPage.axaml | 220 --------- .../Views/DesktopSingerSetupPage.axaml.cs | 90 +--- .../Installation/ISingerInstallSession.cs | 2 +- OpenUtauMobile.Plugin.Abstractions/README.md | 2 + OpenUtauMobile/Assets/Lang/Strings.en.resx | 19 + OpenUtauMobile/Assets/Lang/Strings.ja.resx | 19 + OpenUtauMobile/Assets/Lang/Strings.ru.resx | 19 + OpenUtauMobile/Assets/Lang/Strings.uk.resx | 19 + .../Assets/Lang/Strings.zh-Hans.resx | 19 + .../Controls/ArrangementSurface.axaml | 262 ++++++----- OpenUtauMobile/Controls/EditorRailSurface.cs | 46 ++ .../Controls/GraphItemPickerPopup.axaml | 4 +- .../Controls/PhonemeSimpleCanvas.cs | 4 +- .../Controls/PianoRollSurface.axaml | 428 +++++++++--------- OpenUtauMobile/Controls/PluginFieldsPanel.cs | 86 ++++ .../Controls/SingerCandidatesList.cs | 35 ++ .../Controls/SingerSetupResult.axaml | 105 ----- .../Controls/SingerSetupResult.axaml.cs | 12 - .../Controls/SingerSetupSummary.axaml | 91 ---- .../Controls/SingerSetupSummary.axaml.cs | 12 - .../Controls/SingerSetupTypeFields.axaml | 58 --- .../Controls/SingerSetupTypeFields.axaml.cs | 12 - .../BuiltinSingerInstallTransaction.cs | 268 +++++++++++ .../Services/BuiltinSingerInstallers.cs | 38 ++ .../Services/ExternalSingerPluginService.cs | 1 + .../SingerPlugins/BuiltinSingerMaintenance.cs | 37 ++ .../Installation/InstallFileOperations.cs | 146 ++++++ .../Installation/InstallWorkspace.cs | 104 +++++ .../Installation/SingerInstallController.cs | 242 ++++++++++ .../SingerPlugins/SingerDiscoveryService.cs | 253 +++++++++++ .../SingerPlugins/SingerPluginRegistration.cs | 2 +- .../SingerPlugins/SingerPluginRuntime.cs | 51 +++ .../SingerPlugins/SingerTypePresentation.cs | 68 +++ .../SingerPlugins/UnavailableSinger.cs | 23 + .../Services/Tracks/TrackHeaderService.cs | 3 +- OpenUtauMobile/Tools/Converters.cs | 22 +- .../ViewModels/BuiltinSingerSetupViewModel.cs | 334 ++++++++++++++ .../ViewModels/ClassicSingerSetupViewModel.cs | 426 ----------------- .../ViewModels/DiffSingerSetupViewModel.cs | 9 + .../ViewModels/EnunuSingerSetupViewModel.cs | 9 + .../ExpressionGraphLibraryViewModel.cs | 3 +- .../ViewModels/GraphItemPickerViewModel.cs | 5 +- .../ViewModels/ISingerInstallationPage.cs | 17 + OpenUtauMobile/ViewModels/MainViewModel.cs | 22 +- .../ViewModels/PianoRollViewModel.cs | 2 +- .../ViewModels/PluginFieldViewModel.cs | 91 ++++ .../ViewModels/PluginSingerSetupViewModel.cs | 204 +++++++++ .../ViewModels/SingerDetailViewModel.cs | 20 +- .../ViewModels/SingerManagementViewModel.cs | 215 ++++++--- .../ViewModels/SingerPickerViewModel.cs | 43 +- .../SingleFileSingerSetupViewModel.cs | 8 + .../ViewModels/SplashScreenViewModel.cs | 4 +- .../ViewModels/UtauSingerSetupViewModel.cs | 9 + .../Views/BuiltinSingerSetupView.axaml | 105 +++++ .../Views/BuiltinSingerSetupView.axaml.cs | 13 + .../Views/ClassicSingerSetupView.axaml | 304 ------------- .../Views/ClassicSingerSetupView.axaml.cs | 11 - OpenUtauMobile/Views/DiffSingerSetupView.cs | 5 + OpenUtauMobile/Views/EnunuSingerSetupView.cs | 5 + .../Views/PluginSingerSetupView.axaml | 68 +++ .../Views/PluginSingerSetupView.axaml.cs | 10 + OpenUtauMobile/Views/SingerDetailView.axaml | 2 +- .../Views/SingerManagementView.axaml | 22 +- .../Views/SingerManagementView.axaml.cs | 4 + .../Views/SingleFileSingerSetupView.cs | 5 + OpenUtauMobile/Views/UtauSingerSetupView.cs | 5 + 73 files changed, 3000 insertions(+), 1843 deletions(-) delete mode 100644 OpenUtauMobile.DesktopUI/Views/DesktopSingerSetupPage.axaml create mode 100644 OpenUtauMobile/Controls/EditorRailSurface.cs create mode 100644 OpenUtauMobile/Controls/PluginFieldsPanel.cs create mode 100644 OpenUtauMobile/Controls/SingerCandidatesList.cs delete mode 100644 OpenUtauMobile/Controls/SingerSetupResult.axaml delete mode 100644 OpenUtauMobile/Controls/SingerSetupResult.axaml.cs delete mode 100644 OpenUtauMobile/Controls/SingerSetupSummary.axaml delete mode 100644 OpenUtauMobile/Controls/SingerSetupSummary.axaml.cs delete mode 100644 OpenUtauMobile/Controls/SingerSetupTypeFields.axaml delete mode 100644 OpenUtauMobile/Controls/SingerSetupTypeFields.axaml.cs create mode 100644 OpenUtauMobile/Services/BuiltinSingerInstallTransaction.cs create mode 100644 OpenUtauMobile/Services/BuiltinSingerInstallers.cs create mode 100644 OpenUtauMobile/Services/SingerPlugins/BuiltinSingerMaintenance.cs create mode 100644 OpenUtauMobile/Services/SingerPlugins/Installation/InstallFileOperations.cs create mode 100644 OpenUtauMobile/Services/SingerPlugins/Installation/InstallWorkspace.cs create mode 100644 OpenUtauMobile/Services/SingerPlugins/Installation/SingerInstallController.cs create mode 100644 OpenUtauMobile/Services/SingerPlugins/SingerDiscoveryService.cs create mode 100644 OpenUtauMobile/Services/SingerPlugins/SingerPluginRuntime.cs create mode 100644 OpenUtauMobile/Services/SingerPlugins/SingerTypePresentation.cs create mode 100644 OpenUtauMobile/Services/SingerPlugins/UnavailableSinger.cs create mode 100644 OpenUtauMobile/ViewModels/BuiltinSingerSetupViewModel.cs delete mode 100644 OpenUtauMobile/ViewModels/ClassicSingerSetupViewModel.cs create mode 100644 OpenUtauMobile/ViewModels/DiffSingerSetupViewModel.cs create mode 100644 OpenUtauMobile/ViewModels/EnunuSingerSetupViewModel.cs create mode 100644 OpenUtauMobile/ViewModels/ISingerInstallationPage.cs create mode 100644 OpenUtauMobile/ViewModels/PluginFieldViewModel.cs create mode 100644 OpenUtauMobile/ViewModels/PluginSingerSetupViewModel.cs create mode 100644 OpenUtauMobile/ViewModels/SingleFileSingerSetupViewModel.cs create mode 100644 OpenUtauMobile/ViewModels/UtauSingerSetupViewModel.cs create mode 100644 OpenUtauMobile/Views/BuiltinSingerSetupView.axaml create mode 100644 OpenUtauMobile/Views/BuiltinSingerSetupView.axaml.cs delete mode 100644 OpenUtauMobile/Views/ClassicSingerSetupView.axaml delete mode 100644 OpenUtauMobile/Views/ClassicSingerSetupView.axaml.cs create mode 100644 OpenUtauMobile/Views/DiffSingerSetupView.cs create mode 100644 OpenUtauMobile/Views/EnunuSingerSetupView.cs create mode 100644 OpenUtauMobile/Views/PluginSingerSetupView.axaml create mode 100644 OpenUtauMobile/Views/PluginSingerSetupView.axaml.cs create mode 100644 OpenUtauMobile/Views/SingleFileSingerSetupView.cs create mode 100644 OpenUtauMobile/Views/UtauSingerSetupView.cs diff --git a/AGENTS.md b/AGENTS.md index 0b9ee714..6baa8bd2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,6 +19,8 @@ - Follow `.editorconfig`. Write new code comments in Simplified Chinese; preserve upstream comments. - Newly added classes, public methods, hot private methods, and hot properties should use XML comments in Simplified Chinese whenever possible. - When newly added controls involve icons, you must use existing icons in the icon library and are prohibited from drawing icons yourself in forms such as PathGeometry. If necessary, stop and confirm. +- Add comments to critical containers to explain their purpose when adding new controls in `.axaml` files. +- Always use collection expressions instead of such as `ToList()` or `ToArray()` when constructing collections. ## Verification - Before `dotnet build`, set `$env:AVALONIA_TELEMETRY_OPTOUT='1';` (or the equivalent environment variable in another shell). diff --git a/OpenUtau.Core/Vogen/VogenSingerLoader.cs b/OpenUtau.Core/Vogen/VogenSingerLoader.cs index 3ee136b0..c5a0ef36 100644 --- a/OpenUtau.Core/Vogen/VogenSingerLoader.cs +++ b/OpenUtau.Core/Vogen/VogenSingerLoader.cs @@ -24,7 +24,7 @@ class VogenMeta { public string misc; } - class VogenSingerLoader { + public class VogenSingerLoader { readonly string basePath; public static IEnumerable FindAllSingers() { diff --git a/OpenUtauMobile.DesktopUI/Views/DesktopPageLocator.cs b/OpenUtauMobile.DesktopUI/Views/DesktopPageLocator.cs index 0a4f9367..5e0316b8 100644 --- a/OpenUtauMobile.DesktopUI/Views/DesktopPageLocator.cs +++ b/OpenUtauMobile.DesktopUI/Views/DesktopPageLocator.cs @@ -130,14 +130,14 @@ private void ShowUtility(NavigateViewModelBase vm) window.KeyDown += (_, e) => { if (EditorInputController.IsComposing(window.FocusManager?.GetFocusedElement() as Visual ?? e.Source as Visual)) return; - if (!e.Handled && (e.Key == Key.Escape || e.Key == Key.W && e.KeyModifiers == (OperatingSystem.IsMacOS() ? KeyModifiers.Meta : KeyModifiers.Control)) && !IsUtilityModalOpen && vm is not ClassicSingerSetupViewModel { IsInstalling: true }) { e.Handled = true; vm.OnBackRequested(); } + if (!e.Handled && (e.Key == Key.Escape || e.Key == Key.W && e.KeyModifiers == (OperatingSystem.IsMacOS() ? KeyModifiers.Meta : KeyModifiers.Control)) && !IsUtilityModalOpen) { e.Handled = true; vm.OnBackRequested(); } }; window.Closing += (_, e) => { if (_closing) return; SaveGeometry(window, _utilityKey); e.Cancel = true; - if (!IsUtilityModalOpen && vm is not ClassicSingerSetupViewModel { IsInstalling: true }) vm.OnBackRequested(); + if (!IsUtilityModalOpen) vm.OnBackRequested(); }; window.Activated += (_, _) => RegisterWindowProviders(); window.Show(parent); diff --git a/OpenUtauMobile.DesktopUI/Views/DesktopPresentationCatalog.cs b/OpenUtauMobile.DesktopUI/Views/DesktopPresentationCatalog.cs index 24eecc49..606997d7 100644 --- a/OpenUtauMobile.DesktopUI/Views/DesktopPresentationCatalog.cs +++ b/OpenUtauMobile.DesktopUI/Views/DesktopPresentationCatalog.cs @@ -46,7 +46,15 @@ private static PageRoute Route(string titleKey, DesktopWindowProfile window, (about, _, _) => Utility("About.Title", new DesktopAboutPage(about))), [typeof(ExportLogsViewModel)] = Route("ExportLogs.Title", DesktopWindowProfile.Logs, (logs, _, _) => Utility("ExportLogs.Title", new DesktopExportLogsPage(logs))), - [typeof(ClassicSingerSetupViewModel)] = Route("SingerSetup.Title", DesktopWindowProfile.SingerSetup, + [typeof(UtauSingerSetupViewModel)] = Route("SingerSetup.Title", DesktopWindowProfile.SingerSetup, + (setup, _, _) => Utility("SingerSetup.Title", new DesktopSingerSetupPage(setup))), + [typeof(DiffSingerSetupViewModel)] = Route("SingerSetup.Title", DesktopWindowProfile.SingerSetup, + (setup, _, _) => Utility("SingerSetup.Title", new DesktopSingerSetupPage(setup))), + [typeof(EnunuSingerSetupViewModel)] = Route("SingerSetup.Title", DesktopWindowProfile.SingerSetup, + (setup, _, _) => Utility("SingerSetup.Title", new DesktopSingerSetupPage(setup))), + [typeof(SingleFileSingerSetupViewModel)] = Route("SingerSetup.Title", DesktopWindowProfile.SingerSetup, + (setup, _, _) => Utility("SingerSetup.Title", new DesktopSingerSetupPage(setup))), + [typeof(PluginSingerSetupViewModel)] = Route("SingerSetup.Title", DesktopWindowProfile.SingerSetup, (setup, _, _) => Utility("SingerSetup.Title", new DesktopSingerSetupPage(setup))), [typeof(SingerDetailViewModel)] = Route("SingerDetail.Title", DesktopWindowProfile.Standard, (singer, _, _) => Utility("SingerDetail.Title", new DesktopSingerDetailPage(singer))), diff --git a/OpenUtauMobile.DesktopUI/Views/DesktopShell.cs b/OpenUtauMobile.DesktopUI/Views/DesktopShell.cs index 0703e36c..bcc92b4e 100644 --- a/OpenUtauMobile.DesktopUI/Views/DesktopShell.cs +++ b/OpenUtauMobile.DesktopUI/Views/DesktopShell.cs @@ -113,7 +113,7 @@ void UpdateChrome() AddHandler(DragDrop.DropEvent, OnDrop); UpdateNavigation(); } - private bool Ready => !_fileAction && !PianoRollViewModel.IsBatchEditRunning && _main.CurrentViewModel is not (SplashScreenViewModel or ClassicSingerSetupViewModel { IsInstalling: true }) && !_pages.IsUtilityModalOpen && !_dialogHost.IsOpen && _main.ActiveEditor is not { IsLoadingProject: true }; + private bool Ready => !_fileAction && !PianoRollViewModel.IsBatchEditRunning && _main.CurrentViewModel is not (SplashScreenViewModel or ISingerInstallationPage { IsBusy: true }) && !_pages.IsUtilityModalOpen && !_dialogHost.IsOpen && _main.ActiveEditor is not { IsLoadingProject: true }; public void CancelInput() => _pages.Workspace?.CancelInput(); private void OnWindowActivated(object? sender, EventArgs e) => _pages.InitializeWindowProviders(); public bool PrepareFileAction() => _pages.Workspace?.PrepareFileAction() != false; @@ -266,7 +266,7 @@ private async void OnShellKeyDown(object? sender, KeyEventArgs e) await RunAsync(action); } private static bool Supported(string path) => TrackImportService.FilePatterns.Any(p => Path.GetExtension(path).Equals(p[1..], StringComparison.OrdinalIgnoreCase)) || IsAudio(path) || IsArchive(path) || IsTool(path); - private static bool IsArchive(string path) => new[] { ".zip", ".rar", ".uar" }.Contains(Path.GetExtension(path).ToLowerInvariant()); + private static bool IsArchive(string path) => SingerManagementViewModel.IsInstallPackagePath(path); private static bool IsTool(string path) => new[] { ".exe", ".bat", ".sh" }.Contains(Path.GetExtension(path).ToLowerInvariant()) || !OperatingSystem.IsWindows() && Path.GetExtension(path).Length == 0 && DesktopToolsService.IsExecutable(path); private static bool IsAudio(string path) => new[] { ".wav", ".mp3", ".flac", ".ogg", ".aac", ".aiff", ".aif", ".aifc" }.Contains(Path.GetExtension(path).ToLowerInvariant()); private void OnDragOver(object? sender, DragEventArgs e) @@ -295,7 +295,8 @@ await RunFileAsync(async () => string? archive = paths.FirstOrDefault(IsArchive); if (archive != null) { - Show(new ClassicSingerSetupViewModel(_main) { ArchiveFilePath = archive }); + using SingerManagementViewModel installers = new(_main); + await installers.ChooseInstallerAsync(archive); return; } string? tool = paths.FirstOrDefault(IsTool); diff --git a/OpenUtauMobile.DesktopUI/Views/DesktopSingerDetailPage.axaml b/OpenUtauMobile.DesktopUI/Views/DesktopSingerDetailPage.axaml index 6719e0e5..a861e140 100644 --- a/OpenUtauMobile.DesktopUI/Views/DesktopSingerDetailPage.axaml +++ b/OpenUtauMobile.DesktopUI/Views/DesktopSingerDetailPage.axaml @@ -130,7 +130,7 @@ FontSize="{x:Static semantic:TypographyTokens.BodySSize}" Foreground="{DynamicResource Sem.Color.OnSurfaceVariant}" TextWrapping="Wrap" /> - - - - - - - - - - - - - - + - - - - - - + + + + - - - + + VerticalAlignment="Stretch"> + + + + + + + + + + + + + + - + - + - - + + - - - + + + + + + + + + 为编辑器固定侧栏提供统一的 MD3 Level 3 双层阴影。 + public class EditorRailSurface : Border + { + /// 随主题变化的语义阴影色。 + public static readonly StyledProperty ShadowColorProperty = + AvaloniaProperty.Register(nameof(ShadowColor)); + + /// 获取或设置侧栏的语义阴影色。 + public Color ShadowColor + { + get => GetValue(ShadowColorProperty); + set => SetValue(ShadowColorProperty, value); + } + + /// 在主题阴影色变化时同步更新主阴影与环境阴影。 + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) + { + base.OnPropertyChanged(change); + if (change.Property == ShadowColorProperty) + { + Color color = ShadowColor; + // MD3 Level 3:主阴影 (0,1,3,0),环境阴影 (0,4,8,3)。 + BoxShadow = new BoxShadows( + new BoxShadow + { + OffsetY = 1, + Blur = 3, + Color = Color.FromArgb((byte)(color.A * 0.30), color.R, color.G, color.B) + }, + [new BoxShadow + { + OffsetY = 4, + Blur = 8, + Spread = 3, + Color = Color.FromArgb((byte)(color.A * 0.15), color.R, color.G, color.B) + }]); + } + } + } +} \ No newline at end of file diff --git a/OpenUtauMobile/Controls/GraphItemPickerPopup.axaml b/OpenUtauMobile/Controls/GraphItemPickerPopup.axaml index d84facdb..9aba0225 100644 --- a/OpenUtauMobile/Controls/GraphItemPickerPopup.axaml +++ b/OpenUtauMobile/Controls/GraphItemPickerPopup.axaml @@ -15,8 +15,8 @@ - + diff --git a/OpenUtauMobile/Controls/PhonemeSimpleCanvas.cs b/OpenUtauMobile/Controls/PhonemeSimpleCanvas.cs index 91ccae2a..f2858b65 100644 --- a/OpenUtauMobile/Controls/PhonemeSimpleCanvas.cs +++ b/OpenUtauMobile/Controls/PhonemeSimpleCanvas.cs @@ -17,7 +17,7 @@ namespace OpenUtauMobile.Controls; /// -/// 简易音素画布,SynthV 风格:独立的圆角音素卡片,卡片之间有清晰间距与显著的垂直边界手柄。 +/// 显示音素卡片与可拖动的边界手柄。 /// 双击音素卡片直接唤起音素别名编辑弹窗。 /// public class PhonemeSimpleCanvas : Control, ICmdSubscriber @@ -257,7 +257,7 @@ public override void Render(DrawingContext context) IBrush currentTextBrush = hasError ? errorText : isSelected ? selectedTextBrush : textBrush; IPen borderPen = hasError ? isSelected ? selectedErrorBorder : errorBorder : chipBorderPen; - // 1. 绘制音素卡片(SynthV 风格独立圆角药丸框) + // 1. 绘制音素卡片 Rect blockRect = new Rect(chipLeft, topMargin, chipWidth, blockHeight); context.DrawRectangle(fillBrush, borderPen, blockRect, 4, 4); diff --git a/OpenUtauMobile/Controls/PianoRollSurface.axaml b/OpenUtauMobile/Controls/PianoRollSurface.axaml index 3c00796c..42ae8279 100644 --- a/OpenUtauMobile/Controls/PianoRollSurface.axaml +++ b/OpenUtauMobile/Controls/PianoRollSurface.axaml @@ -1,6 +1,5 @@ - - - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - + KeyOffset="{Binding KeyOffset}" + ProjectKey="{Binding ProjectKey}" + LabelMode="{Binding PianoKeyLabelMode}" /> + + + + + + + + + + - - - - - - - - - + + + + + + + - - - - - - - - - + Fill="{DynamicResource Sem.Color.Surface}" + Stroke="{DynamicResource Sem.Color.Outline}" + StrokeThickness="1" + Stretch="Fill" /> + + + + - - - - - - - - - - - - + + + + + + + + + + + + + + + + + - + diff --git a/OpenUtauMobile/Controls/PluginFieldsPanel.cs b/OpenUtauMobile/Controls/PluginFieldsPanel.cs new file mode 100644 index 00000000..250f80b3 --- /dev/null +++ b/OpenUtauMobile/Controls/PluginFieldsPanel.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.Templates; +using Avalonia.Data; +using Avalonia.Layout; +using OpenUtauMobile.Plugin.Abstractions; +using OpenUtauMobile.ViewModels; + +namespace OpenUtauMobile.Controls +{ + /// 使用宿主标准控件呈现声明式字段,不加载插件视图。 + public sealed class PluginFieldsPanel : StackPanel + { + public static readonly StyledProperty?> FieldsProperty = + AvaloniaProperty.Register?>(nameof(Fields)); + public IReadOnlyList? Fields { get => GetValue(FieldsProperty); set => SetValue(FieldsProperty, value); } + + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) + { + base.OnPropertyChanged(change); + if (change.Property != FieldsProperty) return; + Children.Clear(); + Spacing = Themes.OpenUtauMobile.Tokens.Foundation.LayoutTokens.SpaceM; + foreach (PluginFieldViewModel field in Fields ?? []) + { + PluginFieldDescriptor descriptor = field.Descriptor; + if (!descriptor.IsVisible) continue; + StackPanel row = new() { DataContext = field, Spacing = 8, IsEnabled = descriptor.IsEnabled }; + row.Children.Add(new TextBlock { Text = descriptor.Label, TextWrapping = Avalonia.Media.TextWrapping.Wrap }); + if (!string.IsNullOrEmpty(descriptor.Description)) + row.Children.Add(new TextBlock { Text = descriptor.Description, TextWrapping = Avalonia.Media.TextWrapping.Wrap }); + switch (descriptor.Kind) + { + case PluginFieldKind.Boolean: + CheckBox check = new() { Content = descriptor.Label }; + check.Bind(CheckBox.IsCheckedProperty, new Binding(nameof(field.Checked)) { Mode = BindingMode.TwoWay }); + row.Children.Add(check); + break; + case PluginFieldKind.Number: + NumericUpDown number = new() { Minimum = descriptor.Minimum ?? decimal.MinValue, Maximum = descriptor.Maximum ?? decimal.MaxValue }; + number.Bind(NumericUpDown.ValueProperty, new Binding(nameof(field.Number)) { Mode = BindingMode.TwoWay }); + row.Children.Add(number); + break; + case PluginFieldKind.Selection: + ComboBox combo = new() + { + ItemsSource = descriptor.Options.IsDefault ? [] : descriptor.Options, + HorizontalAlignment = HorizontalAlignment.Stretch, + ItemTemplate = new FuncDataTemplate((option, _) => new TextBlock { Text = option?.Label }) + }; + combo.Bind(ComboBox.SelectedItemProperty, new Binding(nameof(field.Selected)) { Mode = BindingMode.TwoWay }); + row.Children.Add(combo); + break; + case PluginFieldKind.MultipleSelection: + foreach (PluginFieldOption option in descriptor.Options.IsDefault ? [] : descriptor.Options) + { + CheckBox choice = new() { Content = option.Label, IsChecked = field.SelectedIds.Contains(option.Id) }; + choice.IsCheckedChanged += (_, _) => field.SelectedIds = choice.IsChecked == true + ? field.SelectedIds.Add(option.Id) : field.SelectedIds.Remove(option.Id); + row.Children.Add(choice); + } + break; + default: + TextBox text = new() { IsReadOnly = descriptor.Kind is PluginFieldKind.File or PluginFieldKind.Directory }; + text.Bind(TextBox.TextProperty, new Binding(nameof(field.Text)) { Mode = BindingMode.TwoWay }); + row.Children.Add(text); + if (text.IsReadOnly) + { + Button browse = new() { Command = field.BrowseCommand }; + browse.Bind(ContentControl.ContentProperty, browse.GetResourceObservable("Common.Browse")); + row.Children.Add(browse); + } + break; + } + TextBlock error = new() { TextWrapping = Avalonia.Media.TextWrapping.Wrap }; + error.Bind(TextBlock.TextProperty, new Binding(nameof(field.Error))); + error.Bind(TextBlock.ForegroundProperty, error.GetResourceObservable("Sem.Color.Error")); + row.Children.Add(error); + Children.Add(row); + } + } + } +} \ No newline at end of file diff --git a/OpenUtauMobile/Controls/SingerCandidatesList.cs b/OpenUtauMobile/Controls/SingerCandidatesList.cs new file mode 100644 index 00000000..d1adced5 --- /dev/null +++ b/OpenUtauMobile/Controls/SingerCandidatesList.cs @@ -0,0 +1,35 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.Templates; +using OpenUtauMobile.Services.SingerPlugins; + +namespace OpenUtauMobile.Controls +{ + /// 管理页展示不可用候选的位置和诊断,不提供工程选择操作。 + public sealed class SingerCandidatesList : ItemsControl + { + public SingerCandidatesList() + { + ItemTemplate = new FuncDataTemplate((candidate, _) => + { + if (candidate == null) return null; + StackPanel text = new() { Spacing = 4 }; + text.Children.Add(new TextBlock + { + Text = candidate.Entry.DisplayName, + FontWeight = Avalonia.Media.FontWeight.SemiBold, + TextWrapping = Avalonia.Media.TextWrapping.Wrap + }); + TextBlock status = new() + { + Text = Helpers.L.S($"SingerAvailability.{candidate.Entry.Availability}"), + TextWrapping = Avalonia.Media.TextWrapping.Wrap + }; + status.Bind(TextBlock.ForegroundProperty, status.GetResourceObservable("Sem.Color.Warning")); + text.Children.Add(status); + text.Children.Add(new TextBlock { Text = candidate.Details, TextWrapping = Avalonia.Media.TextWrapping.Wrap }); + return new Border { Padding = new Thickness(12), Child = text }; + }); + } + } +} \ No newline at end of file diff --git a/OpenUtauMobile/Controls/SingerSetupResult.axaml b/OpenUtauMobile/Controls/SingerSetupResult.axaml deleted file mode 100644 index 77ab63bb..00000000 --- a/OpenUtauMobile/Controls/SingerSetupResult.axaml +++ /dev/null @@ -1,105 +0,0 @@ - - - - - - - - - - - - - - + + - \ No newline at end of file + diff --git a/OpenUtauMobile/Views/SingerManagementView.axaml.cs b/OpenUtauMobile/Views/SingerManagementView.axaml.cs index 79b4ec7b..01436818 100644 --- a/OpenUtauMobile/Views/SingerManagementView.axaml.cs +++ b/OpenUtauMobile/Views/SingerManagementView.axaml.cs @@ -7,5 +7,9 @@ public partial class SingerManagementView : UserControl public SingerManagementView() { InitializeComponent(); + InstallerMenu.ActionInvoked += async action => + { + if (DataContext is ViewModels.SingerManagementViewModel model) await model.InvokeInstallerAsync(action.Id); + }; } } \ No newline at end of file diff --git a/OpenUtauMobile/Views/SingleFileSingerSetupView.cs b/OpenUtauMobile/Views/SingleFileSingerSetupView.cs new file mode 100644 index 00000000..53298e42 --- /dev/null +++ b/OpenUtauMobile/Views/SingleFileSingerSetupView.cs @@ -0,0 +1,5 @@ +namespace OpenUtauMobile.Views +{ + /// 内置单文件包的安装确认页面。 + public sealed class SingleFileSingerSetupView : BuiltinSingerSetupView; +} diff --git a/OpenUtauMobile/Views/UtauSingerSetupView.cs b/OpenUtauMobile/Views/UtauSingerSetupView.cs new file mode 100644 index 00000000..3a96573e --- /dev/null +++ b/OpenUtauMobile/Views/UtauSingerSetupView.cs @@ -0,0 +1,5 @@ +namespace OpenUtauMobile.Views +{ + /// UTAU 专用页面入口,复用内置编码预览布局。 + public sealed class UtauSingerSetupView : BuiltinSingerSetupView; +} From 8f804eafad6f083a0dd4cfb7966a864f80bb22e4 Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Sun, 1 Nov 2026 01:40:44 +0800 Subject: [PATCH 04/45] =?UTF-8?q?feature:=20=E5=AE=8C=E5=96=84=E5=86=85?= =?UTF-8?q?=E7=BD=AE=E6=AD=8C=E6=89=8B=E5=AE=89=E8=A3=85=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Views/DesktopPresentationCatalog.cs | 2 + .../Views/DesktopSingerSetupPage.axaml.cs | 1 + OpenUtauMobile/Assets/Lang/Strings.en.resx | 6 ++- OpenUtauMobile/Assets/Lang/Strings.ja.resx | 6 ++- OpenUtauMobile/Assets/Lang/Strings.ru.resx | 6 ++- OpenUtauMobile/Assets/Lang/Strings.uk.resx | 6 ++- .../Assets/Lang/Strings.zh-Hans.resx | 6 ++- .../Services/BuiltinSingerInstallers.cs | 1 + .../SingerInstallation/VogenPackage.cs | 31 +++++++++++++++ .../ViewModels/BuiltinSingerSetupViewModel.cs | 38 ++++++++++++++----- .../NeutrinoSingerSetupViewModel.cs | 9 +++++ .../ViewModels/PluginSingerSetupViewModel.cs | 2 +- .../ViewModels/RendererPickerViewModel.cs | 2 +- .../ViewModels/SingerManagementViewModel.cs | 1 + .../Views/BuiltinSingerSetupView.axaml | 15 ++++++++ .../Views/NeutrinoSingerSetupView.cs | 5 +++ 16 files changed, 121 insertions(+), 16 deletions(-) create mode 100644 OpenUtauMobile/Services/SingerInstallation/VogenPackage.cs create mode 100644 OpenUtauMobile/ViewModels/NeutrinoSingerSetupViewModel.cs create mode 100644 OpenUtauMobile/Views/NeutrinoSingerSetupView.cs diff --git a/OpenUtauMobile.DesktopUI/Views/DesktopPresentationCatalog.cs b/OpenUtauMobile.DesktopUI/Views/DesktopPresentationCatalog.cs index 606997d7..a32d3e90 100644 --- a/OpenUtauMobile.DesktopUI/Views/DesktopPresentationCatalog.cs +++ b/OpenUtauMobile.DesktopUI/Views/DesktopPresentationCatalog.cs @@ -52,6 +52,8 @@ private static PageRoute Route(string titleKey, DesktopWindowProfile window, (setup, _, _) => Utility("SingerSetup.Title", new DesktopSingerSetupPage(setup))), [typeof(EnunuSingerSetupViewModel)] = Route("SingerSetup.Title", DesktopWindowProfile.SingerSetup, (setup, _, _) => Utility("SingerSetup.Title", new DesktopSingerSetupPage(setup))), + [typeof(NeutrinoSingerSetupViewModel)] = Route("SingerSetup.Title", DesktopWindowProfile.SingerSetup, + (setup, _, _) => Utility("SingerSetup.Title", new DesktopSingerSetupPage(setup))), [typeof(SingleFileSingerSetupViewModel)] = Route("SingerSetup.Title", DesktopWindowProfile.SingerSetup, (setup, _, _) => Utility("SingerSetup.Title", new DesktopSingerSetupPage(setup))), [typeof(PluginSingerSetupViewModel)] = Route("SingerSetup.Title", DesktopWindowProfile.SingerSetup, diff --git a/OpenUtauMobile.DesktopUI/Views/DesktopSingerSetupPage.axaml.cs b/OpenUtauMobile.DesktopUI/Views/DesktopSingerSetupPage.axaml.cs index 6b3b3d33..aaf1c1d4 100644 --- a/OpenUtauMobile.DesktopUI/Views/DesktopSingerSetupPage.axaml.cs +++ b/OpenUtauMobile.DesktopUI/Views/DesktopSingerSetupPage.axaml.cs @@ -15,6 +15,7 @@ public DesktopSingerSetupPage(BuiltinSingerSetupViewModel model) UtauSingerSetupViewModel => new UtauSingerSetupView(), DiffSingerSetupViewModel => new DiffSingerSetupView(), EnunuSingerSetupViewModel => new EnunuSingerSetupView(), + NeutrinoSingerSetupViewModel => new NeutrinoSingerSetupView(), _ => new SingleFileSingerSetupView(), }; view.DataContext = model; diff --git a/OpenUtauMobile/Assets/Lang/Strings.en.resx b/OpenUtauMobile/Assets/Lang/Strings.en.resx index 9b6ea904..9443bd1d 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.en.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.en.resx @@ -1394,7 +1394,7 @@ Installation failed: {0} - Step {0} / 4 + Step {0} / {1} Initializing document manager @@ -2607,4 +2607,8 @@ Applying replaces the source of this input. Rollback failed Installation is in progress. Cancel it before leaving. The destination already exists. + Singer name + Voicebank version + Reading metadata… + Could not parse metadata diff --git a/OpenUtauMobile/Assets/Lang/Strings.ja.resx b/OpenUtauMobile/Assets/Lang/Strings.ja.resx index baf47768..28835619 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.ja.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.ja.resx @@ -1394,7 +1394,7 @@ インストール失敗: {0} - ステップ {0} / 4 + ステップ {0} / {1} ドキュメントマネージャーを初期化中 @@ -2603,4 +2603,8 @@ Applying replaces the source of this input. 復元に失敗しました インストール中です。先にキャンセルしてください。 インストール先は既に存在します。 + 歌手名 + 音源バージョン + メタデータを読み込み中… + メタデータを解析できませんでした diff --git a/OpenUtauMobile/Assets/Lang/Strings.ru.resx b/OpenUtauMobile/Assets/Lang/Strings.ru.resx index a7b2857d..b7b54405 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.ru.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.ru.resx @@ -1317,7 +1317,7 @@ Не удалось выполнить установку: {0} - Шаг {0} / 4 + Шаг {0} / {1} Инициализация менеджера документов @@ -2562,4 +2562,8 @@ Applying replaces the source of this input. Не удалось восстановить файлы Идёт установка. Сначала отмените её. Путь назначения уже существует. + Имя певца + Версия голосового банка + Чтение метаданных… + Не удалось прочитать метаданные diff --git a/OpenUtauMobile/Assets/Lang/Strings.uk.resx b/OpenUtauMobile/Assets/Lang/Strings.uk.resx index a840b5cf..69bca9de 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.uk.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.uk.resx @@ -1317,7 +1317,7 @@ Не вдалося виконати встановлення: {0} - Крок {0} / 4 + Крок {0} / {1} Ініціалізація менеджера документів @@ -2562,4 +2562,8 @@ Applying replaces the source of this input. Не вдалося відновити файли Триває встановлення. Спочатку скасуйте його. Шлях призначення вже існує. + Ім’я співака + Версія голосового банку + Читання метаданих… + Не вдалося прочитати метадані diff --git a/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx b/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx index 2ecd1ec5..0071ddfe 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx @@ -1394,7 +1394,7 @@ 安装失败: {0} - 第 {0} 步 / 4 + 第 {0} 步 / {1} 文档管理器初始化中 @@ -2607,4 +2607,8 @@ 回滚失败 安装进行中,请先取消安装。 目标已存在。 + 歌手名称 + 声库版本 + 正在读取元数据… + 未能解析元数据 diff --git a/OpenUtauMobile/Services/BuiltinSingerInstallers.cs b/OpenUtauMobile/Services/BuiltinSingerInstallers.cs index ed151b49..9697c2dd 100644 --- a/OpenUtauMobile/Services/BuiltinSingerInstallers.cs +++ b/OpenUtauMobile/Services/BuiltinSingerInstallers.cs @@ -24,6 +24,7 @@ public static class BuiltinSingerInstallers new("builtin:diffsinger", "DiffSinger", "diffsinger", [".zip", ".rar", ".uar"]), new("builtin:enunu", "ENUNU", "enunu", [".zip", ".rar", ".uar"]), new("builtin:vogen", "Vogen", null, [".vogeon"]), + new("builtin:neutrino", "NEUTRINO", "neutrino", [".zip", ".rar", ".uar"]), ]; /// 沿用桌面解包规则,通过会话暂存与文件变更记录提供取消和回滚。 diff --git a/OpenUtauMobile/Services/SingerInstallation/VogenPackage.cs b/OpenUtauMobile/Services/SingerInstallation/VogenPackage.cs new file mode 100644 index 00000000..76fcc45a --- /dev/null +++ b/OpenUtauMobile/Services/SingerInstallation/VogenPackage.cs @@ -0,0 +1,31 @@ +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Threading; +using SharpCompress.Archives; +using SharpCompress.Readers; + +namespace OpenUtauMobile.Services.SingerInstallation +{ + /// 仅读取 Vogen 展示信息,与安装提交及模型加载无关。 + internal static class VogenPackage + { + /// 无法取得可展示的名称时返回空;读取异常由页面转换为非阻断提示。 + internal static (string Name, string Version)? ReadMetadata(string source, CancellationToken token) + { + token.ThrowIfCancellationRequested(); + using FileStream input = File.OpenRead(source); + using IArchive archive = ArchiveFactory.OpenArchive(input, new ReaderOptions { LeaveStreamOpen = false }); + IArchiveEntry? meta = archive.Entries.FirstOrDefault(entry => !entry.IsDirectory && entry.Key == "meta.json"); + if (meta == null) return null; + using Stream stream = meta.OpenEntryStream(); + using JsonDocument document = JsonDocument.Parse(stream); + JsonElement root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("name", out JsonElement name) + || name.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(name.GetString())) return null; + token.ThrowIfCancellationRequested(); + return (name.GetString()!, root.TryGetProperty("version", out JsonElement version) && version.ValueKind == JsonValueKind.String + ? version.GetString()! : ""); + } + } +} diff --git a/OpenUtauMobile/ViewModels/BuiltinSingerSetupViewModel.cs b/OpenUtauMobile/ViewModels/BuiltinSingerSetupViewModel.cs index 93a050cf..3074a41e 100644 --- a/OpenUtauMobile/ViewModels/BuiltinSingerSetupViewModel.cs +++ b/OpenUtauMobile/ViewModels/BuiltinSingerSetupViewModel.cs @@ -12,6 +12,7 @@ using OpenUtauMobile.Helpers; using OpenUtauMobile.Services; using OpenUtauMobile.Services.Dialogs; +using OpenUtauMobile.Services.SingerInstallation; using ReactiveUI; using ReactiveUI.Fody.Helpers; using SharpCompress.Archives; @@ -42,10 +43,11 @@ public abstract class BuiltinSingerSetupViewModel : NavigateViewModelBase, ISing private static readonly string[] viewProperties = [ nameof(CanInstallAtStep), nameof(CanNext), nameof(CanBack), nameof(ShowArchiveEncoding), - nameof(ShowTextEncoding), nameof(ShowPreview), nameof(ShowForm), nameof(IsSuccessful), nameof(ResultTitle), nameof(StepText), + nameof(ShowTextEncoding), nameof(ShowPreview), nameof(ShowPackageMetadata), nameof(ShowPackageMetadataError), nameof(ShowForm), nameof(IsSuccessful), nameof(ResultTitle), nameof(StepText), ]; - private sealed record PreviewResult(IReadOnlyList Items, string? TextEncoding); + private sealed record PreviewResult(IReadOnlyList Items, string? TextEncoding, + (string Name, string Version)? Package = null); public string ArchiveFilePath { get; } public string FileName => Path.GetFileName(ArchiveFilePath); public string InstallerName => installer.DisplayName; @@ -62,6 +64,10 @@ private sealed record PreviewResult(IReadOnlyList Items, string? TextEnc public string SingerType => installer.SingerType ?? ""; [Reactive] public int Step { get; private set; } [Reactive] public IReadOnlyList TextItems { get; private set; } = []; + /// 单文件安装确认中的歌手名称,不与编码样例混用。 + [Reactive] public string PackageName { get; private set; } = ""; + /// 安装包声明的声库版本,缺失时不显示对应信息行。 + [Reactive] public string PackageVersion { get; private set; } = ""; [Reactive] public bool IsPreviewLoading { get; private set; } [Reactive] public bool HasPreviewError { get; private set; } [Reactive] public bool IsBusy { get; private set; } @@ -81,9 +87,13 @@ private sealed record PreviewResult(IReadOnlyList Items, string? TextEnc public bool ShowArchiveEncoding => ShowForm && IsArchive && Step == 0; public bool ShowTextEncoding => ShowForm && IsArchive && Step == 1; public bool ShowPreview => ShowForm && IsArchive; + /// 单文件包读取成功后展示带标签的元数据确认区域。 + public bool ShowPackageMetadata => ShowForm && !IsArchive && !IsPreviewLoading && !HasPreviewError; + /// 元数据读取失败仅显示简短提示,不作为单文件安装的前置条件。 + public bool ShowPackageMetadataError => ShowForm && !IsArchive && !IsPreviewLoading && HasPreviewError; /// 结果页成功状态,与取消、失败状态互斥。 public bool IsSuccessful => IsFinished && !IsCancelled && !HasFailed; - public string StepText => IsFinished ? "" : IsArchive ? string.Format(L.S("SingerSetup.StepFormat"), Step + 1) : ""; + public string StepText => IsFinished ? "" : IsArchive ? string.Format(L.S("SingerSetup.StepFormat"), Step + 1, 2) : ""; public string ResultTitle => L.S(IsCancelled ? "SingerSetup.Cancelled" : HasFailed ? "SingerSetup.Failed" : "SingerSetup.Success"); public ReactiveCommand NextCommand { get; } public ReactiveCommand BackCommand { get; } @@ -100,7 +110,7 @@ protected BuiltinSingerSetupViewModel(MainViewModel navigator, BuiltinSingerInst TextEncoding = Encodings[0]; IObservable editable = this.WhenAnyValue(item => item.IsBusy, item => item.IsClosing, item => item.IsFinished, item => item.IsPreviewLoading, item => item.HasPreviewError, - (busy, leaving, finished, loading, failed) => !busy && !leaving && !finished && !loading && !failed); + (busy, leaving, finished, loading, failed) => !busy && !leaving && !finished && !loading && (!IsArchive || !failed)); NextCommand = ReactiveCommand.Create(() => { Step++; }, editable.CombineLatest( this.WhenAnyValue(item => item.Step).Select(_ => Step == 0 && IsArchive), (ready, next) => ready && next)); BackCommand = ReactiveCommand.Create(() => { if (TryLeave() && Step > 0) Step--; }, @@ -116,14 +126,15 @@ protected BuiltinSingerSetupViewModel(MainViewModel navigator, BuiltinSingerInst installCancellation?.Cancel(); }, this.WhenAnyValue(item => item.IsBusy, item => item.IsCancelling, (busy, canceling) => busy && !canceling)); ExitCommand = ReactiveCommand.CreateFromTask(LeaveAsync); - this.WhenAnyValue(item => item.Step, item => item.IsFinished, item => item.IsBusy).Subscribe(_ => + this.WhenAnyValue(item => item.Step, item => item.IsFinished, item => item.IsBusy, + item => item.IsPreviewLoading, item => item.HasPreviewError).Subscribe(_ => { foreach (string name in viewProperties) this.RaisePropertyChanged(name); }).DisposeWith(subscriptions); this.WhenAnyValue(item => item.Step, item => item.ArchiveEncoding, item => item.TextEncoding) .Skip(1).Subscribe(_ => { - if (initialized && !applyingEncoding && !IsBusy && !IsClosing && !IsFinished) StartPreview(); + if (initialized && IsArchive && !applyingEncoding && !IsBusy && !IsClosing && !IsFinished) StartPreview(); }).DisposeWith(subscriptions); this.WhenAnyValue(item => item.TextEncoding).Skip(1).Subscribe(_ => { @@ -136,7 +147,7 @@ public override void OnNavigatedTo() { if (initialized) return; initialized = true; - if (IsArchive) StartPreview(); + StartPreview(); } private void StartPreview() @@ -160,7 +171,7 @@ private async Task RefreshPreviewAsync() IsPreviewLoading = true; HasPreviewError = false; Error = ""; - Message = L.S(step == 0 ? "SingerSetup.Step1.Preview" : "SingerSetup.Step2.Preview"); + Message = L.S(!IsArchive ? "SingerSetup.ReadingMetadata" : step == 0 ? "SingerSetup.Step1.Preview" : "SingerSetup.Step2.Preview"); try { await previewGate.WaitAsync(token); @@ -169,6 +180,9 @@ private async Task RefreshPreviewAsync() finally { previewGate.Release(); } if (version != previewVersion || IsClosing) return; TextItems = result.Items; + PackageName = result.Package?.Name ?? ""; + PackageVersion = result.Package?.Version ?? ""; + HasPreviewError = !IsArchive && result.Package == null; if (!textEncodingEdited && result.TextEncoding is { Length: > 0 } encoding) { try @@ -185,7 +199,9 @@ private async Task RefreshPreviewAsync() catch (Exception exception) { if (version != previewVersion || IsClosing) return; - Error = exception.Message; + Error = IsArchive ? exception.Message : ""; + PackageName = ""; + PackageVersion = ""; HasPreviewError = true; } finally @@ -203,6 +219,10 @@ private async Task RefreshPreviewAsync() /// 文件名和文本样例分别最多产生 50 项,达到上限就停止读取后续内容。 private PreviewResult ReadPreview(int step, Encoding archiveEncoding, Encoding textEncoding, bool readEncoding, CancellationToken token) { + if (!IsArchive) + { + return new([], null, VogenPackage.ReadMetadata(ArchiveFilePath, token)); + } using FileStream input = File.OpenRead(ArchiveFilePath); using IArchive archive = ArchiveFactory.OpenArchive(input, new ReaderOptions { diff --git a/OpenUtauMobile/ViewModels/NeutrinoSingerSetupViewModel.cs b/OpenUtauMobile/ViewModels/NeutrinoSingerSetupViewModel.cs new file mode 100644 index 00000000..de15b1f8 --- /dev/null +++ b/OpenUtauMobile/ViewModels/NeutrinoSingerSetupViewModel.cs @@ -0,0 +1,9 @@ +using System.Linq; +using OpenUtauMobile.Services; + +namespace OpenUtauMobile.ViewModels +{ + /// 用户明确选择的 NEUTRINO 安装向导,复用编码及安装生命周期。 + public sealed class NeutrinoSingerSetupViewModel(MainViewModel navigator, string sourcePath) + : BuiltinSingerSetupViewModel(navigator, BuiltinSingerInstallers.All.Single(item => item.Id == "builtin:neutrino"), sourcePath); +} diff --git a/OpenUtauMobile/ViewModels/PluginSingerSetupViewModel.cs b/OpenUtauMobile/ViewModels/PluginSingerSetupViewModel.cs index f85fb7c6..502e1457 100644 --- a/OpenUtauMobile/ViewModels/PluginSingerSetupViewModel.cs +++ b/OpenUtauMobile/ViewModels/PluginSingerSetupViewModel.cs @@ -109,7 +109,7 @@ private void Apply(InstallView view) ClearContent(); InstallStep step = view.Steps.Single(item => item.Id == view.CurrentStepId); Title = step.Title; - StepText = string.Format(L.S("SingerSetup.StepFormat"), view.Steps.IndexOf(step) + 1); + StepText = string.Format(L.S("SingerSetup.StepFormat"), view.Steps.IndexOf(step) + 1, view.Steps.Length); StepTitles = view.Steps.Select(item => item.Title).ToArray(); Fields = (step.Fields.IsDefault ? ImmutableArray.Empty : step.Fields) .Select(item => new PluginFieldViewModel(item, Invalidate)).ToArray(); diff --git a/OpenUtauMobile/ViewModels/RendererPickerViewModel.cs b/OpenUtauMobile/ViewModels/RendererPickerViewModel.cs index 9abf7cf6..b654788f 100644 --- a/OpenUtauMobile/ViewModels/RendererPickerViewModel.cs +++ b/OpenUtauMobile/ViewModels/RendererPickerViewModel.cs @@ -94,7 +94,7 @@ public RendererPickerViewModel(UProject project, UTrack track) _originalGraph = track.ExpressionGraph; if (_original.renderer != null) _graphDrafts[RendererRegistry.GetExpressionGraphSlot(_original.renderer)] = _originalGraph; - if (_singer is { Found: true }) Renderers.Load(OpenUtauMobile.Services.ExternalSingerPluginService.GetSupportedRenderers(_singer)); + if (_singer is { Found: true }) Renderers.Load(Services.ExternalSingerPluginService.GetSupportedRenderers(_singer)); _selectedRenderer = _original.renderer != null && Renderers.Contains(_original.renderer) ? _original.renderer : null; _selectedResampler = _original.resampler; _selectedWavtool = _original.wavtool; diff --git a/OpenUtauMobile/ViewModels/SingerManagementViewModel.cs b/OpenUtauMobile/ViewModels/SingerManagementViewModel.cs index 78f45ddd..4f5aa362 100644 --- a/OpenUtauMobile/ViewModels/SingerManagementViewModel.cs +++ b/OpenUtauMobile/ViewModels/SingerManagementViewModel.cs @@ -151,6 +151,7 @@ private async Task OpenInstallerAsync(string id, string? sourcePath) "builtin:utau" => new UtauSingerSetupViewModel(Navigator, path), "builtin:diffsinger" => new DiffSingerSetupViewModel(Navigator, path), "builtin:enunu" => new EnunuSingerSetupViewModel(Navigator, path), + "builtin:neutrino" => new NeutrinoSingerSetupViewModel(Navigator, path), _ => new SingleFileSingerSetupViewModel(Navigator, builtin, path), }; Navigator.Navigate(setup); diff --git a/OpenUtauMobile/Views/BuiltinSingerSetupView.axaml b/OpenUtauMobile/Views/BuiltinSingerSetupView.axaml index 7da26341..b9b2db2d 100644 --- a/OpenUtauMobile/Views/BuiltinSingerSetupView.axaml +++ b/OpenUtauMobile/Views/BuiltinSingerSetupView.axaml @@ -52,6 +52,21 @@ + + + + + + + + + diff --git a/OpenUtauMobile/Views/NeutrinoSingerSetupView.cs b/OpenUtauMobile/Views/NeutrinoSingerSetupView.cs new file mode 100644 index 00000000..548036ca --- /dev/null +++ b/OpenUtauMobile/Views/NeutrinoSingerSetupView.cs @@ -0,0 +1,5 @@ +namespace OpenUtauMobile.Views +{ + /// NEUTRINO 专用内置安装入口。 + public sealed class NeutrinoSingerSetupView : BuiltinSingerSetupView; +} From ddedd4d957cd0b40077995411626e6b1341b31b5 Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Sun, 1 Nov 2026 15:33:07 +0800 Subject: [PATCH 05/45] =?UTF-8?q?optimize:=20=E4=BC=98=E5=8C=96=E6=8F=92?= =?UTF-8?q?=E4=BB=B6=E6=AD=8C=E6=89=8B=E5=AE=89=E8=A3=85=E6=B5=81=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ViewModels/PluginSingerSetupViewModel.cs | 90 +++++++++++-------- .../Views/PluginSingerSetupView.axaml | 79 ++++++++++------ 2 files changed, 106 insertions(+), 63 deletions(-) diff --git a/OpenUtauMobile/ViewModels/PluginSingerSetupViewModel.cs b/OpenUtauMobile/ViewModels/PluginSingerSetupViewModel.cs index 502e1457..6b020b2a 100644 --- a/OpenUtauMobile/ViewModels/PluginSingerSetupViewModel.cs +++ b/OpenUtauMobile/ViewModels/PluginSingerSetupViewModel.cs @@ -29,24 +29,27 @@ public sealed class PluginSingerSetupViewModel : NavigateViewModelBase, ISingerI [Reactive] public bool IsProgressIndeterminate { get; private set; } = true; [Reactive] public double ProgressPercent { get; private set; } [Reactive] public bool IsFinished { get; private set; } + [Reactive] public bool IsSuccessful { get; private set; } + [Reactive] public bool IsCancelled { get; private set; } + [Reactive] public bool IsPartiallyInstalled { get; private set; } + [Reactive] public bool HasFailed { get; private set; } [Reactive] public string Title { get; private set; } = ""; [Reactive] public string StepText { get; private set; } = ""; [Reactive] public string Message { get; private set; } = ""; [Reactive] public string Error { get; private set; } = ""; - [Reactive] public string Summary { get; private set; } = ""; [Reactive] public bool CanBack { get; private set; } [Reactive] public bool CanNext { get; private set; } - [Reactive] public bool CanPrepare { get; private set; } [Reactive] public bool CanInstall { get; private set; } [Reactive] public IReadOnlyList Fields { get; private set; } = []; [Reactive] public IReadOnlyList Previews { get; private set; } = []; - [Reactive] public IReadOnlyList StepTitles { get; private set; } = []; + /// 终态只显示一次明确结果,不保留安装步骤标题。 + public string ResultTitle => L.S(IsCancelled ? "SingerSetup.Cancelled" : IsPartiallyInstalled + ? "SingerSetup.PartialFailure" : HasFailed ? "SingerSetup.Failed" : "SingerSetup.Success"); [Reactive] public InstallTarget SelectedTarget { get; set; } public ImmutableArray Targets => controller.Targets; public bool HasTargetChoices => Targets.Length > 1; public ReactiveCommand NextCommand { get; } public ReactiveCommand BackCommand { get; } - public ReactiveCommand PrepareCommand { get; } public ReactiveCommand InstallCommand { get; } public ReactiveCommand ExitCommand { get; } private readonly IDisposable targetSubscription; @@ -67,28 +70,9 @@ public PluginSingerSetupViewModel(MainViewModel navigator, RegisteredSingerInsta this.WhenAnyValue(item => item.CanNext, item => item.IsBusy, item => item.IsClosing, (ready, busy, closing) => ready && !busy && !closing)); BackCommand = ReactiveCommand.CreateFromTask(() => RunAsync(async () => Apply(await controller.BackAsync())), this.WhenAnyValue(item => item.CanBack, item => item.IsBusy, item => item.IsClosing, (ready, busy, closing) => ready && !busy && !closing)); - PrepareCommand = ReactiveCommand.CreateFromTask(() => RunAsync(async () => - { - PreparedInstall plan = await controller.PrepareAsync(Submission(), SelectedTarget.Id, progress); - Summary = string.Join("\n", new[] { plan.Summary }.Concat(plan.DestinationPaths) - .Concat(plan.Diagnostics.IsDefault ? [] : plan.Diagnostics.Select(item => item.Message))); - CanInstall = true; - }), this.WhenAnyValue(item => item.CanPrepare, item => item.IsBusy, item => item.IsClosing, (ready, busy, closing) => ready && !busy && !closing)); - InstallCommand = ReactiveCommand.CreateFromTask(() => RunAsync(async () => - { - try - { - InstallResult result = await controller.InstallAsync(controller.Plan!.PlanId, progress); - Message = L.S(result.Status == InstallResultStatus.Committed ? "SingerSetup.InstallComplete" : "SingerSetup.PartialFailure"); - Error = string.Join("\n", result.Diagnostics.IsDefault ? [] : result.Diagnostics.Select(item => item.Message)); - } - finally - { - IsFinished = true; - CanBack = CanNext = CanPrepare = CanInstall = false; - ClearContent(); - } - }), this.WhenAnyValue(item => item.CanInstall, item => item.IsBusy, item => item.IsClosing, (ready, busy, closing) => ready && !busy && !closing)); + InstallCommand = ReactiveCommand.CreateFromTask(() => RunAsync(InstallAsync), + this.WhenAnyValue(item => item.CanInstall, item => item.IsBusy, item => item.IsClosing, + (ready, busy, closing) => ready && !busy && !closing)); ExitCommand = ReactiveCommand.CreateFromTask(LeaveAsync); targetSubscription = this.WhenAnyValue(item => item.SelectedTarget).Subscribe(_ => Invalidate()); } @@ -110,21 +94,50 @@ private void Apply(InstallView view) InstallStep step = view.Steps.Single(item => item.Id == view.CurrentStepId); Title = step.Title; StepText = string.Format(L.S("SingerSetup.StepFormat"), view.Steps.IndexOf(step) + 1, view.Steps.Length); - StepTitles = view.Steps.Select(item => item.Title).ToArray(); - Fields = (step.Fields.IsDefault ? ImmutableArray.Empty : step.Fields) - .Select(item => new PluginFieldViewModel(item, Invalidate)).ToArray(); - Previews = (step.Content.IsDefault ? ImmutableArray.Empty : step.Content) - .Select(item => new InstallPreviewViewModel(item, controller)).ToArray(); + Fields = [.. (step.Fields.IsDefault ? ImmutableArray.Empty : step.Fields) + .Select(item => new PluginFieldViewModel(item, Invalidate))]; + Previews = [.. (step.Content.IsDefault ? ImmutableArray.Empty : step.Content) + .Select(item => new InstallPreviewViewModel(item.Title == step.Title ? item with { Title = "" } : item, controller))]; foreach (PluginDiagnostic diagnostic in view.Diagnostics.IsDefault ? [] : view.Diagnostics) Fields.FirstOrDefault(item => item.Descriptor.Id == diagnostic.FieldId)?.SetError(diagnostic.Message); Error = string.Join("\n", view.Diagnostics.IsDefault ? [] : view.Diagnostics.Select(item => item.Message)); CanBack = view.CanGoBack; CanNext = view.CanGoNext; - CanPrepare = view.CanPrepare && (view.Diagnostics.IsDefault || view.Diagnostics.All(item => item.Severity != PluginDiagnosticSeverity.Error)); + CanInstall = view.CanPrepare && (view.Diagnostics.IsDefault || view.Diagnostics.All(item => item.Severity != PluginDiagnosticSeverity.Error)); Invalidate(); } - private void Invalidate() { controller.InvalidatePlan(); CanInstall = false; Summary = ""; } + private void Invalidate() => controller.InvalidatePlan(); + + /// 单次安装操作内部完成计划准备;准备失败保留输入,提交结束后只保留结果。 + private async Task InstallAsync() + { + PreparedInstall plan = await controller.PrepareAsync(Submission(), SelectedTarget.Id, progress); + try + { + InstallResult result = await controller.InstallAsync(plan.PlanId, progress); + Finish(result.Status == InstallResultStatus.Committed, false, + result.Status == InstallResultStatus.PartialFailure, + string.Join("\n", result.Diagnostics.IsDefault ? [] : result.Diagnostics.Select(item => item.Message))); + } + catch (OperationCanceledException) { Finish(false, true, false, ""); } + catch (Exception exception) { Finish(false, false, false, exception.Message); } + } + + /// 清除步骤及操作状态,避免完成页残留许可证、进度或内部计划摘要。 + private void Finish(bool successful, bool cancelled, bool partial, string error) + { + IsSuccessful = successful; + IsCancelled = cancelled; + IsPartiallyInstalled = partial; + HasFailed = !successful && !cancelled && !partial; + CanBack = CanNext = CanInstall = false; + Title = StepText = Message = ""; + Error = error; + ClearContent(); + IsFinished = true; + this.RaisePropertyChanged(nameof(ResultTitle)); + } private async Task RunAsync(Func action) { @@ -133,15 +146,17 @@ private async Task RunAsync(Func action) TaskCompletionSource completion = new(TaskCreationOptions.RunContinuationsAsynchronously); operationCompletion = completion; Error = ""; + Message = ""; try { await action(); } - catch (OperationCanceledException) { Message = L.S("Common.Cancel"); } + catch (OperationCanceledException) { Finish(false, true, false, ""); } catch (Exception exception) { Error = exception.Message; if (exception is SingerInstallException failure) Fields.FirstOrDefault(item => item.Descriptor.Id == failure.FieldId)?.SetError(failure.Message); + if (controller.View == null) Finish(false, false, false, exception.Message); } - finally { IsBusy = false; completion.SetResult(); } + finally { IsBusy = false; Message = ""; completion.SetResult(); } } /// 导航和系统返回共用同一次取消收尾。 @@ -160,7 +175,7 @@ public async Task CloseSessionAsync() await controller.DisposeAsync(); if (operationCompletion != null) await operationCompletion.Task; IsSessionClosed = true; - CanBack = CanNext = CanPrepare = CanInstall = false; + CanBack = CanNext = CanInstall = false; ClearContent(); } public override void OnBackRequested() { _ = LeaveAsync(); } @@ -175,7 +190,7 @@ public void Dispose() { _ = controller.DisposeAsync(); ClearContent(); targetSubscription.Dispose(); - NextCommand.Dispose(); BackCommand.Dispose(); PrepareCommand.Dispose(); InstallCommand.Dispose(); ExitCommand.Dispose(); + NextCommand.Dispose(); BackCommand.Dispose(); InstallCommand.Dispose(); ExitCommand.Dispose(); } } @@ -187,6 +202,7 @@ public sealed class InstallPreviewViewModel : IDisposable public Bitmap? Image { get; } public bool HasImage => Image != null; public bool HasText => !string.IsNullOrEmpty(Text); + public bool HasTitle => !string.IsNullOrWhiteSpace(Title); public InstallPreviewViewModel(InstallContent content, SingerInstallController controller) { Title = content.Title; diff --git a/OpenUtauMobile/Views/PluginSingerSetupView.axaml b/OpenUtauMobile/Views/PluginSingerSetupView.axaml index 1a73a690..bd98a3d6 100644 --- a/OpenUtauMobile/Views/PluginSingerSetupView.axaml +++ b/OpenUtauMobile/Views/PluginSingerSetupView.axaml @@ -1,4 +1,4 @@ - - + + + + @@ -342,7 +402,7 @@ Opacity="0.10" Background="{DynamicResource Sem.Color.OnSurfaceVariant}" /> - + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenUtauMobile/Views/SingerDetailView.axaml b/OpenUtauMobile/Views/SingerDetailView.axaml index 7ab7c908..00fda3f2 100644 --- a/OpenUtauMobile/Views/SingerDetailView.axaml +++ b/OpenUtauMobile/Views/SingerDetailView.axaml @@ -149,7 +149,7 @@ - + - + Date: Mon, 2 Nov 2026 00:27:32 +0800 Subject: [PATCH 07/45] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E6=8A=A5?= =?UTF-8?q?=E9=94=99=E5=BC=B9=E7=AA=97=E8=AF=A6=E6=83=85=E8=A2=AB=E9=81=AE?= =?UTF-8?q?=E4=BD=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controls/ErrorDialogPopup.axaml | 79 ++++++++++--------- .../Controls/ErrorDialogPopup.axaml.cs | 3 +- .../Controls/Styles/ErrorDialogPopup.axaml | 11 ++- .../Services/PluginLoadErrorReporter.cs | 14 +++- .../SingerPlugins/SingerDiscoveryService.cs | 4 +- .../SingerPlugins/SingerPluginService.cs | 2 +- .../ViewModels/ErrorDialogViewModel.cs | 24 +++--- 7 files changed, 79 insertions(+), 58 deletions(-) diff --git a/OpenUtauMobile/Controls/ErrorDialogPopup.axaml b/OpenUtauMobile/Controls/ErrorDialogPopup.axaml index 3142e927..b99f71e4 100644 --- a/OpenUtauMobile/Controls/ErrorDialogPopup.axaml +++ b/OpenUtauMobile/Controls/ErrorDialogPopup.axaml @@ -18,7 +18,10 @@ - + + + + @@ -47,42 +50,42 @@ - - - - - - - - - + + + + + + + + + + + + + diff --git a/OpenUtauMobile/Controls/ErrorDialogPopup.axaml.cs b/OpenUtauMobile/Controls/ErrorDialogPopup.axaml.cs index 899852b3..7a12665e 100644 --- a/OpenUtauMobile/Controls/ErrorDialogPopup.axaml.cs +++ b/OpenUtauMobile/Controls/ErrorDialogPopup.axaml.cs @@ -7,7 +7,7 @@ public partial class ErrorDialogPopup : PopupDialogControl { private bool _detailExpanded; - protected override PopupDialogWidthPreset WidthPreset => PopupDialogWidthPreset.Regular; + protected override PopupDialogWidthPreset WidthPreset => PopupDialogWidthPreset.Wide; public ErrorDialogPopup() { @@ -18,6 +18,7 @@ private void OnDetailToggleClicked(object? sender, RoutedEventArgs e) { _detailExpanded = !_detailExpanded; DetailPanel.IsVisible = _detailExpanded; + MessagePanel.IsVisible = !_detailExpanded; DetailChevron.Kind = _detailExpanded ? PackIconPhosphorIconsKind.CaretUp : PackIconPhosphorIconsKind.CaretDown; diff --git a/OpenUtauMobile/Controls/Styles/ErrorDialogPopup.axaml b/OpenUtauMobile/Controls/Styles/ErrorDialogPopup.axaml index cfe84971..278169b2 100644 --- a/OpenUtauMobile/Controls/Styles/ErrorDialogPopup.axaml +++ b/OpenUtauMobile/Controls/Styles/ErrorDialogPopup.axaml @@ -1,14 +1,17 @@ + xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" + xmlns:semantic="clr-namespace:OpenUtauMobile.Themes.OpenUtauMobile.Tokens.Semantic"> - + diff --git a/OpenUtauMobile/Services/PluginLoadErrorReporter.cs b/OpenUtauMobile/Services/PluginLoadErrorReporter.cs index 03e16f89..4219b941 100644 --- a/OpenUtauMobile/Services/PluginLoadErrorReporter.cs +++ b/OpenUtauMobile/Services/PluginLoadErrorReporter.cs @@ -24,11 +24,23 @@ private PluginLoadErrorReporter() public void Emit(LogEvent logEvent) { - if (logEvent.Level < LogEventLevel.Warning || logEvent.Exception == null) + if (logEvent.Level < LogEventLevel.Warning) { return; } + // 仅元数据检查失败也应进入统一通知,不在歌手目录中生成错误条目。 + if (logEvent.MessageTemplate.Text == "Plugin assembly unavailable: {Location}: {Message}" + && logEvent.Properties.TryGetValue("Location", out LogEventPropertyValue? source) + && source is ScalarValue { Value: string unavailable } + && logEvent.Properties.TryGetValue("Message", out LogEventPropertyValue? detail) + && detail is ScalarValue { Value: string message }) + { + _pendingErrors.Enqueue(new IOException(unavailable, logEvent.Exception ?? new InvalidOperationException(message))); + return; + } + if (logEvent.Exception == null) return; + // 上游没有公开逐文件加载结果;按结构化模板识别,不解析日志文件或本地化文本。 switch (logEvent.MessageTemplate.Text) { diff --git a/OpenUtauMobile/Services/SingerPlugins/SingerDiscoveryService.cs b/OpenUtauMobile/Services/SingerPlugins/SingerDiscoveryService.cs index 1a230398..d211d492 100644 --- a/OpenUtauMobile/Services/SingerPlugins/SingerDiscoveryService.cs +++ b/OpenUtauMobile/Services/SingerPlugins/SingerDiscoveryService.cs @@ -212,9 +212,7 @@ private void Publish(List found, List entries, bool re ExternalSingerPluginService.RefreshSingers(); next = SingerManager.Inst.Singers.ToDictionary(item => item.Key, item => item.Value, StringComparer.Ordinal); } - foreach (PluginDiagnostic diagnostic in SingerPluginService.Diagnostics) - entries.Add(new("host:plugin-errors", new(diagnostic.Location ?? "", diagnostic.Location ?? "", - SingerAvailability.Unavailable, Diagnostics: [diagnostic]))); + // 插件程序集错误由启动错误通知展示,不能伪装成不可用歌手占据管理列表。 foreach (UTrack track in DocManager.Inst.Project.tracks) { string? id = track.Singer?.Id ?? track.singer; diff --git a/OpenUtauMobile/Services/SingerPlugins/SingerPluginService.cs b/OpenUtauMobile/Services/SingerPlugins/SingerPluginService.cs index a9897beb..81f0fc4c 100644 --- a/OpenUtauMobile/Services/SingerPlugins/SingerPluginService.cs +++ b/OpenUtauMobile/Services/SingerPlugins/SingerPluginService.cs @@ -99,7 +99,7 @@ public static void Initialize() InspectUnloadedEntries(); } - /// 只读检查未载入的声明入口,补充 Core 日志之外可在管理页定位的依赖及位数诊断。 + /// 只读检查未载入的声明入口,补充启动错误通知中的依赖及位数诊断。 private static void InspectUnloadedEntries() { string root = PathManager.Inst.PluginsPath; diff --git a/OpenUtauMobile/ViewModels/ErrorDialogViewModel.cs b/OpenUtauMobile/ViewModels/ErrorDialogViewModel.cs index 0e85d560..0acacbbb 100644 --- a/OpenUtauMobile/ViewModels/ErrorDialogViewModel.cs +++ b/OpenUtauMobile/ViewModels/ErrorDialogViewModel.cs @@ -20,6 +20,8 @@ public class ErrorDialogViewModel : PopupViewModelBase public string Title { get; } = L.S("ErrorDialog.Title"); public string Message { get; } public string Detail { get; } + /// 详情展示和复制共用的完整报告,保留所有内部异常与堆栈。 + public string ReportText { get; } public bool HasDetail => !string.IsNullOrWhiteSpace(Detail); public bool HasMissingPackage { get; } @@ -62,6 +64,16 @@ public ErrorDialogViewModel(ErrorMessageNotification notification) Detail = string.Empty; } + StringBuilder report = new(); + report.AppendLine(Title); + report.AppendLine(Message); + if (HasDetail) + { + report.AppendLine(); + report.Append(Detail); + } + ReportText = report.ToString(); + CloseCommand = ReactiveCommand.Create(RequestBack); CopyCommand = ReactiveCommand.CreateFromTask(CopyErrorAsync); OpenDependencyManagerCommand = ReactiveCommand.Create(() => @@ -72,18 +84,10 @@ public ErrorDialogViewModel(ErrorMessageNotification notification) }); } + /// 复制与展开详情完全相同的报告,不另行拼接或截断。 private async Task CopyErrorAsync() { - StringBuilder text = new(); - text.AppendLine(Title); - text.AppendLine(Message); - if (HasDetail) - { - text.AppendLine(); - text.Append(Detail); - } - - bool copied = await ServiceHub.ClipboardService.SetTextAsync(text.ToString()); + bool copied = await ServiceHub.ClipboardService.SetTextAsync(ReportText); ToastService.Enqueue(L.S(copied ? "ErrorDialog.CopySucceeded" : "ErrorDialog.CopyFailed")); From 32cf8e031311cb1f2d15c31f6978dd9665315a63 Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Tue, 3 Nov 2026 01:08:30 +0800 Subject: [PATCH 08/45] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E6=9E=84?= =?UTF-8?q?=E5=BB=BA=E6=97=B6=E6=B7=B7=E5=85=A5=E5=88=AB=E7=9A=84=E5=B9=B3?= =?UTF-8?q?=E5=8F=B0=E5=9C=B0=E5=8C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/actions/setup-worldline/action.yml | 2 +- .github/workflows/build-all-platforms.yml | 12 - .github/workflows/build-android.yml | 119 +------- .github/workflows/build-browser.yml | 9 - .github/workflows/build-ios.yml | 102 ------- .github/workflows/pr-requirements.yml | 13 - AGENTS.md | 4 + OpenUtau.Core/OpenUtau.Core.csproj | 19 +- .../OpenUtau.Plugin.Builtin.csproj | 6 +- .../OpenUtauMobile.DesktopUI.csproj | 2 +- .../OpenUtauMobile.Linux.csproj | 1 + .../OpenUtauMobile.MacOS.csproj | 1 + .../OpenUtauMobile.Plugin.Abstractions.csproj | 2 +- .../OpenUtauMobile.Plugin.Renderers.csproj | 2 +- .../OpenUtauMobile.Windows.csproj | 4 +- OpenUtauMobile/OpenUtauMobile.csproj | 2 +- .../BuiltinSingerInstallTransaction.cs | 18 +- .../Services/PluginManagementService.cs | 3 +- .../SingerPlugins/BuiltinSingerMaintenance.cs | 3 +- .../Installation/InstallFileOperations.cs | 14 +- .../Installation/InstallWorkspace.cs | 12 +- .../Installation/SingerInstallController.cs | 1 - .../SingerPlugins/PluginSettingsService.cs | 3 - .../SingerPlugins/SingerPluginService.cs | 11 +- native/game/GameNative.targets | 1 - native/game/README.md | 22 +- native/game/build.py | 21 +- native/game/verify.py | 59 ---- native/verify-android-runtime.py | 86 ------ native/verify-runtime.py | 31 -- native/worldline/README.md | 28 +- native/worldline/WorldlineNative.targets | 1 - native/worldline/build.py | 19 +- native/worldline/verify.py | 271 ------------------ native/worldline/verify_browser.py | 73 ----- native/worldline/verify_static.py | 94 ------ 36 files changed, 60 insertions(+), 1011 deletions(-) delete mode 100644 native/game/verify.py delete mode 100644 native/verify-android-runtime.py delete mode 100644 native/verify-runtime.py delete mode 100644 native/worldline/verify.py delete mode 100644 native/worldline/verify_browser.py delete mode 100644 native/worldline/verify_static.py diff --git a/.github/actions/setup-worldline/action.yml b/.github/actions/setup-worldline/action.yml index 1e8f13e9..18ece9e0 100644 --- a/.github/actions/setup-worldline/action.yml +++ b/.github/actions/setup-worldline/action.yml @@ -2,7 +2,7 @@ name: Setup native Bazel build tools description: Install Python and the pinned Bazelisk for source builds inputs: architecture: - description: Python architecture for native ABI verification + description: Python architecture for native build tools default: x64 runs: using: composite diff --git a/.github/workflows/build-all-platforms.yml b/.github/workflows/build-all-platforms.yml index fbd809cf..21b4f46a 100644 --- a/.github/workflows/build-all-platforms.yml +++ b/.github/workflows/build-all-platforms.yml @@ -137,10 +137,6 @@ jobs: -p:SourceCommit=${{ inputs.source_sha }} \ -p:ActionRunId=${{ inputs.action_run_id }} - - name: Verify native runtime loading - shell: bash - run: python native/verify-runtime.py "artifacts/publish/${{ matrix.rid }}" - - name: Package Linux ${{ matrix.arch }} shell: bash run: | @@ -231,10 +227,6 @@ jobs: -p:SourceCommit=${{ inputs.source_sha }} ` -p:ActionRunId=${{ inputs.action_run_id }} - - name: Verify native runtime loading - shell: bash - run: python native/verify-runtime.py "artifacts/publish/${{ matrix.rid }}" - - name: Package Windows ${{ matrix.arch }} shell: pwsh run: | @@ -322,10 +314,6 @@ jobs: -p:SourceCommit=${{ inputs.source_sha }} \ -p:ActionRunId=${{ inputs.action_run_id }} - - name: Verify native runtime loading - shell: bash - run: python native/verify-runtime.py "artifacts/publish/${{ matrix.rid }}" - - name: Package macOS ${{ matrix.arch }} shell: bash run: | diff --git a/.github/workflows/build-android.yml b/.github/workflows/build-android.yml index 79ba8d02..07f03c62 100644 --- a/.github/workflows/build-android.yml +++ b/.github/workflows/build-android.yml @@ -89,11 +89,9 @@ jobs: shell: bash run: | set -euo pipefail - command -v sdkmanager NDK_VERSION="$(tr -d '\r\n' < native/game/android-ndk-version.txt)" SDK_ROOT="${ANDROID_HOME:-${ANDROID_SDK_ROOT:?Android SDK is required}}" sdkmanager --sdk_root="$SDK_ROOT" "ndk;$NDK_VERSION" - test -f "$SDK_ROOT/ndk/$NDK_VERSION/source.properties" echo "OPUM_ANDROID_NDK=$SDK_ROOT/ndk/$NDK_VERSION" >> "$GITHUB_ENV" - name: Create Swap Space @@ -143,8 +141,6 @@ jobs: set -euo pipefail signing_args=(-p:AndroidKeyStore=false) if [ "$RELEASE_SIGNING" = "true" ]; then - test -s signing.keystore - test -n "$KEYSTORE_PASSWORD" && test -n "$KEY_ALIAS" && test -n "$KEY_PASSWORD" signing_args=(-p:AndroidKeyStore=true "-p:AndroidSigningKeyStore=$GITHUB_WORKSPACE/signing.keystore" "-p:AndroidSigningStorePass=$KEYSTORE_PASSWORD" @@ -167,116 +163,18 @@ jobs: -p:AndroidPackageFormat=apk \ "${signing_args[@]}" - - name: Verify and prepare Android artifact + - name: Prepare Android artifact shell: bash run: | set -euo pipefail PUBLISH_DIR="OpenUtauMobile.Android/bin/Release/net10.0-android36.0/${{ inputs.rid }}/publish" ARTIFACT_DIR="artifacts/android-${{ inputs.arch }}" - VERIFY_DIR="artifacts/verification-android-${{ inputs.arch }}" - - case "${{ inputs.rid }}" in - android-arm64) EXPECTED_ABI=arm64-v8a ;; - android-arm) EXPECTED_ABI=armeabi-v7a ;; - android-x64) EXPECTED_ABI=x86_64 ;; - android-x86) EXPECTED_ABI=x86 ;; - *) echo "::error::不支持的 Android RID:${{ inputs.rid }}"; exit 1 ;; - esac - - mkdir -p "$ARTIFACT_DIR" "$VERIFY_DIR/native" - echo "===== Publish files =====" - find "$PUBLISH_DIR" -maxdepth 1 -type f -printf '%f\n' - - mapfile -t SIGNED_APKS < <(find "$PUBLISH_DIR" -maxdepth 1 -type f -iname '*-signed.apk' -print) - if [ "${#SIGNED_APKS[@]}" -ne 1 ]; then - echo "::error::应当生成且仅生成一个已签名 APK,实际为 ${#SIGNED_APKS[@]} 个" - exit 1 - fi - SIGNED_APK="${SIGNED_APKS[0]}" - python native/verify-android-runtime.py "$SIGNED_APK" "${{ inputs.rid }}" - - ANDROID_SDK="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-}}" - if [ -z "$ANDROID_SDK" ] || [ ! -d "$ANDROID_SDK/build-tools" ]; then - echo "::error::找不到 Android SDK build-tools 目录,无法核对 APK 版本号" - exit 1 - fi - AAPT="$(find "$ANDROID_SDK/build-tools" -type f -name aapt -print | sort -V | tail -n 1)" - if [ -z "$AAPT" ]; then - echo "::error::找不到 Android Asset Packaging Tool,无法核对 APK 版本号" - exit 1 - fi - PACKAGE_BADGING="$("$AAPT" dump badging "$SIGNED_APK")" - APK_VERSION_CODE="$(sed -n "s/.*versionCode='\([^']*\)'.*/\1/p" <<< "$PACKAGE_BADGING")" - APK_VERSION_NAME="$(sed -n "s/.*versionName='\([^']*\)'.*/\1/p" <<< "$PACKAGE_BADGING")" - if [ "$APK_VERSION_CODE" != "${{ inputs.build_number }}" ]; then - echo "::error::APK versionCode 未继承调用方构建号。期望 ${{ inputs.build_number }},实际 $APK_VERSION_CODE" - exit 1 - fi - if [ "$APK_VERSION_NAME" != "${{ inputs.version }}" ]; then - echo "::error::APK versionName 未继承调用方版本。期望 ${{ inputs.version }},实际 $APK_VERSION_NAME" - exit 1 - fi - - mapfile -t PACKAGED_ABIS < <( - unzip -Z1 "$SIGNED_APK" | - sed -n 's#^lib/\([^/]*\)/.*\.so$#\1#p' | - sort -u - ) - if [ "${#PACKAGED_ABIS[@]}" -ne 1 ] || [ "${PACKAGED_ABIS[0]}" != "$EXPECTED_ABI" ]; then - printf '::error::APK 原生 ABI 与 RID 不一致。期望 %s,实际:%s\n' \ - "$EXPECTED_ABI" "${PACKAGED_ABIS[*]:-}" - exit 1 - fi - - for LIBRARY in libworldline.so libonnxruntime.so libonnxruntime4j_jni.so libopum_game.so; do - ENTRY="lib/$EXPECTED_ABI/$LIBRARY" - COUNT="$(unzip -Z1 "$SIGNED_APK" | grep -Fxc "$ENTRY" || true)" - if [ "$COUNT" -ne 1 ]; then - echo "::error::$ENTRY 应当在 APK 中恰好出现一次,实际为 $COUNT 次" - exit 1 - fi - unzip -p "$SIGNED_APK" "$ENTRY" > "$VERIFY_DIR/native/$LIBRARY" - done - - for LIBRARY in "$VERIFY_DIR/native/"*.so; do - DYNAMIC_INFO="$VERIFY_DIR/$(basename "$LIBRARY").dynamic.txt" - readelf -d "$LIBRARY" > "$DYNAMIC_INFO" - if grep -E 'libdl\.so\.2|libc\.so\.6|libm\.so\.6|libpthread\.so\.0|librt\.so\.1|ld-linux' "$DYNAMIC_INFO"; then - echo "::error::$(basename "$LIBRARY") 包含 Linux/glibc 依赖,不是 Android 原生库" - exit 1 - fi - done - - find "$VERIFY_DIR/native" -maxdepth 1 -type f -name '*.so' -print0 | - sort -z | - xargs -0 sha256sum | - sed "s#$VERIFY_DIR/native/##" > "$VERIFY_DIR/native-libraries.sha256" - - cat > "$VERIFY_DIR/build-contract.txt" < "$PACKAGE.sha256" - sha256sum --check "$PACKAGE.sha256" - name: Upload Android ${{ inputs.arch }} uses: actions/upload-artifact@v7 @@ -295,13 +192,3 @@ jobs: artifacts/android-${{ inputs.arch }}/OpenUtauMobile-build${{ inputs.build_number }}-android-${{ inputs.arch }}.apk.sha256 if-no-files-found: error compression-level: 0 - - - name: Upload Android ${{ inputs.arch }} verification - uses: actions/upload-artifact@v7 - with: - name: verification-android-${{ inputs.arch }} - path: | - artifacts/verification-android-${{ inputs.arch }}/build-contract.txt - artifacts/verification-android-${{ inputs.arch }}/native-libraries.sha256 - artifacts/verification-android-${{ inputs.arch }}/*.dynamic.txt - if-no-files-found: error diff --git a/.github/workflows/build-browser.yml b/.github/workflows/build-browser.yml index bd0b0a9d..b3fccf65 100644 --- a/.github/workflows/build-browser.yml +++ b/.github/workflows/build-browser.yml @@ -51,11 +51,8 @@ jobs: -c Release -o artifacts/publish/browser-wasm \ -p:BuildNumber="$BUILD_NUMBER" -p:SourceCommit="$SOURCE_SHA" \ -p:ActionRunId="$ACTION_RUN_ID" "${args[@]}" - - name: Verify Worldline WASM ABI - run: python native/worldline/verify_browser.py artifacts/worldline-native/browser-wasm - name: Package Browser static files run: | - test -f artifacts/publish/browser-wasm/wwwroot/licenses/Worldline/worldline-build.json tar -C artifacts/publish/browser-wasm/wwwroot -czf artifacts/OpenUtauMobile-browser-wasm.tar.gz . cd artifacts sha256sum OpenUtauMobile-browser-wasm.tar.gz > OpenUtauMobile-browser-wasm.tar.gz.sha256 @@ -67,9 +64,3 @@ jobs: artifacts/OpenUtauMobile-browser-wasm.tar.gz artifacts/OpenUtauMobile-browser-wasm.tar.gz.sha256 if-no-files-found: error - - name: Upload native verification evidence - uses: actions/upload-artifact@v4 - with: - name: worldline-browser-wasm - path: artifacts/worldline-native/browser-wasm/ - if-no-files-found: error diff --git a/.github/workflows/build-ios.yml b/.github/workflows/build-ios.yml index 1f8e196f..267df2fc 100644 --- a/.github/workflows/build-ios.yml +++ b/.github/workflows/build-ios.yml @@ -61,35 +61,6 @@ jobs: echo "BUILD_MACHINE=${RUNNER_OS} / $(uname -srm)" >> "$GITHUB_ENV" mkdir -p "${GITHUB_WORKSPACE}/artifacts/ios-arm64-logs" - - name: Validate iOS Toolchain - shell: bash - run: | - set -euo pipefail - - echo "::group::.NET and installed workloads" - dotnet --info - dotnet workload list - echo "::endgroup::" - - echo "::group::Xcode and iPhoneOS SDK" - if [ ! -d "$DEVELOPER_DIR" ]; then - echo "::error::Required Xcode developer directory is missing: $DEVELOPER_DIR" - ls -1d /Applications/Xcode_*.app 2>/dev/null | sed -n '1,20p' || true - exit 1 - fi - - XCODE_VERSION="$(xcodebuild -version | awk '/^Xcode / { print $2 }')" - if [[ "$XCODE_VERSION" != "27.0" && "$XCODE_VERSION" != 27.0.* ]]; then - echo "::error::Expected Xcode 27.0, selected $XCODE_VERSION from $DEVELOPER_DIR" - exit 1 - fi - - echo "Developer directory: $DEVELOPER_DIR" - xcodebuild -version - echo "iPhoneOS SDK: $(xcrun --sdk iphoneos --show-sdk-version)" - echo "iPhoneOS SDK path: $(xcrun --sdk iphoneos --show-sdk-path)" - echo "::endgroup::" - - name: Restore iOS Workload shell: bash run: | @@ -145,78 +116,6 @@ jobs: ls -lh "$IPA_PATH" - - name: Validate iOS ARM64 Mono AOT Unsigned IPA - shell: bash - run: | - set -euo pipefail - - IPA_PATH="${GITHUB_WORKSPACE}/artifacts/ios-arm64/OpenUtauMobile-build${{ inputs.build_number }}-ios-arm64-mono-aot-unsigned.ipa" - VERIFY_DIR="${RUNNER_TEMP}/opum-ios-arm64-verify" - - unzip -tq "$IPA_PATH" - mkdir -p "$VERIFY_DIR" - unzip -q "$IPA_PATH" -d "$VERIFY_DIR" - - APP_COUNT="$(find "$VERIFY_DIR/Payload" -maxdepth 1 -type d -name '*.app' | wc -l | tr -d ' ')" - if [ "$APP_COUNT" != "1" ]; then - echo "::error::IPA must contain exactly one app bundle, found $APP_COUNT" - exit 1 - fi - - APP_DIR="$(find "$VERIFY_DIR/Payload" -maxdepth 1 -type d -name '*.app' -print -quit)" - INFO_PLIST="$APP_DIR/Info.plist" - EXECUTABLE="$(plutil -extract CFBundleExecutable raw "$INFO_PLIST")" - BUNDLE_ID="$(plutil -extract CFBundleIdentifier raw "$INFO_PLIST")" - DISPLAY_VERSION="$(plutil -extract CFBundleShortVersionString raw "$INFO_PLIST")" - BUILD_VERSION="$(plutil -extract CFBundleVersion raw "$INFO_PLIST")" - PLATFORM="$(plutil -extract CFBundleSupportedPlatforms.0 raw "$INFO_PLIST")" - ARCHS="$(lipo -archs "$APP_DIR/$EXECUTABLE")" - python native/worldline/verify_static.py \ - artifacts/worldline-native/ios-arm64/libworldline.a ios-arm64 \ - --nm "$(xcrun --find nm)" --app-bundle "$APP_DIR" - EXPECTED_BUNDLE_ID="$(dotnet msbuild \ - OpenUtauMobile.iOS/OpenUtauMobile.iOS.csproj \ - -nologo \ - -getProperty:ApplicationId \ - -p:Configuration=Release \ - -p:TargetFramework=net10.0-ios \ - -p:RuntimeIdentifier=ios-arm64)" - - if [ "$BUNDLE_ID" != "$EXPECTED_BUNDLE_ID" ]; then - echo "::error::Bundle ID is $BUNDLE_ID, expected $EXPECTED_BUNDLE_ID" - exit 1 - fi - if [ "$DISPLAY_VERSION" != "${{ inputs.version }}" ]; then - echo "::error::CFBundleShortVersionString is $DISPLAY_VERSION, expected ${{ inputs.version }}" - exit 1 - fi - if [ "$BUILD_VERSION" != "${{ inputs.build_number }}" ]; then - echo "::error::CFBundleVersion is $BUILD_VERSION, expected ${{ inputs.build_number }}" - exit 1 - fi - if [ "$PLATFORM" != "iPhoneOS" ]; then - echo "::error::IPA targets $PLATFORM instead of iPhoneOS" - exit 1 - fi - if [ "$ARCHS" != "arm64" ]; then - echo "::error::App executable architectures are $ARCHS instead of arm64" - exit 1 - fi - if [ -e "$APP_DIR/_CodeSignature" ] || [ -e "$APP_DIR/embedded.mobileprovision" ]; then - echo "::error::App bundle unexpectedly contains signing assets" - exit 1 - fi - if codesign --verify --deep --strict "$APP_DIR" 2>"$VERIFY_DIR/codesign.txt"; then - echo "::error::App bundle unexpectedly passed code-sign verification" - exit 1 - fi - - echo "Bundle ID: $BUNDLE_ID" - echo "Version: $DISPLAY_VERSION ($BUILD_VERSION)" - echo "Platform: $PLATFORM" - echo "Architectures: $ARCHS" - echo "Code signature: unsigned, verified" - - name: Upload iOS Failure Diagnostics if: failure() uses: actions/upload-artifact@v4 @@ -237,7 +136,6 @@ jobs: set -euo pipefail PACKAGE="OpenUtauMobile-build${{ inputs.build_number }}-ios-arm64-mono-aot-unsigned.ipa" shasum -a 256 "$PACKAGE" > "$PACKAGE.sha256" - shasum -a 256 --check "$PACKAGE.sha256" - name: Upload iOS ARM64 Mono AOT Unsigned IPA uses: actions/upload-artifact@v4 diff --git a/.github/workflows/pr-requirements.yml b/.github/workflows/pr-requirements.yml index 3e54f71c..cd891218 100644 --- a/.github/workflows/pr-requirements.yml +++ b/.github/workflows/pr-requirements.yml @@ -49,11 +49,9 @@ jobs: shell: bash run: | set -euo pipefail - command -v sdkmanager NDK_VERSION="$(tr -d '\r\n' < native/game/android-ndk-version.txt)" SDK_ROOT="${ANDROID_HOME:-${ANDROID_SDK_ROOT:?Android SDK is required}}" sdkmanager --sdk_root="$SDK_ROOT" "ndk;$NDK_VERSION" - test -f "$SDK_ROOT/ndk/$NDK_VERSION/source.properties" echo "OPUM_ANDROID_NDK=$SDK_ROOT/ndk/$NDK_VERSION" >> "$GITHUB_ENV" - name: Restore @@ -67,14 +65,3 @@ jobs: --no-restore \ -p:RuntimeIdentifier=android-arm64 \ -p:AndroidNdkDirectory="$OPUM_ANDROID_NDK" - - - name: Verify Android native packaging - shell: bash - run: | - set -euo pipefail - mapfile -t APKS < <(find OpenUtauMobile.Android/bin/Release/net10.0-android36.0/android-arm64 -maxdepth 1 -type f -iname '*-signed.apk') - if [ "${#APKS[@]}" -ne 1 ]; then - echo "::error::Expected exactly one signed APK; found ${#APKS[@]}" - exit 1 - fi - python native/verify-android-runtime.py "${APKS[0]}" android-arm64 diff --git a/AGENTS.md b/AGENTS.md index b7a54157..a94f9bb9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,6 +23,10 @@ - Always use collection expressions instead of such as `ToList()` or `ToArray()` when constructing collections. ## Verification +- Do not introduce defensive validation layers in the build graph or CI. +- Do not add non-temporary verification scripts unless explicitly requested. + Keep temporary investigation scripts outside the source tree and do not hook + them into normal builds or CI. - Before `dotnet build`, set `$env:AVALONIA_TELEMETRY_OPTOUT='1';` (or the equivalent environment variable in another shell). - Do not add new unit tests unless explicitly requested or the task requires them. - Run existing relevant tests when available and appropriate. diff --git a/OpenUtau.Core/OpenUtau.Core.csproj b/OpenUtau.Core/OpenUtau.Core.csproj index d0ac2b02..5b8ee372 100644 --- a/OpenUtau.Core/OpenUtau.Core.csproj +++ b/OpenUtau.Core/OpenUtau.Core.csproj @@ -1,7 +1,7 @@ - net10.0 + net10.0;net10.0-windows none true embedded @@ -41,7 +41,6 @@ Compile assets stay private: its root "Json" namespace would hide OpenUtau.Core.Json in referencing projects. --> - @@ -84,16 +83,16 @@ VogenRes.Designer.cs - - WINDOWS - - - - - - + + + + + + + + diff --git a/OpenUtau.Plugin.Builtin/OpenUtau.Plugin.Builtin.csproj b/OpenUtau.Plugin.Builtin/OpenUtau.Plugin.Builtin.csproj index 8dd4d9ca..2596110b 100644 --- a/OpenUtau.Plugin.Builtin/OpenUtau.Plugin.Builtin.csproj +++ b/OpenUtau.Plugin.Builtin/OpenUtau.Plugin.Builtin.csproj @@ -1,7 +1,7 @@  - net10.0 + net10.0;net10.0-windows none embedded enable @@ -9,10 +9,6 @@ CS0168;CS0162;CS0219;CS0649;CS0414;CS8600;CS8601;CS8602;CS8603;CS8604;CS8612;CS8618;CS8619;CS8625;CS8629;CS8714;CS8767;CS8769;CS0108 - - - - diff --git a/OpenUtauMobile.DesktopUI/OpenUtauMobile.DesktopUI.csproj b/OpenUtauMobile.DesktopUI/OpenUtauMobile.DesktopUI.csproj index 352ec67f..650a794d 100644 --- a/OpenUtauMobile.DesktopUI/OpenUtauMobile.DesktopUI.csproj +++ b/OpenUtauMobile.DesktopUI/OpenUtauMobile.DesktopUI.csproj @@ -1,6 +1,6 @@ - net10.0 + net10.0;net10.0-windows enable true diff --git a/OpenUtauMobile.Linux/OpenUtauMobile.Linux.csproj b/OpenUtauMobile.Linux/OpenUtauMobile.Linux.csproj index c0092550..c1f783c7 100644 --- a/OpenUtauMobile.Linux/OpenUtauMobile.Linux.csproj +++ b/OpenUtauMobile.Linux/OpenUtauMobile.Linux.csproj @@ -9,6 +9,7 @@ + diff --git a/OpenUtauMobile.MacOS/OpenUtauMobile.MacOS.csproj b/OpenUtauMobile.MacOS/OpenUtauMobile.MacOS.csproj index 0ca47a1d..b6a82c39 100644 --- a/OpenUtauMobile.MacOS/OpenUtauMobile.MacOS.csproj +++ b/OpenUtauMobile.MacOS/OpenUtauMobile.MacOS.csproj @@ -10,6 +10,7 @@ + diff --git a/OpenUtauMobile.Plugin.Abstractions/OpenUtauMobile.Plugin.Abstractions.csproj b/OpenUtauMobile.Plugin.Abstractions/OpenUtauMobile.Plugin.Abstractions.csproj index d976f81d..1e4e7181 100644 --- a/OpenUtauMobile.Plugin.Abstractions/OpenUtauMobile.Plugin.Abstractions.csproj +++ b/OpenUtauMobile.Plugin.Abstractions/OpenUtauMobile.Plugin.Abstractions.csproj @@ -1,6 +1,6 @@ - net10.0 + net10.0;net10.0-windows enable enable 1.0.0 diff --git a/OpenUtauMobile.Plugin.Renderers/OpenUtauMobile.Plugin.Renderers.csproj b/OpenUtauMobile.Plugin.Renderers/OpenUtauMobile.Plugin.Renderers.csproj index 22fc27f3..4ca24e01 100644 --- a/OpenUtauMobile.Plugin.Renderers/OpenUtauMobile.Plugin.Renderers.csproj +++ b/OpenUtauMobile.Plugin.Renderers/OpenUtauMobile.Plugin.Renderers.csproj @@ -1,7 +1,7 @@  - net10.0 + net10.0;net10.0-windows preview enable enable diff --git a/OpenUtauMobile.Windows/OpenUtauMobile.Windows.csproj b/OpenUtauMobile.Windows/OpenUtauMobile.Windows.csproj index 4a94e078..78b5cdfb 100644 --- a/OpenUtauMobile.Windows/OpenUtauMobile.Windows.csproj +++ b/OpenUtauMobile.Windows/OpenUtauMobile.Windows.csproj @@ -14,7 +14,9 @@ - + + + diff --git a/OpenUtauMobile/OpenUtauMobile.csproj b/OpenUtauMobile/OpenUtauMobile.csproj index 3f17832c..94f9a24d 100644 --- a/OpenUtauMobile/OpenUtauMobile.csproj +++ b/OpenUtauMobile/OpenUtauMobile.csproj @@ -1,6 +1,6 @@ - net10.0 + net10.0;net10.0-windows enable preview true diff --git a/OpenUtauMobile/Services/BuiltinSingerInstallTransaction.cs b/OpenUtauMobile/Services/BuiltinSingerInstallTransaction.cs index 8c3cc35b..071f7d1b 100644 --- a/OpenUtauMobile/Services/BuiltinSingerInstallTransaction.cs +++ b/OpenUtauMobile/Services/BuiltinSingerInstallTransaction.cs @@ -133,7 +133,6 @@ private async Task PublishAsync(bool overwrite, CancellationToken token) string relative = Path.GetRelativePath(payload, source); string destination = Resolve(targetRoot, relative); EnsureDirectory(Path.GetDirectoryName(destination)!); - RejectLinks(destination); if (Directory.Exists(destination) || !overwrite && File.Exists(destination)) throw new IOException($"{L.S("SingerSetup.TargetExists")} {destination}"); string? original = null; @@ -171,7 +170,6 @@ private async Task RollbackAsync() if (!change.Applied) continue; try { - RejectLinks(change.Path); if (File.Exists(change.Path)) File.SetAttributes(change.Path, File.GetAttributes(change.Path) & ~FileAttributes.ReadOnly); if (change.Original == null) { @@ -199,7 +197,6 @@ private async Task RollbackAsync() { try { - RejectLinks(directory); if (Directory.Exists(directory)) Directory.Delete(directory, false); } catch (Exception exception) { failures.Add(exception); } @@ -211,20 +208,18 @@ private async Task RollbackAsync() /// 按父子顺序登记新目录,回滚仅删除本会话创建的空目录。 private void EnsureDirectory(string path) { - RejectLinks(path); if (Directory.Exists(path)) return; if (!string.Equals(path, targetRoot, PathComparison)) EnsureDirectory(Path.GetDirectoryName(path)!); Directory.CreateDirectory(path); createdDirectories.Add(path); } - /// 显式检查链接后递归,不沿链接枚举会话外文件。 + /// 递归收集会话文件和目录,支持取消。 private static void Collect(string root, List files, List directories, CancellationToken token) { foreach (string path in Directory.EnumerateFileSystemEntries(root)) { token.ThrowIfCancellationRequested(); - if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0) throw new IOException("安装内容包含符号链接。"); if (Directory.Exists(path)) { directories.Add(path); @@ -246,17 +241,6 @@ private static string Resolve(string root, string relative) private static StringComparison PathComparison => OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; - /// 检查目标根以内的现有路径,避免覆盖或删除链接所指向的内容。 - private void RejectLinks(string path) - { - for (string? current = path; current != null; current = Path.GetDirectoryName(current)) - { - if ((File.Exists(current) || Directory.Exists(current)) && - (File.GetAttributes(current) & FileAttributes.ReparsePoint) != 0) throw new IOException("安装目标包含符号链接。"); - if (string.Equals(current, targetRoot, PathComparison)) break; - } - } - /// 异步复制支持在大文件中途取消,失败的临时文件由会话收尾清理。 private static async Task CopyAsync(string source, string destination, CancellationToken token) { diff --git a/OpenUtauMobile/Services/PluginManagementService.cs b/OpenUtauMobile/Services/PluginManagementService.cs index 6ac6c0fe..68b151df 100644 --- a/OpenUtauMobile/Services/PluginManagementService.cs +++ b/OpenUtauMobile/Services/PluginManagementService.cs @@ -32,12 +32,11 @@ public static IReadOnlyList ListFiles() { Directory.CreateDirectory(Root); HashSet pending = ReadPendingDeletions(); - // 不跟随目录链接,避免将插件目录之外的文件纳入管理。 EnumerationOptions options = new() { RecurseSubdirectories = true, IgnoreInaccessible = false, - AttributesToSkip = FileAttributes.ReparsePoint, + AttributesToSkip = 0, }; return Directory.EnumerateFiles(Root, "*", options) .Where(path => string.Equals(Path.GetExtension(path), ".dll", StringComparison.OrdinalIgnoreCase)) diff --git a/OpenUtauMobile/Services/SingerPlugins/BuiltinSingerMaintenance.cs b/OpenUtauMobile/Services/SingerPlugins/BuiltinSingerMaintenance.cs index bdeaf13e..e829e246 100644 --- a/OpenUtauMobile/Services/SingerPlugins/BuiltinSingerMaintenance.cs +++ b/OpenUtauMobile/Services/SingerPlugins/BuiltinSingerMaintenance.cs @@ -24,7 +24,6 @@ internal static async Task UninstallAsync(USinger singer) if (path.StartsWith(Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)) + Path.DirectorySeparatorChar, InstallPaths.Comparison)) inside = true; if (!inside) throw new IOException("不能卸载歌手根目录或目录外的内容。"); - InstallPaths.RejectLinks(path); await SingerDiscoveryService.Instance.MaintainAsync(() => Task.Run(() => { singer.FreeMemory(); @@ -34,4 +33,4 @@ await SingerDiscoveryService.Instance.MaintainAsync(() => Task.Run(() => })); } } -} \ No newline at end of file +} diff --git a/OpenUtauMobile/Services/SingerPlugins/Installation/InstallFileOperations.cs b/OpenUtauMobile/Services/SingerPlugins/Installation/InstallFileOperations.cs index e63f6744..f10662af 100644 --- a/OpenUtauMobile/Services/SingerPlugins/Installation/InstallFileOperations.cs +++ b/OpenUtauMobile/Services/SingerPlugins/Installation/InstallFileOperations.cs @@ -39,7 +39,6 @@ public async ValueTask PublishAsync(PublishRequest request, RequireAbsent(destination); bool directory = request.Kind == InstallArtifactKind.Directory; if (directory ? !Directory.Exists(source) : !File.Exists(source)) throw new IOException("已校验的安装源不存在。"); - CheckTree(source); cancellationToken.ThrowIfCancellationRequested(); Directory.CreateDirectory(Path.GetDirectoryName(destination)!); progress.Report(new(InstallPhase.Publishing, request.DestinationRelativePath)); @@ -77,17 +76,9 @@ internal static void RequireAbsent(string path) if (File.Exists(path) || Directory.Exists(path)) throw new IOException($"安装目标已存在:{path}"); } - private static void CheckTree(string path) - { - InstallPaths.RejectLinks(path); - if (!Directory.Exists(path)) return; - foreach (string child in Directory.EnumerateFileSystemEntries(path)) CheckTree(child); - } - private static async Task CopyCheckedAsync(string source, string destination, bool directory, CancellationToken token) { token.ThrowIfCancellationRequested(); - InstallPaths.RejectLinks(source); if (directory) { Directory.CreateDirectory(destination); @@ -108,7 +99,6 @@ private static async Task CopyCheckedAsync(string source, string destination, bo public void RegisterTemporaryPath(string path) { InstallPaths.RequireInside(workspace.RootPath, path); - InstallPaths.RejectLinks(path); // Workspace 统一清理,无需再保存可与正式目录混淆的额外列表。 } @@ -119,7 +109,6 @@ public void RecordPublishedLocation(PublishedLocation location) RequirePlanned(path); if (!targets.Any(target => path.StartsWith(Path.TrimEndingDirectorySeparator(Path.GetFullPath(target.Path)) + Path.DirectorySeparatorChar, InstallPaths.Comparison))) throw new IOException("发布位置不属于配置的安装目标。"); - InstallPaths.RejectLinks(path); if (location.Kind == InstallArtifactKind.Directory ? !Directory.Exists(path) : !File.Exists(path)) throw new IOException("正式发布内容不存在。"); if (published.All(item => !string.Equals(item.Path, path, InstallPaths.Comparison))) published.Add(location with { Path = path }); @@ -137,10 +126,9 @@ internal void Cleanup() foreach (string path in staging.Append(workspace.RootPath)) try { - InstallPaths.RejectLinks(path); InstallPaths.DeleteTemporary(path); } catch (Exception exception) { Log.Warning(exception, "Failed to clean singer installation workspace {Path}", path); } } } -} \ No newline at end of file +} diff --git a/OpenUtauMobile/Services/SingerPlugins/Installation/InstallWorkspace.cs b/OpenUtauMobile/Services/SingerPlugins/Installation/InstallWorkspace.cs index d6ab4be1..6ebcb2b7 100644 --- a/OpenUtauMobile/Services/SingerPlugins/Installation/InstallWorkspace.cs +++ b/OpenUtauMobile/Services/SingerPlugins/Installation/InstallWorkspace.cs @@ -7,7 +7,7 @@ namespace OpenUtauMobile.Services.SingerPlugins.Installation { - /// 会话路径边界,同时拒绝越界和已有符号链接。 + /// 限定会话路径边界,拒绝越界路径。 internal static class InstallPaths { internal static StringComparison Comparison => OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; @@ -22,7 +22,6 @@ internal static string Resolve(string root, string relative) throw new IOException("安装路径不能包含空路径或上级目录。"); string full = Path.GetFullPath(Path.Combine(root, normalized)); RequireInside(root, full); - RejectLinks(full); return full; } @@ -32,14 +31,6 @@ internal static void RequireInside(string root, string path) if (!Path.GetFullPath(path).StartsWith(prefix, Comparison)) throw new IOException("安装路径超出允许范围。"); } - internal static void RejectLinks(string path) - { - for (string? current = Path.GetFullPath(path); current != null; current = Path.GetDirectoryName(current)) - if ((File.Exists(current) || Directory.Exists(current)) && - (File.GetAttributes(current) & FileAttributes.ReparsePoint) != 0) - throw new IOException($"安装路径包含符号链接:{current}"); - } - internal static void DeleteTemporary(string path) { if (Directory.Exists(path)) Directory.Delete(path, true); @@ -54,7 +45,6 @@ internal sealed class InstallWorkspace : IInstallWorkspace internal InstallWorkspace(string cachePath, Guid sessionId) { RootPath = Path.GetFullPath(Path.Combine(cachePath, "SingerInstall", sessionId.ToString("N"))); - InstallPaths.RejectLinks(RootPath); Directory.CreateDirectory(RootPath); } public string GetPath(string relativePath) => InstallPaths.Resolve(RootPath, relativePath); diff --git a/OpenUtauMobile/Services/SingerPlugins/Installation/SingerInstallController.cs b/OpenUtauMobile/Services/SingerPlugins/Installation/SingerInstallController.cs index 2486c15c..df7b6385 100644 --- a/OpenUtauMobile/Services/SingerPlugins/Installation/SingerInstallController.cs +++ b/OpenUtauMobile/Services/SingerPlugins/Installation/SingerInstallController.cs @@ -103,7 +103,6 @@ public Task PrepareAsync(InstallSubmission submission, string t foreach (string path in plan.DestinationPaths) { InstallPaths.RequireInside(target.Path, path); - InstallPaths.RejectLinks(path); InstallFileOperations.RequireAbsent(path); } if (version != Interlocked.Read(ref inputVersion)) diff --git a/OpenUtauMobile/Services/SingerPlugins/PluginSettingsService.cs b/OpenUtauMobile/Services/SingerPlugins/PluginSettingsService.cs index a7db2c0e..e7ef64a7 100644 --- a/OpenUtauMobile/Services/SingerPlugins/PluginSettingsService.cs +++ b/OpenUtauMobile/Services/SingerPlugins/PluginSettingsService.cs @@ -12,7 +12,6 @@ using System.Threading.Tasks; using OpenUtau.Core; using OpenUtauMobile.Plugin.Abstractions; -using OpenUtauMobile.Services.SingerPlugins.Installation; namespace OpenUtauMobile.Services.SingerPlugins { @@ -63,7 +62,6 @@ private static Document Read(RegisteredPluginSettings registration) { string directory = DirectoryFor(registration.PluginId); string path = Path.Combine(directory, "settings.json"); - InstallPaths.RejectLinks(path); bool exists = File.Exists(path); if (exists && new FileInfo(path).Length is 0 or > 1024 * 1024) throw new InvalidDataException("插件设置文件为空或过大。"); byte[] bytes = exists ? File.ReadAllBytes(path) : []; @@ -129,7 +127,6 @@ private static async Task CommitAsync(PluginSettingsSession session, ImmutableDi { await File.WriteAllBytesAsync(temporary, bytes, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); - InstallPaths.RejectLinks(path); File.Move(temporary, path, true); } finally { if (File.Exists(temporary)) File.Delete(temporary); } diff --git a/OpenUtauMobile/Services/SingerPlugins/SingerPluginService.cs b/OpenUtauMobile/Services/SingerPlugins/SingerPluginService.cs index 81f0fc4c..367b93e9 100644 --- a/OpenUtauMobile/Services/SingerPlugins/SingerPluginService.cs +++ b/OpenUtauMobile/Services/SingerPlugins/SingerPluginService.cs @@ -105,11 +105,17 @@ private static void InspectUnloadedEntries() string root = PathManager.Inst.PluginsPath; if (!Directory.Exists(root)) return; HashSet loaded = new(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + HashSet loadedModules = []; foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) - if (!assembly.IsDynamic && !string.IsNullOrEmpty(assembly.Location)) loaded.Add(Path.GetFullPath(assembly.Location)); + { + if (assembly.IsDynamic) continue; + if (!string.IsNullOrEmpty(assembly.Location)) loaded.Add(Path.GetFullPath(assembly.Location)); + // Android 运行时可能返回映射后的 Location,模块标识仍能对应磁盘上的同一份程序集。 + loadedModules.Add(assembly.ManifestModule.ModuleVersionId); + } try { - EnumerationOptions options = new() { RecurseSubdirectories = true, AttributesToSkip = FileAttributes.ReparsePoint, IgnoreInaccessible = false }; + EnumerationOptions options = new() { RecurseSubdirectories = true, AttributesToSkip = 0, IgnoreInaccessible = false }; foreach (string path in Directory.EnumerateFiles(root, "*", options).Where(path => Path.GetExtension(path).Equals(".dll", StringComparison.OrdinalIgnoreCase))) { if (loaded.Contains(Path.GetFullPath(path))) continue; @@ -120,6 +126,7 @@ private static void InspectUnloadedEntries() if (!pe.HasMetadata) continue; MetadataReader reader = pe.GetMetadataReader(); if (!reader.IsAssembly) continue; + if (loadedModules.Contains(reader.GetGuid(reader.GetModuleDefinition().Mvid))) continue; bool entry = reader.GetAssemblyDefinition().GetCustomAttributes().Any(handle => { CustomAttribute attribute = reader.GetCustomAttribute(handle); diff --git a/native/game/GameNative.targets b/native/game/GameNative.targets index 4c8f3fd7..ce21cafd 100644 --- a/native/game/GameNative.targets +++ b/native/game/GameNative.targets @@ -31,7 +31,6 @@ <_GameNdkArgument Condition="'$(_OpumAndroidNdkDirectory)' != ''">--ndk "$(_OpumAndroidNdkDirectory)" - <_GameBuiltFile Include="$(_GameRuntimeDirectory)/*" /> diff --git a/native/game/README.md b/native/game/README.md index f53585e7..cce706ec 100644 --- a/native/game/README.md +++ b/native/game/README.md @@ -9,7 +9,7 @@ Core 与 USTX 数据结构不需要改动。 - 平台、渲染器、推理后端及硬件加速支持:[全局 README](../../README.md#feature-matrix)。 - 音符提取入口及模型包:[GAME 使用说明](../../README.md#game-note-extraction)。 - Windows 电脑的环境安装和 Windows / Android 调试:[贡献指南](../../CONTRIBUTING.md)。 -- 本文面向维护原生桥接和构建逻辑的开发者,说明构建约定、ABI 和验证边界。 +- 本文面向维护原生桥接和构建逻辑的开发者,说明构建约定和 ABI。 ## 构建约定 @@ -17,7 +17,7 @@ Core 与 USTX 数据结构不需要改动。 1. 在 `artifacts/game-bazel-build//workspace` 准备独立构建入口,按 RID 选择工具链。每次由 Bazel 检查依赖图,同 RID 的构建由进程锁串行化。 2. `MODULE.bazel` 固定 game.cpp `97f92770704c154e1af4a9b3066b7701041dbc38`、ggml `v0.19.0` 和 pocketfft `32424d2067c2e8043dc646a4e49754b2b40cc549`,归档均带 SHA256。dr_libs 仅供上游 WAV/CLI 测试,不进入应用库依赖图。 -3. 检查二进制架构、四个 C ABI 导出、运行时依赖和 Android 16 KB 对齐;安装到 `artifacts/game-native/`,同时收集许可证及 `game-build.json` 来源记录。 +3. 安装到 `artifacts/game-native/`,同时收集许可证及 `game-build.json` 来源记录。 4. MSBuild 收集产物用于桌面输出或 Android 原生资产。缺少工具链、锁文件过时或下载失败会使构建失败。 Worldline 由 [WorldlineNative.targets](../worldline/WorldlineNative.targets) 使用同一版本的 Bazel 构建。 @@ -35,27 +35,23 @@ NDK 路径通过 `--ndk` 传给脚本,并与 .NET 原生资产收集共用;B ARMv7 关闭不兼容的 llamafile,其他架构保留。工具链发生变化时 Bazel 重新编译受影响的目标。 可选 MSBuild 属性:`GamePythonExecutable`、`GameBazelExecutable`、`GameBuildRoot`、`GameNativeRoot`。 -`EnableGameGgml=false` 可跳过构建和打包,但不会隐藏 UI 选项或删除旧输出;验证这种包时使用独立输出目录。 -正常 Build / Publish 均包含原生构建,不将 `publish --no-build` 作为验证入口。 +`EnableGameGgml=false` 可跳过构建和打包,但不会隐藏 UI 选项或删除旧输出。 +正常 Build / Publish 均包含原生构建。 -## CI 与本地验证 +## CI 与本地构建 PR 矩阵包含桌面六个 RID、Android 四 ABI 的 Worldline 和 GAME 源码构建。 -匹配宿主的桌面任务运行上游已有测试及无模型 ABI 检查;GAME 编译上游完整测试源文件, -`--test` 明确选择 19 项无需模型/参考数据的既有用例。其余 18 项数值对照/模型用例未验收: +手动使用 `--test` 可运行 19 项无需模型/参考数据的上游既有用例。其余 18 项数值对照/模型用例需要外部数据: 其中 11 项在辅助函数中调用 `GTEST_SKIP` 后仍继续读缺失文件,不能当作自动跳过。 -完整目标 `@game_cpp//:core_tests` 仍可在准备好上游参考数据后单独运行。Linux/macOS 真正执行结果以 CI 验收为准。 -发布流程通过项目自身的 Build / Publish 规则收集库,验证发布目录加载及 Android APK 资产。 +完整目标 `@game_cpp//:core_tests` 仍可在准备好上游参考数据后单独运行。 +发布流程通过项目自身的 Build / Publish 规则收集库、打包并上传。 ```sh python native/game/build.py --rid win-x64 --test -python native/game/verify.py artifacts/game-native/win-x64 win-x64 --run -python native/verify-runtime.py OpenUtauMobile.Windows/bin/Debug/net10.0-windows ``` -`--test` 和 `--run` 只能用于匹配宿主及 Python 架构的平台。交叉构建自动检查文件格式与导出,但不执行目标库。 +`--test` 只能用于匹配宿主架构的平台。 更新依赖时显式传入 `--update-lock`,审查并提交 `MODULE.bazel.lock`;普通构建要求锁文件匹配。 -这些检查不能代替真机加载、真实模型推理与识别质量验证。 ## 生命周期与限制 diff --git a/native/game/build.py b/native/game/build.py index b8789240..a1749355 100644 --- a/native/game/build.py +++ b/native/game/build.py @@ -14,9 +14,7 @@ ROOT = HERE.parent.parent sys.path.insert(0, str(HERE.parent)) from bazel_common import build_lock, configure_windows_bash, write_changed -from worldline.verify import verify_binary -EXPORTS = {'opum_game_open', 'opum_game_close', 'opum_game_infer', 'opum_game_error'} RIDS = ('win-x64', 'win-arm64', 'win-x86', 'linux-x64', 'linux-arm64', 'osx-x64', 'osx-arm64', 'android-arm64', 'android-arm', 'android-x64', 'android-x86') LICENSES = {'game_cpp': 'game.cpp', 'ggml': 'ggml', 'pocketfft': 'pocketfft'} @@ -106,10 +104,6 @@ def build_native(args, parser, build): bazel = shutil.which(args.bazel) if not bazel: parser.error('Bazelisk not found. Install Bazelisk or pass --bazel.') - actual_version = subprocess.run([bazel, '--version'], cwd=stage, env=env, check=True, - capture_output=True, text=True).stdout.strip() - if actual_version != f'bazel {version}': - parser.error(f'Expected Bazel {version}, got {actual_version!r}. Use Bazelisk.') command = [bazel, '--nohome_rc', '--nosystem_rc', f'--output_user_root={args.build_root.resolve() / "bazel"}'] def run(action, targets, capture=False): @@ -130,14 +124,9 @@ def run(action, targets, capture=False): write_changed(HERE / 'MODULE.bazel.lock', (stage / 'MODULE.bazel.lock').read_bytes()) name = 'opum_game.dll' if args.rid.startswith('win-') else ('libopum_game.dylib' if args.rid.startswith('osx-') else 'libopum_game.so') libraries = [stage / path for path in paths if Path(path).name == name] - if len(libraries) != 1 or not libraries[0].is_file(): - raise RuntimeError(f'Expected exactly one {name}; cquery returned {paths}') - verification = verify_binary(libraries[0], args.rid, EXPORTS) destination = args.install_root.resolve() / args.rid for repo, license_name in LICENSES.items(): matches = [execution_root / path for path in paths if '+' + repo + '/' in path] - if len(matches) != 1 or not matches[0].read_bytes().strip(): - raise RuntimeError(f'Missing or ambiguous license for {repo}') write_changed(destination / f'LICENSE.{license_name}.txt', matches[0].read_bytes()) compiler_action = next(action for action in actions['actions'] if action['mnemonic'] == 'CppCompile') compiler = compiler_action['arguments'][0] @@ -148,20 +137,14 @@ def run(action, targets, capture=False): compiler_info = (result.stdout + result.stderr).decode(locale.getpreferredencoding(False), errors='replace').strip() if compiler_path.name.lower() == 'cl.exe': compiler_info = compiler_info.splitlines()[0] - elif result.returncode: - raise RuntimeError(f'Cannot identify compiler: {compiler_info}') - if not compiler_info: - raise RuntimeError('Compiler did not report its version') - if args.rid == 'win-arm64' and 'clang' not in compiler_path.name.lower(): - raise RuntimeError('Windows ARM64 GGML requires Clang') provenance = { 'rid': args.rid, 'bazel': version, 'backend': 'cpu', 'compiler': compiler, 'compiler_version': compiler_info, 'compiler_arguments': compiler_action['arguments'], - 'build_options': options, 'binary': verification, + 'build_options': options, 'dependencies': (HERE / 'MODULE.bazel').read_text(encoding='utf-8'), 'lock_sha256': hashlib.sha256((stage / 'MODULE.bazel.lock').read_bytes()).hexdigest(), 'build_adapter_sha256': {p.relative_to(HERE.parent).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() - for p in files + [HERE / 'build.py', HERE.parent / 'bazel_common.py', HERE.parent / 'worldline/verify.py']}, + for p in files + [HERE / 'build.py', HERE.parent / 'bazel_common.py']}, 'library_sha256': hashlib.sha256(libraries[0].read_bytes()).hexdigest(), } if args.rid.startswith('android-'): diff --git a/native/game/verify.py b/native/game/verify.py deleted file mode 100644 index d73402f9..00000000 --- a/native/game/verify.py +++ /dev/null @@ -1,59 +0,0 @@ -"""核对 GAME 库的架构、来源记录、许可证及无模型 C ABI 调用。""" -import argparse -import ctypes -import hashlib -import json -from pathlib import Path -import platform -import sys - -sys.path.insert(0, str(Path(__file__).resolve().parents[1])) -from worldline.verify import verify_binary - -EXPORTS = {'opum_game_open', 'opum_game_close', 'opum_game_infer', 'opum_game_error'} - - -def verify(root, rid, run=False): - root = Path(root).resolve() - name = 'opum_game.dll' if rid.startswith('win-') else ('libopum_game.dylib' if rid.startswith('osx-') else 'libopum_game.so') - path = root / name - result = verify_binary(path, rid, EXPORTS) - provenance = json.loads((root / 'game-build.json').read_text(encoding='utf-8')) - if provenance['rid'] != rid or provenance['library_sha256'] != hashlib.sha256(path.read_bytes()).hexdigest(): - raise ValueError('GAME library does not match its build provenance') - for dependency in ('game.cpp', 'ggml', 'pocketfft'): - if not (root / f'LICENSE.{dependency}.txt').read_text(encoding='utf-8').strip(): - raise ValueError(f'Missing GAME license: {dependency}') - if run: - host = {'win32': 'win', 'darwin': 'osx'}.get(sys.platform, 'linux') - arch = 'arm64' if platform.machine().lower() in ('arm64', 'aarch64') else 'x64' - if ctypes.sizeof(ctypes.c_void_p) == 4: - arch = 'x86' - if rid != f'{host}-{arch}': - raise ValueError('Runtime verification requires a matching host and Python architecture') - library = ctypes.CDLL(str(path)) - library.opum_game_open.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int] - library.opum_game_open.restype = ctypes.c_void_p - library.opum_game_error.argtypes = [ctypes.c_void_p] - library.opum_game_error.restype = ctypes.c_char_p - library.opum_game_close.argtypes = [ctypes.c_void_p] - library.opum_game_close.restype = None - for model in (None, b'', b'opum-deliberately-missing.gguf'): - error = ctypes.create_string_buffer(1024) - handle = library.opum_game_open(model, error, len(error)) - if handle or not error.value: - raise ValueError('Invalid model path must return an error without a handle') - if not library.opum_game_error(None): - raise ValueError('Missing invalid-handle error') - library.opum_game_close(None) - print(f'PASS: GAME {rid}; {result}') - return result - - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('directory') - parser.add_argument('rid') - parser.add_argument('--run', action='store_true') - args = parser.parse_args() - verify(args.directory, args.rid, args.run) diff --git a/native/verify-android-runtime.py b/native/verify-android-runtime.py deleted file mode 100644 index 5b22c891..00000000 --- a/native/verify-android-runtime.py +++ /dev/null @@ -1,86 +0,0 @@ -"""检查 APK 的原生库架构、Worldline ABI、页面对齐和许可证。""" -import argparse -import hashlib -import json -from pathlib import Path -import struct -import tempfile -import zipfile - -from worldline.verify import verify_binary -from game.verify import EXPORTS as GAME_EXPORTS - -parser = argparse.ArgumentParser(description=__doc__) -parser.add_argument('apk') -parser.add_argument('rid', choices=['android-arm64', 'android-arm', 'android-x64', 'android-x86']) -args = parser.parse_args() -abi, machine, elf_class = { - 'android-arm64': ('arm64-v8a', 183, 2), - 'android-arm': ('armeabi-v7a', 40, 1), - 'android-x64': ('x86_64', 62, 2), - 'android-x86': ('x86', 3, 1), -}[args.rid] - -with zipfile.ZipFile(args.apk) as apk: - names = apk.namelist() - abis = {name.split('/')[1] for name in names if name.startswith('lib/') and name.endswith('.so')} - if abis != {abi}: - raise ValueError(f'Expected only {abi}, found {sorted(abis)}') - for library in ('libworldline.so', 'libonnxruntime.so', 'libonnxruntime4j_jni.so', 'libopum_game.so'): - entry = f'lib/{abi}/{library}' - if names.count(entry) != 1: - raise ValueError(f'{entry} must occur exactly once') - data = apk.read(entry) - if data[:6] != b'\x7fELF' + bytes([elf_class, 1]) or struct.unpack_from('`,在加入应用之前验证目标架构、20 个所需导出, -以及 Android 的动态依赖和段对齐。`worldline-build.json` 记录冻结提交、CPP 指纹、依赖与补丁指纹、 +产物安装到 `artifacts/worldline-native/`。`worldline-build.json` 记录冻结提交、CPP 指纹、依赖与补丁指纹、 编译器、NDK、Bazel、构建选项和库哈希。这是来源追踪,不表示不同编译器下能生成相同字节。 许可证和来源清单进入应用的 `WorldlineLicenses`(Android 为 assets 下的同名目录)。 更新冻结上游时,也需同步审查 `upstream-revision.txt`、许可证、Bzlmod 依赖和适配器。 -不执行 `publish --no-build` 来验证首次原生资产收集。 +首次构建使用正常 Build / Publish 收集原生资产。 -## 直接构建与验证 +## 直接构建 ```powershell python native/worldline/build.py --rid win-x64 --test -python native/worldline/verify.py artifacts/worldline-native/win-x64/worldline.dll win-x64 --run python native/worldline/build.py --rid android-arm64 ``` `--test` 运行上游已有的 worldline、effects、continuous_noise 测试,仅适用于宿主架构。 -音频设备测试需要硬件,不自动运行。`--run` 实际调用全部十个分析/合成导出: -F0 四种模式、MGC/BAP 解码、AnalysisConfig 初始化、普通/R1.1 分析和合成。 -检查输出长度、有限数、缓冲区前后哨兵、编码/解码输入的一致性,以及连续噪声种子的高 32 位和输入不可变约定。 -`--run --report ` 可保存确定性输入输出,用于与实际 Core 托管调用比较。 -这些是小输入的 ABI 检查,不代替模型、真实音源渲染、内存压力或设备音频验收。 -Android ELF 检查不能替代设备上的渲染和音频播放验收。 +音频设备测试需要硬件,不自动运行。 ## iOS / Browser 静态链接 @@ -63,21 +56,16 @@ python3 native/worldline/build.py --rid iossimulator-x64 # 通过 .NET 提供精确的 Emscripten 工具和编译配置,生成 worldline.a。 dotnet msbuild OpenUtauMobile.Browser/OpenUtauMobile.Browser.csproj -t:BuildWorldlineNative -python3 native/worldline/verify_browser.py artifacts/worldline-native/browser-wasm ``` `cc_static_library` 收集冻结上游的 Worldline、音频接口及传递依赖对象,生成独立归档。 -平台工具链只在新目标上注册,不改变桌面或 Android 工具链。归档检查包含每个对象的文件格式、 -iOS CPU 与真机/模拟器平台、全部 20 个 ABI 定义及重复定义;来源清单记录 SDK、目标三元组与选项。 +平台工具链按目标注册;来源清单记录 SDK、目标三元组与选项。 iOS 使用 `NativeReference`、C++ 运行库和系统音频框架。宿主模块初始化器将 Core 的 `DllImport("worldline")` 解析到主程序;链接选项显式保留并导出这些函数。 -IPA 验证还检查最终可执行文件导出和 `WorldlineLicenses`,避免仅归档成功而发布时被裁掉。 Browser 使用文件名 `worldline.a` 配合 `NativeFileReference`,让 .NET 生成静态 P/Invoke 表, 不修改 Core。许可证和来源清单位于 `wwwroot/licenses/Worldline`。 -`verify_browser.py` 使用同一 SDK 链接全部 ABI,并在 Node 中运行四种 F0 模式、缓冲区哨兵、 -AnalysisConfig 布局和合成长度检查。此检查不创建音频设备,也不验证 ONNX、模型渲染或浏览器播放。 本机 Windows 已验证 Browser 原生构建、Debug 应用链接、Release 发布与 Node 中的 WASM 调用;iOS 配置需在 Mac/CI 实测, 不能将 CI 任务定义视为构建或设备验收通过。现有 Browser Dummy 音频后端及 ONNX 能力边界不因静态库接入改变。 @@ -89,9 +77,7 @@ AnalysisConfig 布局和合成长度检查。此检查不创建音频设备, 可选 MSBuild 属性:`WorldlinePythonExecutable`、`WorldlineBazelExecutable`、`WorldlineBuildRoot`、 `WorldlineNativeRoot`。DesignTimeBuild 不编译或下载。 -PR 工作流覆盖桌面六个 RID 的上游测试和实际 ABI 调用、Android 四 ABI 的源码构建。 -发布工作流通过相同 MSBuild 入口构建并检查最终发布目录或 APK;Linux/macOS 的实际验证结果以 CI 为准。 +PR 工作流覆盖桌面六个 RID 和 Android 四 ABI 的源码构建。 +发布工作流通过相同 MSBuild 入口构建、打包并上传产物。 Linux x64/ARM64 的 CI 编译环境固定为 Ubuntu 24.04,避免浮动 runner 自动抬高系统库基线。 -实际所需的 glibc/libstdc++ 符号版本,以及 macOS 的依赖、部署版本和加载路径随 CI 验证产物保存; -这些结果核验完成前,不声明更老系统兼容性。 CI 暂不恢复或保存跨任务的 Bazel 编译缓存,每个矩阵任务独立构建;本地下载缓存与目标架构的编译目录分离。 diff --git a/native/worldline/WorldlineNative.targets b/native/worldline/WorldlineNative.targets index b741cf3f..5f449a3e 100644 --- a/native/worldline/WorldlineNative.targets +++ b/native/worldline/WorldlineNative.targets @@ -56,7 +56,6 @@ - <_WorldlineLibrary Include="$(_WorldlineRuntimeDirectory)/$(_WorldlineNativeName)" /> diff --git a/native/worldline/build.py b/native/worldline/build.py index bf6caf74..510c37a6 100644 --- a/native/worldline/build.py +++ b/native/worldline/build.py @@ -13,9 +13,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from bazel_common import build_lock, configure_windows_bash, write_changed -from verify import verify_binary from static_platforms import STATIC_RIDS, configure -from verify_static import verify_archive HERE = Path(__file__).resolve().parent ROOT = HERE.parent.parent @@ -151,10 +149,6 @@ def build_native(args, parser, build): bazel = shutil.which(args.bazel) if not bazel: parser.error('Bazelisk not found. Install Bazelisk or pass --bazel.') - actual_version = subprocess.run([bazel, '--version'], cwd=stage, env=env, check=True, - capture_output=True, text=True).stdout.strip() - if actual_version != f'bazel {version}': - parser.error(f'Expected Bazel {version}, got {actual_version!r}. Use Bazelisk.') command = [bazel, '--nohome_rc', '--nosystem_rc', f'--output_user_root={args.build_root.resolve() / "bazel"}'] @@ -180,17 +174,12 @@ def run(action, targets, capture=False): if is_static: name = 'libworldline_static.a' libraries = [stage / path for path in paths if Path(path).name == name] - if len(libraries) != 1 or not libraries[0].is_file(): - raise RuntimeError(f'Expected exactly one {name}; cquery returned {paths}') destination = args.install_root.resolve() / args.rid - verification = verify_archive(libraries[0], args.rid, static_sdk['nm']) if is_static else verify_binary(libraries[0], args.rid) if is_static: name = 'worldline.a' if args.rid == 'browser-wasm' else 'libworldline.a' licenses = {name: [] for name in LICENSES} for path in license_paths: repo = next((name for name in LICENSES if '+' + name + '/' in path), None) - if not repo: - raise ValueError(f'Unrecognized license source: {path}') content = (execution_root / path).read_text(encoding='utf-8') if repo == 'libpyin': notices = re.findall(r'/\*.*?\*/', content, re.DOTALL) @@ -198,8 +187,6 @@ def run(action, targets, capture=False): if content.strip() and content not in licenses[repo]: licenses[repo].append(content) for license_name, contents in licenses.items(): - if not contents: - raise ValueError(f'Missing license: {license_name}') write_changed(destination / f'LICENSE.{license_name}.txt', ('\n\n'.join(contents) + '\n').encode()) write_changed(destination / 'LICENSE.worldline.txt', (HERE / 'LICENSE.worldline.txt').read_bytes()) write_changed(destination / name, libraries[0].read_bytes()) @@ -215,15 +202,11 @@ def run(action, targets, capture=False): if compiler_path.name.lower() == 'cl.exe': # cl /Bv 输出版本后因没有输入文件返回非零;保留首行版本与目标架构。 compiler_info = compiler_info.splitlines()[0] - elif compiler_result.returncode: - raise RuntimeError(f'Cannot identify compiler: {compiler_info}') - if not compiler_info: - raise RuntimeError('Compiler did not report its version') provenance = {'rid': args.rid, 'bazel': version, 'source_sha256': digest, 'upstream_commit': upstream_commit, 'compiler': static_sdk['compiler'] if is_static else compiler, 'compiler_version': compiler_info, 'compiler_arguments': compiler_action['arguments'], - 'build_options': options, 'binary': verification, + 'build_options': options, 'module_sha256': hashlib.sha256((stage / 'MODULE.bazel').read_bytes()).hexdigest(), 'lock_sha256': hashlib.sha256((stage / 'MODULE.bazel.lock').read_bytes()).hexdigest(), 'build_adapter_sha256': adapter_hashes, diff --git a/native/worldline/verify.py b/native/worldline/verify.py deleted file mode 100644 index 49d88088..00000000 --- a/native/worldline/verify.py +++ /dev/null @@ -1,271 +0,0 @@ -"""检查 Worldline 原生库架构、导出及调用方持有缓冲区的新 ABI。""" -import argparse -import ctypes -import json -import math -from pathlib import Path -import struct - -if not __debug__: - raise RuntimeError('Native verification requires Python without -O/PYTHONOPTIMIZE.') - -EXPORTS = { - 'F0FrameCount', 'F0', 'DecodeMgc', 'DecodeBap', 'InitAnalysisConfig', - 'WorldAnalysisF0In', 'WorldSynthesisSampleCount', 'WorldSynthesis', - 'HnAnalysisF0In', 'WorldSynthesisContinuousNoise', - 'ou_get_audio_device_infos', 'ou_free_audio_device_infos', - 'ou_init_audio_device', 'ou_init_audio_device_auto', 'ou_get_audio_device_api', - 'ou_get_audio_device_name', 'ou_free_audio_device', 'ou_audio_device_start', - 'ou_audio_device_stop', 'ou_audio_get_error_message', -} - - -def verify_binary(path, rid, expected_exports=EXPORTS): - data = Path(path).read_bytes() - unpack = lambda fmt, offset: struct.unpack_from('<' + fmt, data, offset) - text = lambda offset: data[offset:data.index(b'\0', offset)].decode('utf-8') - exports, dependencies = set(), [] - arch = rid.split('-')[1] - if rid.startswith('win-'): - assert data[:2] == b'MZ', 'Expected PE DLL' - pe = unpack('I', 0x3c)[0] - assert data[pe:pe + 4] == b'PE\0\0' - machine, count = unpack('HH', pe + 4) - assert machine == {'x64': 0x8664, 'x86': 0x14c, 'arm64': 0xaa64}[arch], 'Wrong PE architecture' - optional_size, characteristics = unpack('HH', pe + 20) - assert characteristics & 0x2000, 'Expected DLL' - optional = pe + 24 - directories = optional + (112 if unpack('H', optional)[0] == 0x20b else 96) - sections = [unpack('IIII', optional + optional_size + i * 40 + 8) for i in range(count)] - - def address(rva): - for size, virtual, raw_size, raw in sections: - if virtual <= rva < virtual + max(size, raw_size): - return raw + rva - virtual - raise ValueError(f'Unmapped PE address {rva}') - - export = address(unpack('I', directories)[0]) - count = unpack('I', export + 24)[0] - names = address(unpack('I', export + 32)[0]) - exports = {text(address(unpack('I', names + i * 4)[0])) for i in range(count)} - imports = address(unpack('I', directories + 8)[0]) - while any(data[imports:imports + 20]): - dependencies.append(text(address(unpack('I', imports + 12)[0]))) - imports += 20 - assert not any(name.lower().startswith(('libgcc', 'libstdc++', 'libwinpthread', 'vcruntime', 'msvcp')) for name in dependencies), 'Expected static Windows C++ runtime' - elif rid.startswith(('android-', 'linux-')): - assert data[:4] == b'\x7fELF' and data[5] == 1, 'Expected little-endian ELF' - wide = arch in ('x64', 'arm64') - assert data[4] == (2 if wide else 1), 'Wrong ELF class' - assert unpack('HH', 16) == (3, {'arm64': 183, 'arm': 40, 'x64': 62, 'x86': 3}[arch]), 'Wrong ELF architecture/type' - section_offset = unpack('Q' if wide else 'I', 40 if wide else 32)[0] - section_size, section_count = unpack('HH', 58 if wide else 46) - sections = [unpack('IIQQQQIIQQ' if wide else 'IIIIIIIIII', section_offset + i * section_size) for i in range(section_count)] - for section in sections: - if section[1] not in (6, 11): - continue - strings = sections[section[6]][4] - for offset in range(section[4], section[4] + section[5], section[9]): - if section[1] == 6: - tag, value = unpack('qQ' if wide else 'iI', offset) - if tag == 1: - dependencies.append(text(strings + value)) - else: - symbol = unpack('IBBHQQ' if wide else 'IIIBBH', offset) - info, index = (symbol[1], symbol[3]) if wide else (symbol[3], symbol[5]) - if info >> 4 and index: - exports.add(text(strings + symbol[0])) - if rid.startswith('android-'): - program_offset = unpack('Q' if wide else 'I', 32 if wide else 28)[0] - size, count = unpack('HH', 54 if wide else 42) - alignments = [unpack('Q' if wide else 'I', program_offset + i * size + (48 if wide else 28))[0] - for i in range(count) if unpack('I', program_offset + i * size)[0] == 1] - assert alignments and all(value >= 16384 for value in alignments), f'Missing 16 KB alignment: {alignments}' - assert set(dependencies) <= {'libc.so', 'libm.so', 'libdl.so', 'liblog.so', 'libandroid.so'}, f'Unexpected Android dependency: {dependencies}' - else: - assert unpack('I', 0)[0] == 0xfeedfacf, 'Expected thin 64-bit Mach-O' - assert unpack('I', 4)[0] == {'x64': 0x1000007, 'arm64': 0x100000c}[arch], 'Wrong Mach-O architecture' - assert unpack('I', 12)[0] == 6, 'Expected Mach-O dylib' - offset = 32 - for _ in range(unpack('I', 16)[0]): - command, size = unpack('II', offset) - if command == 2: - symbols, count, strings, _ = unpack('IIII', offset + 8) - for i in range(count): - name, kind, section, _, _ = unpack('IBBHQ', symbols + i * 16) - if kind & 1 and section: - exports.add(text(strings + name).removeprefix('_')) - elif command in (0xc, 0x80000018, 0x8000001f): - dependencies.append(text(offset + unpack('I', offset + 8)[0])) - offset += size - missing = expected_exports - exports - if missing: - raise ValueError(f'Missing native ABI exports: {sorted(missing)}') - return {'dependencies': dependencies, 'verified_exports': sorted(expected_exports)} - - -class AnalysisConfig(ctypes.Structure): - _fields_ = [('fs', ctypes.c_int), ('hop_size', ctypes.c_int), - ('fft_size', ctypes.c_int), ('f0_floor', ctypes.c_float), - ('frame_ms', ctypes.c_double)] - - -class GuardedBuffer: - """用哨兵检查输出边界,用 NaN 检查未写入的元素。""" - sentinel = 9.87654321e99 - - def __init__(self, count): - self.count = count - self.storage = (ctypes.c_double * (count + 2))( - self.sentinel, *([math.nan] * count), self.sentinel) - self.pointer = ctypes.cast(ctypes.byref(self.storage, ctypes.sizeof(ctypes.c_double)), - ctypes.POINTER(ctypes.c_double)) - - def values(self): - assert self.storage[0] == self.storage[-1] == self.sentinel, 'Native output exceeded its buffer' - result = list(self.storage)[1:-1] - assert all(math.isfinite(value) for value in result), 'Native output is unwritten or non-finite' - return result - - -def verify_runtime(path, report_path=None): - library = ctypes.CDLL(str(Path(path).resolve())) - for name in EXPORTS: - getattr(library, name) - library.F0FrameCount.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_double, ctypes.c_int] - library.F0FrameCount.restype = ctypes.c_int - library.F0.argtypes = [ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int, ctypes.c_double, ctypes.c_int, ctypes.POINTER(ctypes.c_double)] - library.F0.restype = ctypes.c_int - double_p, float_p = ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_float) - config_p = ctypes.POINTER(AnalysisConfig) - integer, real = ctypes.c_int, ctypes.c_double - signatures = { - 'DecodeMgc': ([integer, double_p, integer, integer, integer, double_p], None), - 'DecodeBap': ([integer, double_p, integer, integer, double_p], None), - 'InitAnalysisConfig': ([config_p, integer, integer, integer], None), - 'WorldAnalysisF0In': ([config_p, float_p, integer, double_p, integer, double_p, double_p], None), - 'HnAnalysisF0In': ([config_p, float_p, float_p, integer, double_p, integer, double_p, double_p, double_p], None), - 'WorldSynthesisSampleCount': ([integer, real, integer], integer), - 'WorldSynthesis': ([double_p, integer, double_p, ctypes.c_bool, integer, - double_p, ctypes.c_bool, integer, real, integer, - double_p, double_p, double_p, double_p, double_p], integer), - 'WorldSynthesisContinuousNoise': ([double_p, integer, double_p, double_p, double_p, - double_p, integer, integer, integer, ctypes.c_uint64, - double_p, double_p, double_p, double_p, double_p], integer), - } - for name, (arguments, result) in signatures.items(): - getattr(library, name).argtypes = arguments - getattr(library, name).restype = result - - def doubles(values): - return (ctypes.c_double * len(values))(*values) - - fs, hop, fft, frames, mgc_size, bap_size = 44100, 220, 2048, 24, 24, 5 - bins = fft // 2 + 1 - report = {'fs': fs, 'hop': hop, 'fft': fft, 'frames': frames, 'mgc_size': mgc_size, - 'bap_size': bap_size, 'f0_cases': []} - samples = (ctypes.c_float * 8820)() - assert library.F0FrameCount(0, fs, 10, 0) == library.F0(None, 0, fs, 10, 0, None) == 0 - for method in (-1, 0, 1, 2): - # 5 ms 在 44.1 kHz 下需要取整,覆盖 pyin 的容量上界与实际长度不同的情况。 - period = 5.0 - count = library.F0FrameCount(len(samples), fs, period, method) - assert 0 < count < 1000 - output = GuardedBuffer(count) - written = library.F0(samples, len(samples), fs, period, method, output.pointer) - values = output.values() - assert 0 < written <= count and all(value == 0 for value in values) - report['f0_cases'].append({'method': method, 'capacity': count, 'written': written, 'values': values[:written]}) - - assert ctypes.sizeof(AnalysisConfig) == 24 - assert [getattr(AnalysisConfig, name).offset for name, _ in AnalysisConfig._fields_] == [0, 4, 8, 12, 16] - config = AnalysisConfig() - library.InitAnalysisConfig(ctypes.byref(config), fs, hop, fft) - assert (config.fs, config.hop_size, config.fft_size) == (fs, hop, fft) - assert 0 < config.f0_floor < 220 and config.frame_ms == hop * 1000.0 / fs - report['config'] = {name: getattr(config, name) for name, _ in AnalysisConfig._fields_} - - mgc = [(-4 + row * 0.015 if col == 0 else 0.01 / (col + 1)) - for row in range(frames) for col in range(mgc_size)] - bap = [-25 - row * 0.1 - col for row in range(frames) for col in range(bap_size)] - sp, ap = GuardedBuffer(frames * bins), GuardedBuffer(frames * bins) - library.DecodeMgc(frames, doubles(mgc), mgc_size, fft, fs, sp.pointer) - library.DecodeBap(frames, doubles(bap), fft, fs, ap.pointer) - decoded_sp, decoded_ap = sp.values(), ap.values() - assert all(value > 0 for value in decoded_sp) - assert all(0 <= value <= 1 for value in decoded_ap) - assert decoded_sp[:bins] != decoded_sp[-bins:] and decoded_ap[:bins] != decoded_ap[-bins:] - report.update(mgc=mgc, bap=bap, decoded_sp=decoded_sp, decoded_ap=decoded_ap) - - f0 = [0 if row % 7 == 0 else 220.0 for row in range(frames)] - harmonic = (ctypes.c_float * len(samples))(*[0.1 * math.sin(2 * math.pi * 220 * i / fs) for i in range(len(samples))]) - samples = (ctypes.c_float * len(samples))(*[harmonic[i] + 0.01 * math.sin(2 * math.pi * 1777 * i / fs) for i in range(len(samples))]) - sp, ap = GuardedBuffer(frames * bins), GuardedBuffer(frames * bins) - library.WorldAnalysisF0In(ctypes.byref(config), samples, len(samples), doubles(f0), frames, sp.pointer, ap.pointer) - report.update(samples=list(samples), harmonic=list(harmonic), f0=f0, - analysis_sp=sp.values(), analysis_ap=ap.values()) - hn_sp, hn_harmonic, hn_ap = [GuardedBuffer(frames * bins) for _ in range(3)] - library.HnAnalysisF0In(ctypes.byref(config), samples, harmonic, len(samples), doubles(f0), frames, - hn_sp.pointer, hn_harmonic.pointer, hn_ap.pointer) - report.update(hn_sp=hn_sp.values(), hn_harmonic=hn_harmonic.values(), hn_ap=hn_ap.values()) - assert all(0.001 <= value <= 0.999 for value in report['hn_ap']) - for row in range(frames): - if f0[row] == 0: - assert all(value == 0.999 for value in report['hn_ap'][row * bins:(row + 1) * bins]) - - count = library.WorldSynthesisSampleCount(frames, config.frame_ms, fs) - assert count == 1 + int((frames - 1) * config.frame_ms / 1000 * fs) - assert library.WorldSynthesisSampleCount(0, config.frame_ms, fs) == 0 - assert library.WorldSynthesisSampleCount(1, config.frame_ms, fs) == 1 - curves = [[0.4 + row * 0.005 for row in range(frames)], - [0.45 + row * 0.003 for row in range(frames)], - [0.3 + row * 0.01 for row in range(frames)], - [0.8 + row * 0.005 for row in range(frames)]] - report.update(curves=curves, sample_count=count, synthesis={}) - for is_mgc in (False, True): - for is_bap in (False, True): - output = GuardedBuffer(count) - written = library.WorldSynthesis(doubles(f0), frames, doubles(mgc if is_mgc else decoded_sp), - is_mgc, mgc_size, doubles(bap if is_bap else decoded_ap), is_bap, fft, config.frame_ms, - fs, output.pointer, *(doubles(curve) for curve in curves)) - values = output.values() - assert written == count and any(value != 0 for value in values) - report['synthesis'][f'{int(is_mgc)}{int(is_bap)}'] = values - baseline = report['synthesis']['00'] - for values in report['synthesis'].values(): - assert all(math.isclose(a, b, rel_tol=1e-10, abs_tol=1e-12) for a, b in zip(baseline, values)), 'Decoded and encoded synthesis disagree' - - # 纯噪声输入排除周期部分影响,单独验证种子高 32 位与输入不可变约定。 - inputs = [[0.0] * frames, [1e-4] * (frames * bins), [1e-4] * (frames * bins), - [1.0] * (frames * bins), [1.0] * frames, *curves] - arrays = [doubles(values) for values in inputs] - seed = 0x12345678abcdef01 - noise_results = [] - for current_seed in (seed, seed, seed ^ (1 << 40)): - output = GuardedBuffer(count) - written = library.WorldSynthesisContinuousNoise(arrays[0], frames, *arrays[1:5], fft, hop, fs, - current_seed, output.pointer, *arrays[5:]) - assert written == count - noise_results.append(output.values()) - assert all(list(array) == values for array, values in zip(arrays, inputs)), 'Continuous synthesis modified an input' - assert noise_results[0] == noise_results[1] and noise_results[0] != noise_results[2], '64-bit seed is not respected' - report.update(seed=seed, noise=noise_results[0], noise_high_seed=noise_results[2]) - if report_path: - Path(report_path).write_text(json.dumps(report, allow_nan=False), encoding='utf-8') - print('PASS: Worldline F0/codec/config/analysis/synthesis/R1.1 ABI, output guards and 64-bit seed') - return library - - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('library') - parser.add_argument('rid') - parser.add_argument('--run', action='store_true') - parser.add_argument('--report', help='Write deterministic inputs/outputs for managed ABI comparison (requires --run)') - args = parser.parse_args() - if args.report and not args.run: - parser.error('--report requires --run') - print(verify_binary(args.library, args.rid)) - if args.run: - verify_runtime(args.library, args.report) - print('PASS: Worldline ' + args.rid) diff --git a/native/worldline/verify_browser.py b/native/worldline/verify_browser.py deleted file mode 100644 index 243ddb15..00000000 --- a/native/worldline/verify_browser.py +++ /dev/null @@ -1,73 +0,0 @@ -"""链接完整 WASM ABI,并在 Node 中检查缓冲区调用;不代替浏览器音频验收。""" -import argparse -import hashlib -import json -import os -from pathlib import Path -import subprocess -import sys - -from verify import EXPORTS -from verify_static import verify_archive - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('directory', type=Path) - args = parser.parse_args() - directory = args.directory.resolve() - manifest = json.loads((directory / 'worldline-build.json').read_text(encoding='utf-8')) - library = directory / 'worldline.a' - if manifest['rid'] != 'browser-wasm' or hashlib.sha256(library.read_bytes()).hexdigest() != manifest['library_sha256']: - raise ValueError('Browser library provenance mismatch') - sdk = manifest['static_sdk'] - verify_archive(library, 'browser-wasm', sdk['nm']) - output = directory / 'verification' - output.mkdir(exist_ok=True) - module = output / 'worldline.cjs' - # 将所有 ABI 导出交给最终链接器,检查归档是否遗漏了传递依赖。 - command = [sys.executable, str(Path(sdk['sdk']) / 'emscripten/emcc.py'), str(library), - '-O2', '--no-entry', '-sMODULARIZE=1', '-sEXPORT_NAME=WorldlineModule', '-sENVIRONMENT=node', - '-sALLOW_MEMORY_GROWTH=1', '-sWASM_BIGINT=1', '-sEXIT_RUNTIME=1', - '-sEXPORTED_FUNCTIONS=' + json.dumps(['_' + name for name in sorted(EXPORTS)] + ['_malloc', '_free']), - '-o', str(module)] - command += [flag for flag in sdk['flags'] if flag in ('-pthread', '-msimd128', '-fwasm-exceptions', '-fexceptions')] - subprocess.run(command, env=os.environ | sdk['environment'], check=True) - script = output / 'verify.cjs' - script.write_text('''const assert = require('node:assert/strict'); -require('./worldline.cjs')().then(m => { - assert.equal(m._F0FrameCount(0, 44100, 5, 0), 0); - const samples = m._malloc(8820 * 4); - m.HEAPF32.fill(0, samples / 4, samples / 4 + 8820); - for (const method of [-1, 0, 1, 2]) { - const count = m._F0FrameCount(8820, 44100, 5, method); - assert(count > 0 && count < 1000); - const buffer = m._malloc((count + 2) * 8); - m.HEAPF64.fill(NaN, buffer / 8, buffer / 8 + count + 2); - m.HEAPF64[buffer / 8] = 123456.5; - m.HEAPF64[buffer / 8 + count + 1] = 123456.5; - const written = m._F0(samples, 8820, 44100, 5, method, buffer + 8); - assert(written > 0 && written <= count); - assert.equal(m.HEAPF64[buffer / 8], 123456.5); - assert.equal(m.HEAPF64[buffer / 8 + count + 1], 123456.5); - for (let i = 0; i < written; i++) assert.equal(m.HEAPF64[buffer / 8 + i + 1], 0); - m._free(buffer); - } - const config = m._malloc(24); - m._InitAnalysisConfig(config, 44100, 220, 2048); - assert.equal(m.HEAP32[config / 4], 44100); - assert.equal(m.HEAP32[config / 4 + 1], 220); - assert.equal(m.HEAP32[config / 4 + 2], 2048); - assert.equal(m.HEAPF64[(config + 16) / 8], 220 * 1000 / 44100); - assert.equal(m._WorldSynthesisSampleCount(24, 5, 44100), 5072); - m._free(config); - m._free(samples); - console.log('Worldline WASM: all ABI symbols linked; F0 four modes, buffer guards, config and synthesis sizing passed.'); - process.exit(0); -}).catch(error => { console.error(error); process.exit(1); }); -''', encoding='utf-8') - subprocess.run([sdk['environment']['DOTNET_EMSCRIPTEN_NODE_JS'], str(script)], check=True) - - -if __name__ == '__main__': - main() diff --git a/native/worldline/verify_static.py b/native/worldline/verify_static.py deleted file mode 100644 index 99932e20..00000000 --- a/native/worldline/verify_static.py +++ /dev/null @@ -1,94 +0,0 @@ -"""验证静态归档的每个对象架构和 Worldline ABI,不把交叉编译当作设备验收。""" -import argparse -import hashlib -import json -from pathlib import Path -import struct -import subprocess -import plistlib - -from verify import EXPORTS - - -def verify_archive(path, rid, nm): - data = Path(path).read_bytes() - if data[:8] != b'!\n': - raise ValueError('Expected a self-contained ar archive, not a thin archive') - cursor, count = 8, 0 - while cursor < len(data): - header = data[cursor:cursor + 60] - if len(header) != 60 or header[58:] != b'`\n': - raise ValueError('Invalid ar member header') - size = int(header[48:58]) - name = header[:16].strip() - content = data[cursor + 60:cursor + 60 + size] - if len(content) != size: - raise ValueError('Truncated archive') - cursor += 60 + size + size % 2 - if name.startswith(b'#1/'): - length = int(name[3:]) - name, content = content[:length].rstrip(b'\0'), content[length:] - if name in (b'/', b'//', b'/SYM64/') or name.startswith(b'__.SYMDEF'): - continue - count += 1 - if rid == 'browser-wasm': - if content[:8] != b'\0asm\x01\0\0\0': - raise ValueError(f'Expected WASM object: {name!r}') - else: - magic, cpu, _, kind, commands = struct.unpack_from('<5I', content) - expected_cpu = 0x1000007 if rid.endswith('-x64') else 0x100000c - if (magic, cpu, kind) != (0xfeedfacf, expected_cpu, 1): - raise ValueError(f'Wrong iOS Mach-O object: {name!r}') - offset, found = 32, False - for _ in range(commands): - command, length = struct.unpack_from('= 2] - if rid != 'browser-wasm': - symbols = [name.removeprefix('_') for name in symbols] - exports = set(symbols) - missing = EXPORTS - exports - if missing: - raise ValueError(f'Missing static Worldline ABI: {sorted(missing)}') - duplicates = [name for name in EXPORTS if symbols.count(name) != 1] - if duplicates: - raise ValueError(f'Duplicate static Worldline ABI definitions: {duplicates}') - return {'object_count': count, 'verified_exports': sorted(EXPORTS), 'rid': rid, 'linkage': 'static'} - - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('library', type=Path) - parser.add_argument('rid', choices=('browser-wasm', 'ios-arm64', 'iossimulator-arm64', 'iossimulator-x64')) - parser.add_argument('--nm', required=True) - parser.add_argument('--app-bundle', type=Path, help='Also verify exported ABI and provenance in an iOS app bundle') - args = parser.parse_args() - print(json.dumps(verify_archive(args.library, args.rid, args.nm), indent=2)) - if args.app_bundle: - if args.rid == 'browser-wasm': - parser.error('--app-bundle is only valid for iOS') - info = plistlib.loads((args.app_bundle / 'Info.plist').read_bytes()) - binary = args.app_bundle / info['CFBundleExecutable'] - symbols = subprocess.run([args.nm, '-gU', str(binary)], check=True, text=True, capture_output=True).stdout - exported = {line.split()[-1].removeprefix('_') for line in symbols.splitlines() if len(line.split()) >= 2} - if EXPORTS - exported: - raise ValueError(f'Linked iOS app is missing ABI exports: {sorted(EXPORTS - exported)}') - packaged = json.loads((args.app_bundle / 'WorldlineLicenses/worldline-build.json').read_text(encoding='utf-8')) - original = json.loads((args.library.parent / 'worldline-build.json').read_text(encoding='utf-8')) - if packaged != original or packaged['library_sha256'] != hashlib.sha256(args.library.read_bytes()).hexdigest(): - raise ValueError('iOS app Worldline provenance mismatch') - for license_file in args.library.parent.glob('LICENSE.*.txt'): - if license_file.read_bytes() != (args.app_bundle / 'WorldlineLicenses' / license_file.name).read_bytes(): - raise ValueError(f'iOS app license mismatch: {license_file.name}') - print('iOS app Worldline exports, provenance and licenses verified.') From 45927a76db9aaec8016b4e81fd4e80967b4aed62 Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:01:09 +0800 Subject: [PATCH 09/45] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E5=8E=9F?= =?UTF-8?q?=E7=94=9F=E5=BA=93=E9=87=8D=E5=A4=8D=E7=BC=96=E8=AF=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/actions/setup-worldline/action.yml | 2 +- .github/workflows/build-all-platforms.yml | 72 ++--- .github/workflows/build-android.yml | 50 +--- .github/workflows/build-browser.yml | 16 +- .github/workflows/build-ios.yml | 28 +- .github/workflows/pr-requirements.yml | 17 +- CONTRIBUTING.md | 14 +- Directory.Build.props | 7 +- .../OpenUtauMobile.Android.csproj | 23 +- .../OpenUtauMobile.Browser.csproj | 3 +- .../OpenUtauMobile.Linux.csproj | 4 +- .../OpenUtauMobile.MacOS.csproj | 4 +- .../OpenUtauMobile.Windows.csproj | 5 +- OpenUtauMobile.iOS/OpenUtauMobile.iOS.csproj | 2 +- build/DesktopRuntime.props | 32 --- docs/CONTRIBUTING.en-US.md | 13 +- native/.bazelrc | 18 ++ native/{game => }/.bazelversion | 0 native/AndroidNativeToolchain.targets | 26 -- native/DesktopNative.targets | 8 - native/NativeBuild.targets | 120 ++++++++ native/README.md | 59 ++++ native/{game => }/android-ndk-version.txt | 0 native/bazel_common.py | 58 ---- native/build.py | 271 ++++++++++++++++++ native/game/.bazelrc | 5 - native/game/GameNative.targets | 49 ---- native/game/README.md | 26 +- native/game/build.py | 158 ---------- native/game/game.BUILD | 1 - native/game/ggml.BUILD | 1 - native/game/pocketfft.BUILD | 1 - native/worldline/.bazelrc | 6 - native/worldline/.bazelversion | 1 - native/worldline/README.md | 89 +----- native/worldline/WorldlineNative.targets | 99 ------- native/worldline/build.py | 225 --------------- native/worldline/frozen_archive.bzl | 2 - native/worldline/static_platforms.py | 120 -------- native/worldline/xxhash.BUILD | 2 - 40 files changed, 567 insertions(+), 1070 deletions(-) delete mode 100644 build/DesktopRuntime.props create mode 100644 native/.bazelrc rename native/{game => }/.bazelversion (100%) delete mode 100644 native/AndroidNativeToolchain.targets delete mode 100644 native/DesktopNative.targets create mode 100644 native/NativeBuild.targets create mode 100644 native/README.md rename native/{game => }/android-ndk-version.txt (100%) delete mode 100644 native/bazel_common.py create mode 100644 native/build.py delete mode 100644 native/game/.bazelrc delete mode 100644 native/game/GameNative.targets delete mode 100644 native/game/build.py delete mode 100644 native/worldline/.bazelrc delete mode 100644 native/worldline/.bazelversion delete mode 100644 native/worldline/WorldlineNative.targets delete mode 100644 native/worldline/build.py delete mode 100644 native/worldline/static_platforms.py diff --git a/.github/actions/setup-worldline/action.yml b/.github/actions/setup-worldline/action.yml index 18ece9e0..c08e409d 100644 --- a/.github/actions/setup-worldline/action.yml +++ b/.github/actions/setup-worldline/action.yml @@ -14,4 +14,4 @@ runs: - uses: bazel-contrib/setup-bazel@0.19.0 with: bazelisk-version: '1.29.0' - module-root: native/worldline + module-root: native diff --git a/.github/workflows/build-all-platforms.yml b/.github/workflows/build-all-platforms.yml index 21b4f46a..77ac0729 100644 --- a/.github/workflows/build-all-platforms.yml +++ b/.github/workflows/build-all-platforms.yml @@ -43,6 +43,11 @@ permissions: env: AVALONIA_TELEMETRY_OPTOUT: "1" VersionLyrics: ${{ inputs.version_lyrics }} + Configuration: Release + Version: ${{ inputs.version }} + BuildNumber: ${{ inputs.build_number }} + SourceCommit: ${{ inputs.source_sha }} + ActionRunId: ${{ inputs.action_run_id }} jobs: # ============================================================ @@ -82,6 +87,8 @@ jobs: linux: name: Linux ${{ matrix.arch }} runs-on: ${{ matrix.runner }} + env: + RuntimeIdentifier: ${{ matrix.rid }} strategy: fail-fast: false @@ -109,15 +116,11 @@ jobs: with: architecture: ${{ matrix.arch }} - - name: Build and test Worldline - shell: bash - run: python native/worldline/build.py --rid ${{ matrix.rid }} --test - - name: Collect Build Metadata shell: bash run: | - echo "BUILD_TIMESTAMP=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> "$GITHUB_ENV" - echo "BUILD_MACHINE=${RUNNER_OS} / $(uname -srm)" >> "$GITHUB_ENV" + echo "BuildTimestamp=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> "$GITHUB_ENV" + echo "BuildMachine=${RUNNER_OS} / $(uname -srm)" >> "$GITHUB_ENV" - name: Publish Linux ${{ matrix.arch }} shell: bash @@ -126,16 +129,7 @@ jobs: dotnet publish \ OpenUtauMobile.Linux/OpenUtauMobile.Linux.csproj \ - -c Release \ - -r "${{ matrix.rid }}" \ - --self-contained true \ - -p:PublishDir="$PUBLISH_DIR/" \ - -p:Version="${{ inputs.version }}" \ - -p:BuildNumber=${{ inputs.build_number }} \ - -p:BuildTimestamp="$BUILD_TIMESTAMP" \ - -p:BuildMachine="$BUILD_MACHINE" \ - -p:SourceCommit=${{ inputs.source_sha }} \ - -p:ActionRunId=${{ inputs.action_run_id }} + -o "$PUBLISH_DIR" - name: Package Linux ${{ matrix.arch }} shell: bash @@ -143,7 +137,7 @@ jobs: PUBLISH_DIR="${GITHUB_WORKSPACE}/artifacts/publish/${{ matrix.rid }}" PACKAGE="${GITHUB_WORKSPACE}/artifacts/OpenUtauMobile-build${{ inputs.build_number }}-linux-${{ matrix.arch }}.tar.gz" - chmod +x "$PUBLISH_DIR/OpenUtauMobile.Linux" || true + chmod +x "$PUBLISH_DIR/OpenUtauMobile.Linux" tar \ -C "$PUBLISH_DIR" \ @@ -167,6 +161,8 @@ jobs: windows: name: Windows ${{ matrix.arch }} runs-on: ${{ matrix.runner }} + env: + RuntimeIdentifier: ${{ matrix.rid }} strategy: fail-fast: false @@ -194,19 +190,15 @@ jobs: with: architecture: ${{ matrix.arch }} - - name: Build and test Worldline - shell: bash - run: python native/worldline/build.py --rid ${{ matrix.rid }} --test - - name: Collect Build Metadata shell: pwsh run: | $timestamp = [DateTime]::UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ") - "BUILD_TIMESTAMP=$timestamp" | + "BuildTimestamp=$timestamp" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append - "BUILD_MACHINE=$env:RUNNER_OS / $env:PROCESSOR_ARCHITECTURE" | + "BuildMachine=$env:RUNNER_OS / $env:PROCESSOR_ARCHITECTURE" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append - name: Publish Windows ${{ matrix.arch }} @@ -216,16 +208,7 @@ jobs: dotnet publish ` OpenUtauMobile.Windows/OpenUtauMobile.Windows.csproj ` - -c Release ` - -r "${{ matrix.rid }}" ` - --self-contained true ` - -p:PublishDir="$publishDir/" ` - -p:Version="${{ inputs.version }}" ` - -p:BuildNumber=${{ inputs.build_number }} ` - -p:BuildTimestamp="$env:BUILD_TIMESTAMP" ` - -p:BuildMachine="$env:BUILD_MACHINE" ` - -p:SourceCommit=${{ inputs.source_sha }} ` - -p:ActionRunId=${{ inputs.action_run_id }} + -o "$publishDir" - name: Package Windows ${{ matrix.arch }} shell: pwsh @@ -257,6 +240,8 @@ jobs: macos: name: macOS ${{ matrix.arch }} runs-on: ${{ matrix.runner }} + env: + RuntimeIdentifier: ${{ matrix.rid }} strategy: fail-fast: false @@ -286,15 +271,11 @@ jobs: with: architecture: ${{ matrix.arch }} - - name: Build and test Worldline - shell: bash - run: python native/worldline/build.py --rid ${{ matrix.rid }} --test - - name: Collect Build Metadata shell: bash run: | - echo "BUILD_TIMESTAMP=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> "$GITHUB_ENV" - echo "BUILD_MACHINE=${RUNNER_OS} / $(uname -srm)" >> "$GITHUB_ENV" + echo "BuildTimestamp=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> "$GITHUB_ENV" + echo "BuildMachine=${RUNNER_OS} / $(uname -srm)" >> "$GITHUB_ENV" - name: Publish macOS ${{ matrix.arch }} shell: bash @@ -303,16 +284,7 @@ jobs: dotnet publish \ OpenUtauMobile.MacOS/OpenUtauMobile.MacOS.csproj \ - -c Release \ - -r "${{ matrix.rid }}" \ - --self-contained true \ - -p:PublishDir="$PUBLISH_DIR/" \ - -p:Version="${{ inputs.version }}" \ - -p:BuildNumber=${{ inputs.build_number }} \ - -p:BuildTimestamp="$BUILD_TIMESTAMP" \ - -p:BuildMachine="$BUILD_MACHINE" \ - -p:SourceCommit=${{ inputs.source_sha }} \ - -p:ActionRunId=${{ inputs.action_run_id }} + -o "$PUBLISH_DIR" - name: Package macOS ${{ matrix.arch }} shell: bash @@ -320,7 +292,7 @@ jobs: PUBLISH_DIR="${GITHUB_WORKSPACE}/artifacts/publish/${{ matrix.rid }}" PACKAGE="${GITHUB_WORKSPACE}/artifacts/OpenUtauMobile-build${{ inputs.build_number }}-macos-${{ matrix.arch }}.tar.gz" - chmod +x "$PUBLISH_DIR/OpenUtauMobile.MacOS" || true + chmod +x "$PUBLISH_DIR/OpenUtauMobile.MacOS" tar \ -C "$PUBLISH_DIR" \ diff --git a/.github/workflows/build-android.yml b/.github/workflows/build-android.yml index 07f03c62..ddc73b99 100644 --- a/.github/workflows/build-android.yml +++ b/.github/workflows/build-android.yml @@ -52,6 +52,12 @@ permissions: env: AVALONIA_TELEMETRY_OPTOUT: "1" VersionLyrics: ${{ inputs.version_lyrics }} + Configuration: Release + RuntimeIdentifier: ${{ inputs.rid }} + Version: ${{ inputs.version }} + BuildNumber: ${{ inputs.build_number }} + SourceCommit: ${{ inputs.source_sha }} + ActionRunId: ${{ inputs.action_run_id }} jobs: build: @@ -89,29 +95,22 @@ jobs: shell: bash run: | set -euo pipefail - NDK_VERSION="$(tr -d '\r\n' < native/game/android-ndk-version.txt)" - SDK_ROOT="${ANDROID_HOME:-${ANDROID_SDK_ROOT:?Android SDK is required}}" - sdkmanager --sdk_root="$SDK_ROOT" "ndk;$NDK_VERSION" - echo "OPUM_ANDROID_NDK=$SDK_ROOT/ndk/$NDK_VERSION" >> "$GITHUB_ENV" + sdkmanager "ndk;$(tr -d '\r\n' < native/android-ndk-version.txt)" - name: Create Swap Space shell: bash run: | SWAP_FILE=/runner-swapfile - if [ ! -f "$SWAP_FILE" ]; then - sudo fallocate -l 6G "$SWAP_FILE" - sudo chmod 600 "$SWAP_FILE" - sudo mkswap "$SWAP_FILE" - fi - sudo swapon "$SWAP_FILE" 2>/dev/null || true - free -h - swapon --show + sudo fallocate -l 6G "$SWAP_FILE" + sudo chmod 600 "$SWAP_FILE" + sudo mkswap "$SWAP_FILE" + sudo swapon "$SWAP_FILE" - name: Collect Build Metadata shell: bash run: | - echo "BUILD_TIMESTAMP=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> "$GITHUB_ENV" - echo "BUILD_MACHINE=${RUNNER_OS} / $(uname -srm)" >> "$GITHUB_ENV" + echo "BuildTimestamp=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> "$GITHUB_ENV" + echo "BuildMachine=${RUNNER_OS} / $(uname -srm)" >> "$GITHUB_ENV" - name: Decode Android Keystore if: inputs.release_signing @@ -120,16 +119,6 @@ jobs: ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }} run: printf '%s' "$ANDROID_KEYSTORE_BASE64" | base64 --decode > signing.keystore - # 必须按最终 RID 显式还原;发布阶段复用同一资产图,防止宿主平台原生资产混入 APK。 - # 全局指定 Mono,让引用的普通 .NET 类库也使用 Mono,避免 armhf 请求不存在的 CoreCLR linux-bionic-arm 包。 - - name: Restore Android ${{ inputs.arch }} - shell: bash - run: | - dotnet restore OpenUtauMobile.Android/OpenUtauMobile.Android.csproj \ - -r "${{ inputs.rid }}" \ - -p:UseMonoRuntime=true \ - -p:Configuration=Release - - name: Publish Android ${{ inputs.arch }} shell: bash env: @@ -148,19 +137,6 @@ jobs: "-p:AndroidSigningKeyPass=$KEY_PASSWORD") fi dotnet publish OpenUtauMobile.Android/OpenUtauMobile.Android.csproj \ - --no-restore \ - -c Release \ - -f net10.0-android36.0 \ - -r "${{ inputs.rid }}" \ - -p:UseMonoRuntime=true \ - -p:Version="${{ inputs.version }}" \ - -p:BuildNumber=${{ inputs.build_number }} \ - -p:BuildTimestamp="$BUILD_TIMESTAMP" \ - -p:BuildMachine="$BUILD_MACHINE" \ - -p:SourceCommit=${{ inputs.source_sha }} \ - -p:ActionRunId=${{ inputs.action_run_id }} \ - -p:AndroidNdkDirectory="$OPUM_ANDROID_NDK" \ - -p:AndroidPackageFormat=apk \ "${signing_args[@]}" - name: Prepare Android artifact diff --git a/.github/workflows/build-browser.yml b/.github/workflows/build-browser.yml index b3fccf65..8865b96c 100644 --- a/.github/workflows/build-browser.yml +++ b/.github/workflows/build-browser.yml @@ -28,6 +28,11 @@ jobs: env: AVALONIA_TELEMETRY_OPTOUT: "1" VersionLyrics: ${{ inputs.version_lyrics }} + Configuration: Release + Version: ${{ inputs.version }} + BuildNumber: ${{ inputs.build_number }} + SourceCommit: ${{ inputs.source_sha || github.sha }} + ActionRunId: ${{ inputs.action_run_id || github.run_id }} steps: - uses: actions/checkout@v4 with: @@ -39,18 +44,9 @@ jobs: - name: Install WebAssembly workload run: dotnet workload install wasm-tools - name: Publish Browser with Worldline - env: - PRODUCT_VERSION: ${{ inputs.version }} - BUILD_NUMBER: ${{ inputs.build_number }} - SOURCE_SHA: ${{ inputs.source_sha || github.sha }} - ACTION_RUN_ID: ${{ inputs.action_run_id || github.run_id }} run: | - args=() - if [ -n "$PRODUCT_VERSION" ]; then args+=("-p:Version=$PRODUCT_VERSION"); fi dotnet publish OpenUtauMobile.Browser/OpenUtauMobile.Browser.csproj \ - -c Release -o artifacts/publish/browser-wasm \ - -p:BuildNumber="$BUILD_NUMBER" -p:SourceCommit="$SOURCE_SHA" \ - -p:ActionRunId="$ACTION_RUN_ID" "${args[@]}" + -o artifacts/publish/browser-wasm - name: Package Browser static files run: | tar -C artifacts/publish/browser-wasm/wwwroot -czf artifacts/OpenUtauMobile-browser-wasm.tar.gz . diff --git a/.github/workflows/build-ios.yml b/.github/workflows/build-ios.yml index 267df2fc..9f1d0605 100644 --- a/.github/workflows/build-ios.yml +++ b/.github/workflows/build-ios.yml @@ -34,6 +34,12 @@ jobs: runs-on: xcode-27 timeout-minutes: 90 env: + Configuration: Release + RuntimeIdentifier: ios-arm64 + Version: ${{ inputs.version }} + BuildNumber: ${{ inputs.build_number }} + SourceCommit: ${{ inputs.source_sha }} + ActionRunId: ${{ inputs.action_run_id }} AVALONIA_TELEMETRY_OPTOUT: "1" DOTNET_CLI_TELEMETRY_OPTOUT: "1" DOTNET_NOLOGO: "1" @@ -57,8 +63,8 @@ jobs: run: | set -euo pipefail - echo "BUILD_TIMESTAMP=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> "$GITHUB_ENV" - echo "BUILD_MACHINE=${RUNNER_OS} / $(uname -srm)" >> "$GITHUB_ENV" + echo "BuildTimestamp=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> "$GITHUB_ENV" + echo "BuildMachine=${RUNNER_OS} / $(uname -srm)" >> "$GITHUB_ENV" mkdir -p "${GITHUB_WORKSPACE}/artifacts/ios-arm64-logs" - name: Restore iOS Workload @@ -90,24 +96,6 @@ jobs: dotnet publish \ OpenUtauMobile.iOS/OpenUtauMobile.iOS.csproj \ - --force \ - -c Release \ - -f net10.0-ios \ - -r ios-arm64 \ - -p:Version="${{ inputs.version }}" \ - -p:BuildNumber=${{ inputs.build_number }} \ - -p:BuildTimestamp="$BUILD_TIMESTAMP" \ - -p:BuildMachine="$BUILD_MACHINE" \ - -p:SourceCommit=${{ inputs.source_sha }} \ - -p:ActionRunId=${{ inputs.action_run_id }} \ - -p:PublishAot=false \ - -p:UseMonoRuntime=true \ - -p:MtouchUseLlvm=false \ - -p:UseInterpreter=false \ - -p:TrimMode=partial \ - -p:MtouchLink=SdkOnly \ - -p:EnableAssemblyILStripping=false \ - -p:_IsDedupEnabled=false \ -p:EnableCodeSigning=false \ -p:BuildIpa=true \ -p:IpaPackagePath="$IPA_PATH" \ diff --git a/.github/workflows/pr-requirements.yml b/.github/workflows/pr-requirements.yml index cd891218..81d696e1 100644 --- a/.github/workflows/pr-requirements.yml +++ b/.github/workflows/pr-requirements.yml @@ -13,6 +13,8 @@ jobs: name: PR build test for Android ARM64 env: AVALONIA_TELEMETRY_OPTOUT: "1" + Configuration: Release + RuntimeIdentifier: android-arm64 runs-on: ubuntu-latest steps: @@ -49,19 +51,8 @@ jobs: shell: bash run: | set -euo pipefail - NDK_VERSION="$(tr -d '\r\n' < native/game/android-ndk-version.txt)" - SDK_ROOT="${ANDROID_HOME:-${ANDROID_SDK_ROOT:?Android SDK is required}}" - sdkmanager --sdk_root="$SDK_ROOT" "ndk;$NDK_VERSION" - echo "OPUM_ANDROID_NDK=$SDK_ROOT/ndk/$NDK_VERSION" >> "$GITHUB_ENV" - - - name: Restore - run: dotnet restore OpenUtauMobile.Android/OpenUtauMobile.Android.csproj -r android-arm64 -p:Configuration=Release + sdkmanager "ndk;$(tr -d '\r\n' < native/android-ndk-version.txt)" - name: Build Android ARM64 run: | - dotnet build OpenUtauMobile.Android/OpenUtauMobile.Android.csproj \ - -c Release \ - -f net10.0-android36.0 \ - --no-restore \ - -p:RuntimeIdentifier=android-arm64 \ - -p:AndroidNdkDirectory="$OPUM_ANDROID_NDK" + dotnet build OpenUtauMobile.Android/OpenUtauMobile.Android.csproj diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0f7c4261..a57bf884 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -107,15 +107,15 @@ dotnet run --project OpenUtauMobile.Windows/OpenUtauMobile.Windows.csproj -c Deb 3. 启动前构建目标项目及其依赖;只调试 Windows 时,不要将构建整个解决方案作为启动前任务。 4. 在 C# 代码行旁设置断点,点击虫子图标 **Debug**。需要执行到断点所在操作才会暂停。 -普通 Windows 调试不必设置 `RuntimeIdentifier` 或 `EnableGameGgml`。 -桌面入口和 UI 探针的 Debug/Release 构建默认只复制当前系统架构所需的 NuGet 运行库, +普通 Windows 调试不必设置 `RuntimeIdentifier`。 +桌面入口的 Debug/Release 构建默认只复制当前系统架构所需的 NuGet 运行库, 不会再输出所有平台的 `runtimes`。Windows、Linux、macOS 入口会使用各自平台的 RID; 跨平台或跨架构构建请显式传入 `-r `。共享类库保持平台无关,Android、iOS 和浏览器仍由各自 SDK 选择 RID。 NuGet 原生库附带的 PDB 默认不复制;需要调试这些第三方原生库时,传入 `-p:CopyNuGetNativeSymbols=true`。应用自身的托管调试符号不受影响。 构建会自动生成 `opum_game.dll`,并将对应架构的 worldline 放到输出目录。 -默认 Debug 输出位于 `OpenUtauMobile.Windows/bin/Debug/net10.0-windows/`。 -如果显式使用 `-r win-x64`,输出会多一层 `win-x64/`;启动时应使用此次构建的目录。 +默认 Debug 输出位于 `OpenUtauMobile.Windows/bin/Debug/net10.0-windows//`。 +共同的原生构建参数与增量规则见[原生构建](native/README.md)。 ### 4. 准备 Android 环境 @@ -127,7 +127,7 @@ Windows 已能启动后,再安装以下 Android 专用工具。Android 的 C++ | JDK | 建议安装 [Microsoft OpenJDK 21](https://learn.microsoft.com/java/openjdk/download)。填写 JDK 根目录,不是 `bin`;Android Studio 自带 JBR 只有版本兼容时才可复用。 | | [Android Studio](https://developer.android.com/studio) | 用它的 SDK Manager 安装和管理 SDK,也可用 Device Manager 创建模拟器;C# 代码仍在 Rider 调试。 | | Android SDK | SDK Manager 中安装 Android API 36、Build-Tools 36.0.0、Platform-Tools、Command-line Tools (latest)。具体目标以 [Android 项目](OpenUtauMobile.Android/OpenUtauMobile.Android.csproj) 和安装的 .NET Android 工作负载为准。 | -| Android NDK | 在 SDK Tools 中勾选 Show Package Details,安装 [android-ndk-version.txt](native/game/android-ndk-version.txt) 指定的版本,当前为 r30 LTS `30.0.16248370`。 | +| Android NDK | 在 SDK Tools 中勾选 Show Package Details,安装 [android-ndk-version.txt](native/android-ndk-version.txt) 指定的版本。 | 安装方法也可参考微软的 [.NET Android 依赖说明](https://learn.microsoft.com/dotnet/android/getting-started/installation/dependencies)。 项目当前 CI 使用 JDK 17,本地 JDK 21 已通过构建;不要直接使用未经当前工作负载支持的更高版本。 @@ -136,7 +136,7 @@ Windows 已能启动后,再安装以下 Android 专用工具。Android 的 C++ ```powershell $androidSdk = Join-Path $env:LOCALAPPDATA 'Android/Sdk' -$androidNdkVersion = (Get-Content native/game/android-ndk-version.txt -Raw).Trim() +$androidNdkVersion = (Get-Content native/android-ndk-version.txt -Raw).Trim() $androidNdk = Join-Path $androidSdk "ndk/$androidNdkVersion" $javaSdk = 'C:/替换为你的JDK21目录' $env:JAVA_HOME = $javaSdk @@ -180,7 +180,7 @@ RID 是目标系统与 CPU 架构的标识;Android 应用按目标设备选择 ```powershell $env:AVALONIA_TELEMETRY_OPTOUT='1' $androidRid = 'android-arm64' -dotnet build OpenUtauMobile.Android/OpenUtauMobile.Android.csproj -c Debug -r $androidRid "-p:AndroidSdkDirectory=$androidSdk" "-p:AndroidNdkDirectory=$androidNdk" "-p:JavaSdkDirectory=$javaSdk" +dotnet build OpenUtauMobile.Android/OpenUtauMobile.Android.csproj -r $androidRid ``` 命令会自动恢复对应 RID 的依赖,签名 APK 位于 diff --git a/Directory.Build.props b/Directory.Build.props index 9d78d391..85572462 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -30,9 +30,10 @@ preview - - <_OpumPreviousBeforeMicrosoftNETSdkTargets>$(BeforeMicrosoftNETSdkTargets) - $(MSBuildThisFileDirectory)build/DesktopRuntime.props + + + + true diff --git a/OpenUtauMobile.Android/OpenUtauMobile.Android.csproj b/OpenUtauMobile.Android/OpenUtauMobile.Android.csproj index 2a3938f9..387aee1b 100644 --- a/OpenUtauMobile.Android/OpenUtauMobile.Android.csproj +++ b/OpenUtauMobile.Android/OpenUtauMobile.Android.csproj @@ -4,28 +4,23 @@ net10.0-android36.0 24 enable - $(BaseApplicationId) OpenUtau Mobile 预览版 apk + + true false 2G true + true - + $(BaseApplicationId).debug - True - - True - - True + True - - - @@ -52,11 +47,5 @@ Bind="false"/> - - - - - - - + diff --git a/OpenUtauMobile.Browser/OpenUtauMobile.Browser.csproj b/OpenUtauMobile.Browser/OpenUtauMobile.Browser.csproj index c3e01ac1..43a0cf3c 100644 --- a/OpenUtauMobile.Browser/OpenUtauMobile.Browser.csproj +++ b/OpenUtauMobile.Browser/OpenUtauMobile.Browser.csproj @@ -4,7 +4,6 @@ Exe true enable - browser-wasm BROWSER true $(EmccExtraLDFlags) -lidbfs.js @@ -34,5 +33,5 @@ - + diff --git a/OpenUtauMobile.Linux/OpenUtauMobile.Linux.csproj b/OpenUtauMobile.Linux/OpenUtauMobile.Linux.csproj index c1f783c7..fc1f9de1 100644 --- a/OpenUtauMobile.Linux/OpenUtauMobile.Linux.csproj +++ b/OpenUtauMobile.Linux/OpenUtauMobile.Linux.csproj @@ -4,7 +4,6 @@ net10.0 enable LINUX - linux-x64;linux-arm64 @@ -17,7 +16,6 @@ - - + diff --git a/OpenUtauMobile.MacOS/OpenUtauMobile.MacOS.csproj b/OpenUtauMobile.MacOS/OpenUtauMobile.MacOS.csproj index b6a82c39..a9b6b90c 100644 --- a/OpenUtauMobile.MacOS/OpenUtauMobile.MacOS.csproj +++ b/OpenUtauMobile.MacOS/OpenUtauMobile.MacOS.csproj @@ -5,7 +5,6 @@ net10.0 enable MACOS - osx-x64;osx-arm64 @@ -19,6 +18,5 @@ - - + diff --git a/OpenUtauMobile.Windows/OpenUtauMobile.Windows.csproj b/OpenUtauMobile.Windows/OpenUtauMobile.Windows.csproj index 78b5cdfb..5297a592 100644 --- a/OpenUtauMobile.Windows/OpenUtauMobile.Windows.csproj +++ b/OpenUtauMobile.Windows/OpenUtauMobile.Windows.csproj @@ -4,12 +4,10 @@ net10.0-windows enable true - win-x64;win-x86;win-arm64 app.manifest - WINDOWS @@ -24,7 +22,6 @@ - - + diff --git a/OpenUtauMobile.iOS/OpenUtauMobile.iOS.csproj b/OpenUtauMobile.iOS/OpenUtauMobile.iOS.csproj index 9c9e46ee..5c11f807 100644 --- a/OpenUtauMobile.iOS/OpenUtauMobile.iOS.csproj +++ b/OpenUtauMobile.iOS/OpenUtauMobile.iOS.csproj @@ -28,5 +28,5 @@ - + diff --git a/build/DesktopRuntime.props b/build/DesktopRuntime.props deleted file mode 100644 index 5b4ab3b3..00000000 --- a/build/DesktopRuntime.props +++ /dev/null @@ -1,32 +0,0 @@ - - - - - <_OpumDesktopRuntimeDefaultsImported>true - false - <_OpumDefaultDesktopRid>$(NETCoreSdkRuntimeIdentifier) - <_OpumDesktopArchitecture>$([System.Text.RegularExpressions.Regex]::Replace('$(NETCoreSdkRuntimeIdentifier)', '^.*-', '')) - <_OpumDefaultDesktopRid Condition="'$(MSBuildProjectName)' == 'OpenUtauMobile.Windows'">win-$(_OpumDesktopArchitecture) - <_OpumDefaultDesktopRid Condition="'$(MSBuildProjectName)' == 'OpenUtauMobile.MacOS'">osx-$(_OpumDesktopArchitecture) - <_OpumDefaultDesktopRid Condition="'$(MSBuildProjectName)' == 'OpenUtauMobile.Linux' and !$([System.String]::Copy('$(NETCoreSdkRuntimeIdentifier)').StartsWith('linux-'))">linux-$(_OpumDesktopArchitecture) - <_OpumDesktopArchitecture Condition="'$(PlatformTarget)' != '' and '$(PlatformTarget)' != 'AnyCPU'">$(PlatformTarget) - <_OpumDesktopArchitecture Condition="'$(PlatformTarget)' == '' and ('$(Platform)' == 'x86' or '$(Platform)' == 'x64' or '$(Platform)' == 'ARM64')">$(Platform) - <_OpumDesktopArchitecture>$([System.String]::Copy('$(_OpumDesktopArchitecture)').ToLowerInvariant()) - <_OpumDefaultDesktopRid>$([System.Text.RegularExpressions.Regex]::Replace('$(_OpumDefaultDesktopRid)', '-[^-]+$', '-$(_OpumDesktopArchitecture)')) - - - $(_OpumDefaultDesktopRid) - - false - - - - - - diff --git a/docs/CONTRIBUTING.en-US.md b/docs/CONTRIBUTING.en-US.md index 9b82e90c..746197ec 100644 --- a/docs/CONTRIBUTING.en-US.md +++ b/docs/CONTRIBUTING.en-US.md @@ -89,14 +89,15 @@ In Rider, open `OpenUtauMobile.sln`, check the .NET CLI path, and select the Win run configuration and **Debug** build configuration. Build the target project and dependencies before launch, set a C# breakpoint, then click Debug. If necessary, create the configuration under **Run → Edit Configurations**. -No explicit RID or `EnableGameGgml` flag is needed. GAME and worldline are placed in the correct output directory. -Default output is `OpenUtauMobile.Windows/bin/Debug/net10.0-windows/`; an explicit RID adds a RID subdirectory. +No explicit RID is needed for ordinary Windows builds. GAME and worldline are placed in the output directory. +Default output is `OpenUtauMobile.Windows/bin/Debug/net10.0-windows//`. +Shared compiler settings and incremental behavior are described in [Native builds](../native/README.md). ### 4. Prepare Android Install `dotnet workload install android` from the repository root (use an elevated terminal if requested). Install JDK 21 and use Android Studio's SDK Manager to install API 36, Build-Tools 36.0.0, Platform-Tools, -Command-line Tools (latest), and the NDK from [android-ndk-version.txt](../native/game/android-ndk-version.txt). +Command-line Tools (latest), and the NDK from [android-ndk-version.txt](../native/android-ndk-version.txt). Android uses the NDK's Clang compiler through the same Bazel entry points. The Android project and installed workload remain the source of truth for SDK requirements. Current CI uses JDK 17; local builds have also passed with JDK 21. @@ -105,7 +106,7 @@ Replace the JDK placeholder and SDK path with your installation: ```powershell $androidSdk = Join-Path $env:LOCALAPPDATA 'Android/Sdk' -$androidNdkVersion = (Get-Content native/game/android-ndk-version.txt -Raw).Trim() +$androidNdkVersion = (Get-Content native/android-ndk-version.txt -Raw).Trim() $androidNdk = Join-Path $androidSdk "ndk/$androidNdkVersion" $javaSdk = 'C:/replace-with-your-JDK21-directory' $env:JAVA_HOME = $javaSdk @@ -139,7 +140,7 @@ To check the build before attaching a debugger: ```powershell $env:AVALONIA_TELEMETRY_OPTOUT='1' $androidRid = 'android-arm64' -dotnet build OpenUtauMobile.Android/OpenUtauMobile.Android.csproj -c Debug -r $androidRid "-p:AndroidSdkDirectory=$androidSdk" "-p:AndroidNdkDirectory=$androidNdk" "-p:JavaSdkDirectory=$javaSdk" +dotnet build OpenUtauMobile.Android/OpenUtauMobile.Android.csproj -r $androidRid ``` The signed APK is under `OpenUtauMobile.Android/bin/Debug/net10.0-android36.0//`. @@ -149,7 +150,7 @@ Rider builds, installs, launches and attaches the debugger. No CI release-signin See [Rider's Android instructions](https://www.jetbrains.com/help/rider/Run_Debug_Configuration_Xamarin_Android.html). If compilation fails, inspect the first error and resolved SDK/NDK/JDK paths. A missing native library differs -from a missing model; do not copy binaries from another RID. Use `GameBuildRoot` to isolate native build caches when needed. Check the [known limitations](../README.md#verification-and-known-limits), including Android +from a missing model; do not copy binaries from another RID. Check the [known limitations](../README.md#verification-and-known-limits), including Android 16 KB alignment warnings in existing dependencies. See the Chinese guide for the full troubleshooting table. --- diff --git a/native/.bazelrc b/native/.bazelrc new file mode 100644 index 00000000..516ec9d7 --- /dev/null +++ b/native/.bazelrc @@ -0,0 +1,18 @@ +build --jobs=2 +build --compilation_mode=opt +build --verbose_failures +build --incompatible_strict_action_env +build --lockfile_mode=error +build:windows --cxxopt=/std:c++17 --copt=/utf-8 --features=static_link_msvcrt +build:unix --cxxopt=-std=c++17 +build:worldline --define=absl=1 +build:game-unix --copt=-fno-associative-math +build:android --extra_toolchains=@androidndk//:all --linkopt=-Wl,-z,max-page-size=16384 --features=static_link_cpp_runtimes +build:worldline-linux --linkopt=-lm +build:worldline-osx --macos_minimum_os=10.12 +build:game-osx --macos_minimum_os=10.15 +build:win-x86 --extra_toolchains=@local_config_cc//:cc-toolchain-x64_x86_windows +build:game-win-arm64 --compiler=clang-cl --copt=--target=aarch64-pc-windows-msvc --extra_toolchains=@local_config_cc//:cc-toolchain-arm64_windows-clang-cl +build:static --extra_toolchains=//sdk_toolchain:toolchain --copt=-O2 --copt=-DNDEBUG +build:ios --per_file_copt=worldline/audio_output[.]cc@-x,objective-c++ +test --test_output=errors diff --git a/native/game/.bazelversion b/native/.bazelversion similarity index 100% rename from native/game/.bazelversion rename to native/.bazelversion diff --git a/native/AndroidNativeToolchain.targets b/native/AndroidNativeToolchain.targets deleted file mode 100644 index 19c7c1c8..00000000 --- a/native/AndroidNativeToolchain.targets +++ /dev/null @@ -1,26 +0,0 @@ - - - <_OpumAndroidNativeToolchainImported>true - - - - - <_OpumNdkVersion>$([System.IO.File]::ReadAllText('$(MSBuildThisFileDirectory)game/android-ndk-version.txt').Trim()) - <_OpumAndroidSdkDirectory>$(_AndroidSdkDirectory) - <_OpumAndroidSdkDirectory Condition="'$(_OpumAndroidSdkDirectory)' == ''">$(AndroidSdkDirectory) - - <_OpumAndroidNdkDirectory>$(AndroidNdkDirectory) - <_OpumAndroidNdkDirectory Condition="'$(_OpumAndroidNdkDirectory)' == ''">$(_OpumAndroidSdkDirectory)/ndk/$(_OpumNdkVersion) - <_OpumAndroidSdkDirectory>$([System.String]::Copy('$(_OpumAndroidSdkDirectory)').Replace('\', '/')) - <_OpumAndroidNdkDirectory>$([System.String]::Copy('$(_OpumAndroidNdkDirectory)').Replace('\', '/')) - - - - - $(_OpumAndroidNdkDirectory) - <_AndroidNdkDirectory>$(_OpumAndroidNdkDirectory) - - - diff --git a/native/DesktopNative.targets b/native/DesktopNative.targets deleted file mode 100644 index efaa2f86..00000000 --- a/native/DesktopNative.targets +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/native/NativeBuild.targets b/native/NativeBuild.targets new file mode 100644 index 00000000..1aa6bee2 --- /dev/null +++ b/native/NativeBuild.targets @@ -0,0 +1,120 @@ + + + <_NativeRoot>$(MSBuildThisFileDirectory) + <_NativePlatform>$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) + <_NativePlatform Condition="'$(MSBuildProjectName)' == 'OpenUtauMobile.Linux'">linux + <_NativePlatform Condition="'$(MSBuildProjectName)' == 'OpenUtauMobile.MacOS'">osx + <_NativeDesktop Condition="'$(_NativePlatform)' == 'windows' or '$(_NativePlatform)' == 'linux' or '$(_NativePlatform)' == 'osx'">true + <_NativePython Condition="$([MSBuild]::IsOSPlatform('Windows'))">python + <_NativePython Condition="'$(_NativePython)' == ''">python3 + + + + <_NativeArchitecture>$([System.Text.RegularExpressions.Regex]::Replace('$(NETCoreSdkRuntimeIdentifier)', '^.*-', '')) + <_NativeArchitecture Condition="'$(Platform)' == 'x86' or '$(Platform)' == 'x64' or '$(Platform)' == 'ARM64'">$(Platform) + <_NativeArchitecture Condition="'$(PlatformTarget)' != '' and '$(PlatformTarget)' != 'AnyCPU'">$(PlatformTarget) + <_NativeDesktopRid>$(_NativePlatform)-$([System.String]::Copy('$(_NativeArchitecture)').ToLowerInvariant()) + <_NativeDesktopRid Condition="'$(_NativePlatform)' == 'windows'">win-$([System.String]::Copy('$(_NativeArchitecture)').ToLowerInvariant()) + $(_NativeDesktopRid) + false + true + + + $([System.IO.File]::ReadAllText('$(_NativeRoot)android-ndk-version.txt').Trim()) + <_NativeResolveSdk>_ResolveSdks + + + + + + + $(_AndroidSdkDirectory)/ndk/$(AndroidNdkVersion) + <_AndroidNdkDirectory>$([MSBuild]::EnsureTrailingSlash('$(AndroidNdkDirectory)')) + + + + + + <_NativeRuntime Include="$(RuntimeIdentifiers)" Condition="'$(_NativePlatform)' == 'android' and '$(RuntimeIdentifiers)' != ''" /> + <_NativeRuntime Include="$(RuntimeIdentifier)" Condition="'$(_NativePlatform)' != 'android' or '$(RuntimeIdentifiers)' == ''" /> + <_NativeRuntime Update="@(_NativeRuntime)"> + arm64-v8a + armeabi-v7a + x86_64 + x86 + + + + + + <_NativeCommonSource Include="$(_NativeRoot)build.py;$(_NativeRoot)NativeBuild.targets;$(_NativeRoot).bazelrc;$(_NativeRoot).bazelversion;$(_NativeRoot)android-ndk-version.txt" /> + <_WorldlineSource Include="$(_NativeRoot)upstream_cpp/**/*;$(_NativeRoot)worldline/**/*" + Exclude="$(_NativeRoot)**/__pycache__/**;$(_NativeRoot)**/*.md;$(_NativeRoot)**/LICENSE*;$(_NativeRoot)worldline/WorldlineIosResolver.cs" /> + <_GameSource Include="$(_NativeRoot)game/**/*" Exclude="$(_NativeRoot)**/__pycache__/**;$(_NativeRoot)**/*.md" /> + <_NativeBuild Include="@(_NativeRuntime)"> + worldline + libworldline.so + worldline.dll + libworldline.dylib + libworldline.a + worldline.a + @(_NativeCommonSource);@(_WorldlineSource) + + <_NativeBuild Include="@(_NativeRuntime)" Condition="'$(_NativeDesktop)' == 'true' or '$(_NativePlatform)' == 'android'"> + game + libopum_game.so + opum_game.dll + libopum_game.dylib + @(_NativeCommonSource);@(_GameSource) + + <_NativeBuild Update="@(_NativeBuild)"> + $(_NativeRoot)../artifacts/native/%(_NativeBuild.Identity) + $(_NativeRoot)../artifacts/native/%(_NativeBuild.Identity)/%(_NativeBuild.Library).inputs + $(_NativeRoot)../artifacts/native/%(_NativeBuild.Identity)/%(_NativeBuild.Library).stamp + $(_NativeRoot)../artifacts/native/%(_NativeBuild.Identity)/%(_NativeBuild.LibraryFile) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_WasmRuntimePackSrcFile Update="@(_WasmRuntimePackSrcFile)" Condition="'%(_WasmRuntimePackSrcFile.Filename)' == 'runtime'"> + %(_WasmRuntimePackSrcFile.Dependencies);$(_WasmInterpToNativeTablePath) + + + + diff --git a/native/README.md b/native/README.md new file mode 100644 index 00000000..f30dc582 --- /dev/null +++ b/native/README.md @@ -0,0 +1,59 @@ +# 原生构建 + +六个平台入口只导入 `NativeBuild.targets`,共同使用 `build.py`、`.bazelrc`、`.bazelversion`。 +Worldline 和 GAME 的源码与 Bazel 依赖分别位于各自目录;冻结的 `upstream_cpp` 不修改。 + +## 参数来源 + +- 项目的 TFM、`RuntimeIdentifier(s)`、`Configuration` 和 SDK 解析结果决定构建目标。 +- 共同的 C/C++ 编译选项放在 `.bazelrc`,沿用原有的优化构建,Debug/Release 共用算法与浮点选项。 +- Android NDK 版本由 `android-ndk-version.txt` 指定。SDK 解析安装根目录,两个库使用同一路径。 +- iOS、Browser 的静态工具链使用项目所选的系统 SDK 或 .NET 工作负载,最低系统版本与 WASM 特性跟随项目。 +- Python 读取 MSBuild 生成的 `.inputs` 文件,不另设 RID、SDK 路径或编译开关默认值。 + +## 构建与增量 + +```mermaid +flowchart LR + P[项目 / SDK 参数] --> I[每库每 RID 的输入列表] + I --> M[MSBuild 增量判断] + M -->|输入变化| B[Bazel build] + B --> W[按内容变化安装库] + W --> S[记录成功时间戳] + M -->|输入未变| C[注册平台打包项] + S --> C + C --> D[SDK 编译 / 打包 / 安装] +``` + +SDK 内层和 Install 使用相同输入时,不启动 Python 或 Bazel。原生产物位于 +`artifacts/native//`;Debug/Release 共用原生库,Bazel 工作副本和对象缓存保留在 `artifacts` 下。 +时间戳只表示输入已成功处理;手工修改或删除生成产物后使用 Clean/Rebuild。 +Clean/Rebuild 会使原生成功记录失效,Bazel 仍能复用已有对象缓存。 + +正常构建只执行 Bazel `build`,不运行 `cquery/aquery/info`、许可证收集或来源清单生成。 +同 RID 的工作副本写入由进程锁串行保护,未变化的库不重写。 + +## 使用 + +所有平台需要 Python 3.10+、Bazelisk 和相应 C/C++ 工具链。Windows 使用 VS C++ 工具, +GAME 的 Windows ARM64 使用 ClangCL;Linux 使用系统编译器,Apple 平台使用 Xcode,Android 使用 NDK。 +安装环境后,在 Rider 选择入口项目和设备,或运行普通命令: + +```powershell +$env:AVALONIA_TELEMETRY_OPTOUT='1' +dotnet build OpenUtauMobile.Windows/OpenUtauMobile.Windows.csproj +dotnet build OpenUtauMobile.Android/OpenUtauMobile.Android.csproj -r android-x64 +``` + +跨架构时只在最上层选择一次 RID;未选择时 Android 使用 SDK 的默认集合,桌面使用入口 OS 与当前架构。 +配置 SDK/JDK 的安装环境或 IDE 设置即可,不需要重复传递原生库专用路径和编译参数。 + +已有上游测试保留为手动操作。先生成对应 `.inputs`,再运行: + +```powershell +python native/build.py artifacts/native/win-x64/worldline.inputs --test +python native/build.py artifacts/native/win-x64/game.inputs --test +``` + +GAME 默认选择无需外部模型和参考数据的既有测试。维护依赖时使用同一入口的 `--update-lock`, +审查并提交对应库目录的 `MODULE.bazel.lock`。 diff --git a/native/game/android-ndk-version.txt b/native/android-ndk-version.txt similarity index 100% rename from native/game/android-ndk-version.txt rename to native/android-ndk-version.txt diff --git a/native/bazel_common.py b/native/bazel_common.py deleted file mode 100644 index 70de29da..00000000 --- a/native/bazel_common.py +++ /dev/null @@ -1,58 +0,0 @@ -"""原生 Bazel 构建共用的进程锁和增量文件写入。""" -from contextlib import contextmanager -import os -from pathlib import Path -import shutil -import time - - -def configure_windows_bash(environment): - """兼容 Git cmd、bin 和 mingw64/bin 入口,避免误用 WSL 的 bash。""" - if environment.get('BAZEL_SH'): - return - git = shutil.which('git') - if git: - for parent in Path(git).resolve().parents[:3]: - for relative in ('bin/bash.exe', 'usr/bin/bash.exe'): - candidate = parent / relative - if candidate.is_file(): - environment['BAZEL_SH'] = str(candidate) - return - -@contextmanager -def build_lock(path): - """串行化同一 RID 的构建副本和安装,进程退出后由系统释放锁。""" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open('a+b') as lock: - if not lock.tell(): - lock.write(b'0') - lock.flush() - deadline = time.monotonic() + 900 - while True: - try: - if os.name == 'nt': - import msvcrt - lock.seek(0) - msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1) - else: - import fcntl - fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) - break - except OSError: - if time.monotonic() > deadline: - raise TimeoutError(f'Another native build holds {path}') - time.sleep(0.25) - try: - yield - finally: - if os.name == 'nt': - lock.seek(0) - msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1) - else: - fcntl.flock(lock, fcntl.LOCK_UN) - - -def write_changed(path, content): - path.parent.mkdir(parents=True, exist_ok=True) - if not path.exists() or path.read_bytes() != content: - path.write_bytes(content) diff --git a/native/build.py b/native/build.py new file mode 100644 index 00000000..dd2938a2 --- /dev/null +++ b/native/build.py @@ -0,0 +1,271 @@ +"""使用 MSBuild 继承的目标和配置构建原生库。""" +import argparse +from contextlib import contextmanager +import json +import os +from pathlib import Path +import platform +import re +import shutil +import subprocess +import sys + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent + + +def write_changed(path, content): + """仅在内容变化时写入,保留未变化产物的时间戳。""" + path.parent.mkdir(parents=True, exist_ok=True) + if not path.exists() or path.read_bytes() != content: + path.write_bytes(content) + + +@contextmanager +def build_lock(path): + """串行保护同一原生工作副本,操作系统在进程退出时释放锁。""" + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('a+b') as lock: + if not lock.tell(): + lock.write(b'0') + lock.flush() + if os.name == 'nt': + import msvcrt + import time + lock.seek(0) + while True: + try: + msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1) + break + except OSError: + time.sleep(0.25) + else: + import fcntl + fcntl.flock(lock, fcntl.LOCK_EX) + try: + yield + finally: + if os.name == 'nt': + lock.seek(0) + msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1) + else: + fcntl.flock(lock, fcntl.LOCK_UN) + + +def stage_sources(library, destination): + """同步构建副本,仅适配冻结上游的 Bazel 规则加载。""" + files = {} + if library == 'worldline': + source_root = HERE / 'upstream_cpp' + for source in sorted(source_root.rglob('*')): + if not source.is_file(): + continue + relative = source.relative_to(source_root).as_posix() + if relative in ('.bazelrc', '.bazelversion', 'MODULE.bazel', 'MODULE.bazel.lock', 'WORKSPACE.bazel'): + continue + content = source.read_bytes() + if source.name == 'BUILD.bazel' or source.suffix == '.BUILD': + rules = sorted(set(re.findall(rb'^\s*(cc_\w+)\(', content, re.MULTILINE))) + content = b''.join(b'load("@rules_cc//cc:' + rule + b'.bzl", "' + rule + b'")\n' for rule in rules) + content + files[relative] = content + for source in (HERE / library).iterdir(): + if source.is_file() and (source.suffix in ('.bazel', '.BUILD', '.bzl', '.cpp', '.py') or source.name == 'MODULE.bazel.lock'): + files[source.name] = source.read_bytes() + for name in ('.bazelrc', '.bazelversion'): + files[name] = (HERE / name).read_bytes() + manifest = destination / '.opum-files.json' + if manifest.is_file(): + for relative in set(json.loads(manifest.read_text())) - files.keys(): + obsolete = (destination / relative).resolve() + if not obsolete.is_relative_to(destination.resolve()): + raise ValueError('Invalid generated-file manifest path') + obsolete.unlink(missing_ok=True) + for relative, content in files.items(): + write_changed(destination / relative, content) + write_changed(manifest, json.dumps(sorted(files)).encode()) + + +def configure_static(settings, stage, environment): + """将宿主 SDK 的实际编译与头文件参数接入 Bazel 静态工具链。""" + def output(command): + return subprocess.run(command, check=True, capture_output=True, text=True, env=environment).stdout.strip() + + rid = settings['RuntimeIdentifier'] + tool_environment = {} + if rid == 'browser-wasm': + sdk = Path(settings['EmscriptenSdkToolsPath']).resolve() + cache = Path(settings['EmscriptenCacheSdkCacheDir']).resolve() + sysroot = cache / 'sysroot' + suffix = '.exe' if os.name == 'nt' else '' + driver = Path(sys.executable) + archiver = sdk / ('bin/llvm-ar' + suffix) + node = Path(settings['EmscriptenNodeToolsPath']) / 'bin' / ('node' + suffix) + target = 'wasm32-unknown-emscripten' + flags = [(sdk / 'emscripten/emcc.py').as_posix(), '-fno-fast-math'] + tool_environment = { + 'DOTNET_EMSCRIPTEN_LLVM_ROOT': (sdk / 'bin').as_posix(), + 'DOTNET_EMSCRIPTEN_BINARYEN_ROOT': sdk.as_posix(), + 'DOTNET_EMSCRIPTEN_NODE_JS': node.resolve().as_posix(), + 'EM_CACHE': cache.as_posix(), 'PYTHONUTF8': '1', + } + if settings['WasmEnableThreads'].lower() == 'true': + flags.append('-pthread') + if settings['WasmEnableSIMD'].lower() == 'true': + flags.append('-msimd128') + flags.append('-fwasm-exceptions' if settings['WasmEnableExceptionHandling'].lower() == 'true' else '-fexceptions') + constraints = ['@platforms//os:emscripten', '@platforms//cpu:wasm32'] + else: + sdk_name = 'iphoneos' if rid == 'ios-arm64' else 'iphonesimulator' + sysroot = Path(output(['xcrun', '--sdk', sdk_name, '--show-sdk-path'])) + driver = Path(output(['xcrun', '--sdk', sdk_name, '--find', 'clang'])) + archiver = Path(output(['xcrun', '--sdk', sdk_name, '--find', 'ar'])) + arch = 'x86_64' if rid.endswith('-x64') else 'arm64' + target = arch + '-apple-ios' + settings['SupportedOSPlatformVersion'] + if sdk_name == 'iphonesimulator': + target += '-simulator' + flags = ['--target=' + target, '-isysroot', sysroot.as_posix(), '-fPIC', '-fno-fast-math'] + constraints = ['@platforms//os:ios', '@platforms//cpu:' + arch, + '//:ios_device' if sdk_name == 'iphoneos' else '//:ios_simulator'] + # 工具链需要实际的系统头文件搜索路径,不将文件系统根目录作为隐式依赖。 + probe = subprocess.run([str(driver), *flags, '-x', 'c++', '-E', '-v', '-'], + env=environment | tool_environment, input='', text=True, capture_output=True, check=True) + includes = [] + collecting = False + for line in probe.stderr.splitlines(): + if '#include <...> search starts here:' in line: + collecting = True + elif 'End of search list.' in line: + collecting = False + elif collecting: + includes.append(Path(line.strip().removesuffix(' (framework directory)')).as_posix()) + if rid != 'browser-wasm': + # Xcode 27 的依赖文件包含 SDKSettings.json,限定在所选 SDK 中。 + includes += [sysroot.as_posix(), sysroot.resolve().as_posix()] + quote = json.dumps + config = f'''load("@rules_cc//cc/toolchains:cc_toolchain.bzl", "cc_toolchain") +load("//:static_toolchain.bzl", "static_toolchain_config") +package(default_visibility = ["//visibility:public"]) +filegroup(name = "empty") +static_toolchain_config( + name = "config", compiler_path = {quote(driver.as_posix())}, + archiver_path = {quote(archiver.as_posix())}, target = {quote(target)}, + cpu = {quote(rid.split('-')[1])}, flags = {quote(flags)}, + builtin_includes = {quote(includes)}, environment = {quote(tool_environment)}, + archive_param_file = {rid == 'browser-wasm'}, +) +cc_toolchain( + name = "cc", toolchain_identifier = "opum-worldline-static", + toolchain_config = ":config", all_files = ":empty", compiler_files = ":empty", + linker_files = ":empty", ar_files = ":empty", as_files = ":empty", + dwp_files = ":empty", objcopy_files = ":empty", strip_files = ":empty", + supports_param_files = 1, +) +toolchain(name = "toolchain", toolchain = ":cc", + toolchain_type = "@bazel_tools//tools/cpp:toolchain_type", + target_compatible_with = {quote(constraints)}) +''' + write_changed(stage / 'sdk_toolchain/BUILD.bazel', config.encode()) + + +def build(settings, request, run_tests, update_lock): + """从统一参数构建一个库,直接安装 Bazel 的确定输出。""" + library = settings['NativeLibrary'] + rid = settings['RuntimeIdentifier'] + build_root = ROOT / 'artifacts' / {'worldline': 'worldline-build', 'game': 'game-bazel-build'}[library] + workspace = build_root / rid / 'workspace' + stage_sources(library, workspace) + env = dict(os.environ) + if os.name == 'nt': + # Windows 的 PATH 名称不区分大小写,子进程只保留一项。 + env = {key: value for key, value in env.items() if key.upper() != 'PATH'} + env['Path'] = os.environ.get('PATH', '') + if not env.get('BAZEL_SH'): + git = Path(shutil.which('git')).resolve() + for parent in git.parents[:3]: + for relative in ('bin/bash.exe', 'usr/bin/bash.exe'): + candidate = parent / relative + if candidate.is_file(): + env['BAZEL_SH'] = str(candidate) + break + if env.get('BAZEL_SH'): + break + env['OPUM_WORLDLINE_PYTHON'] = sys.executable + # 原生图没有 Java 编译,Bazel 使用自带 JDK,避免 IDE 与 CLI 的 Android JDK 改变服务器启动参数。 + env.pop('JAVA_HOME', None) + env['USE_BAZEL_VERSION'] = (HERE / '.bazelversion').read_text().strip() + env.setdefault('BAZELISK_HOME', str(ROOT / 'artifacts/bazelisk')) + windows = rid.startswith('win-') + system = 'windows' if windows else 'unix' + configs = [system, library] if library == 'worldline' else [system] + if library == 'game' and not windows: + configs.append('game-unix') + target_os = rid.split('-')[0] + if target_os in ('linux', 'osx') and (library == 'worldline' or target_os == 'osx'): + configs.append(library + '-' + target_os) + if rid.startswith('android-'): + configs.append('android') + env['ANDROID_NDK_HOME'] = Path(settings['AndroidNdkDirectory']).resolve().as_posix() + if rid == 'win-x86': + configs.append('win-x86') + if library == 'game' and rid == 'win-arm64': + host_arch = 'arm64' if platform.machine().lower() in ('aarch64', 'arm64') else 'x64' + if not env.get('BAZEL_LLVM'): + vswhere = Path(os.environ['ProgramFiles(x86)']) / 'Microsoft Visual Studio/Installer/vswhere.exe' + installation = subprocess.run([str(vswhere), '-latest', '-prerelease', '-products', '*', '-property', 'installationPath'], + check=True, capture_output=True, text=True).stdout.strip() + for arch in (host_arch, 'x64', 'ARM64'): + llvm = Path(installation) / 'VC/Tools/Llvm' / arch + if (llvm / 'bin/clang-cl.exe').is_file(): + env['BAZEL_LLVM'] = str(llvm) + break + configs.append('game-win-arm64') + static = rid.startswith(('ios-', 'iossimulator-')) or rid == 'browser-wasm' + if static: + configure_static(settings, workspace, env) + configs.append('static') + if rid != 'browser-wasm': + configs.append('ios') + options = ['--config=' + config for config in configs] + ['--platforms=//:' + rid] + if library == 'game' and rid == 'win-arm64': + options.append('--host_platform=//:win-' + host_arch + '-clang-host') + if update_lock: + options.append('--lockfile_mode=update') + target = '//:opum_game' if library == 'game' else ('//:worldline_static' if static else '//worldline:worldline') + command = [shutil.which('bazel'), '--nohome_rc', '--nosystem_rc', '--output_user_root=' + str(build_root / 'bazel')] + subprocess.run(command + ['build', *options, target], cwd=workspace, env=env, check=True) + if run_tests: + targets = ['//worldline:worldline_test', '//worldline/model:effects_test', '//worldline/model:continuous_noise_test'] + if library == 'game': + # 上游其余数值用例依赖模型和参考数据,只选择不需要外部数据的既有用例。 + targets = ['@game_cpp//:core_tests', '--test_arg=--gtest_filter=Version.*:Backend.*:ParseFlatIntObject.*:GgufFile.RoundtripMockFile:WavIO.*:Decode.*:Slicer.*:MidiWriter.*:TextWriter.*'] + subprocess.run(command + ['test', *options, *targets], cwd=workspace, env=env, check=True) + if update_lock: + write_changed(HERE / library / 'MODULE.bazel.lock', (workspace / 'MODULE.bazel.lock').read_bytes()) + filename = settings['NativeFileName'] + output = workspace / 'bazel-bin' + if static: + output /= 'libworldline_static.a' + else: + output /= 'worldline' if library == 'worldline' else '.' + output /= filename + write_changed(request.parent / filename, output.read_bytes()) + print(f'Native {library} {rid}: {request.parent / filename}', flush=True) + + +def main(): + """读取 MSBuild 生成的同一份参数,不再另设平台、架构或工具链默认值。""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('input', type=Path) + parser.add_argument('--test', action='store_true') + parser.add_argument('--update-lock', action='store_true') + args = parser.parse_args() + request = args.input.resolve() + settings = dict(line.split('=', 1) for line in request.read_text(encoding='utf-8-sig').splitlines() if '=' in line) + library = settings['NativeLibrary'] + rid = settings['RuntimeIdentifier'] + with build_lock(ROOT / 'artifacts/native-locks' / library / (rid + '.lock')): + build(settings, request, args.test, args.update_lock) + + +if __name__ == '__main__': + main() diff --git a/native/game/.bazelrc b/native/game/.bazelrc deleted file mode 100644 index 4437034f..00000000 --- a/native/game/.bazelrc +++ /dev/null @@ -1,5 +0,0 @@ -build --compilation_mode=opt -build --jobs=2 -build --verbose_failures -build --incompatible_strict_action_env -test --test_output=errors diff --git a/native/game/GameNative.targets b/native/game/GameNative.targets deleted file mode 100644 index ce21cafd..00000000 --- a/native/game/GameNative.targets +++ /dev/null @@ -1,49 +0,0 @@ - - - - true - - <_GameRid>$(RuntimeIdentifier) - <_GameRid Condition="'$(_GameRid)' == ''">$(NETCoreSdkRuntimeIdentifier) - <_GameRid Condition="'$(RuntimeIdentifier)' == '' and '$(PlatformTarget)' == 'x86' and $([MSBuild]::IsOSPlatform('Windows'))">win-x86 - <_GameRid Condition="'$(RuntimeIdentifier)' == '' and '$(PlatformTarget)' == 'ARM64' and $([MSBuild]::IsOSPlatform('Windows'))">win-arm64 - $(MSBuildThisFileDirectory)../../artifacts/game-native - $(MSBuildThisFileDirectory)../../artifacts/game-bazel-build - python - bazel - <_GameResolveToolchainDependsOn Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">ResolveOpumAndroidNativeToolchain - <_GameNativeName Condition="$([System.String]::Copy('$(_GameRid)').StartsWith('win-'))">opum_game.dll - <_GameNativeName Condition="$([System.String]::Copy('$(_GameRid)').StartsWith('linux-')) or $([System.String]::Copy('$(_GameRid)').StartsWith('android-'))">libopum_game.so - <_GameNativeName Condition="$([System.String]::Copy('$(_GameRid)').StartsWith('osx-'))">libopum_game.dylib - <_GameAbi Condition="'$(_GameRid)' == 'android-arm64'">arm64-v8a - <_GameAbi Condition="'$(_GameRid)' == 'android-arm'">armeabi-v7a - <_GameAbi Condition="'$(_GameRid)' == 'android-x64'">x86_64 - <_GameAbi Condition="'$(_GameRid)' == 'android-x86'">x86 - <_GameRuntimeDirectory>$(GameNativeRoot)/$(_GameRid) - - - - - - - <_GameNdkArgument Condition="'$(_OpumAndroidNdkDirectory)' != ''">--ndk "$(_OpumAndroidNdkDirectory)" - - - - - <_GameBuiltFile Include="$(_GameRuntimeDirectory)/*" /> - <_GameLicenseFile Include="$(_GameRuntimeDirectory)/LICENSE.*.txt" /> - - - - - - - - - - - diff --git a/native/game/README.md b/native/game/README.md index cce706ec..1d32d39d 100644 --- a/native/game/README.md +++ b/native/game/README.md @@ -13,41 +13,29 @@ Core 与 USTX 数据结构不需要改动。 ## 构建约定 -`GameNative.targets` 在正常 Build / Publish 中调用 `build.py`,以 Bazelisk 1.29.0 / Bazel 9.2.0 直接编译 C/C++ 源码。 - -1. 在 `artifacts/game-bazel-build//workspace` 准备独立构建入口,按 RID 选择工具链。每次由 Bazel 检查依赖图,同 RID 的构建由进程锁串行化。 -2. `MODULE.bazel` 固定 game.cpp `97f92770704c154e1af4a9b3066b7701041dbc38`、ggml `v0.19.0` 和 pocketfft `32424d2067c2e8043dc646a4e49754b2b40cc549`,归档均带 SHA256。dr_libs 仅供上游 WAV/CLI 测试,不进入应用库依赖图。 -3. 安装到 `artifacts/game-native/`,同时收集许可证及 `game-build.json` 来源记录。 -4. MSBuild 收集产物用于桌面输出或 Android 原生资产。缺少工具链、锁文件过时或下载失败会使构建失败。 - -Worldline 由 [WorldlineNative.targets](../worldline/WorldlineNative.targets) 使用同一版本的 Bazel 构建。 -两者共用 Python 3.10+、Git、Bazelisk 和固定 Android NDK,不需要额外原生构建生成器。 -用户与系统 `.bazelrc` 不参与构建;CPU 发布库不使用构建机的 AVX 指令集。 +构建入口、参数与增量规则见[原生构建](../README.md)。GAME 与 Worldline 共用同一个 MSBuild 接入和 Python 执行脚本。 +`MODULE.bazel` 固定 game.cpp、ggml 和 pocketfft 的版本与归档;dr_libs 只参与上游 WAV/CLI 测试。 +正常 Build / Publish 按项目的配置和 RID 生成并打包 `opum_game`,不收集许可证或生成来源清单。 +CPU 发布库不使用构建机的 AVX 指令集。 Windows x64/x86 使用 Visual Studio MSVC,ARM64 使用 ClangCL,因为 ggml 不支持 MSVC ARM。 Windows ARM64 需要 ARM64 C++ 工具、Windows SDK 及 C++ Clang 编译器。 Linux 使用本机 C/C++ 工具链;macOS 使用 Xcode Command Line Tools,CPU 后端保留 Accelerate。 桌面 Linux/macOS 使用匹配目标架构的 runner。 -Android 先由 `AndroidNativeToolchain.targets` 解析工具链,显式 `AndroidNdkDirectory` 优先, -否则使用 SDK 下 `android-ndk-version.txt` 指定的 r30 LTS(`30.0.16248370`)。 -NDK 路径通过 `--ndk` 传给脚本,并与 .NET 原生资产收集共用;Bazel 使用 NDK Clang,静态链接 libc++。 +Android 使用项目解析的 SDK 与 `../android-ndk-version.txt` 指定的 NDK。 +Bazel 使用 NDK Clang,静态链接 libc++。 ARMv7 关闭不兼容的 llamafile,其他架构保留。工具链发生变化时 Bazel 重新编译受影响的目标。 -可选 MSBuild 属性:`GamePythonExecutable`、`GameBazelExecutable`、`GameBuildRoot`、`GameNativeRoot`。 -`EnableGameGgml=false` 可跳过构建和打包,但不会隐藏 UI 选项或删除旧输出。 -正常 Build / Publish 均包含原生构建。 - ## CI 与本地构建 -PR 矩阵包含桌面六个 RID、Android 四 ABI 的 Worldline 和 GAME 源码构建。 手动使用 `--test` 可运行 19 项无需模型/参考数据的上游既有用例。其余 18 项数值对照/模型用例需要外部数据: 其中 11 项在辅助函数中调用 `GTEST_SKIP` 后仍继续读缺失文件,不能当作自动跳过。 完整目标 `@game_cpp//:core_tests` 仍可在准备好上游参考数据后单独运行。 发布流程通过项目自身的 Build / Publish 规则收集库、打包并上传。 ```sh -python native/game/build.py --rid win-x64 --test +python native/build.py artifacts/native/win-x64/game.inputs --test ``` `--test` 只能用于匹配宿主架构的平台。 diff --git a/native/game/build.py b/native/game/build.py deleted file mode 100644 index a1749355..00000000 --- a/native/game/build.py +++ /dev/null @@ -1,158 +0,0 @@ -"""使用固定 Bazel 和源码依赖构建 GAME/ggml CPU 原生库。""" -import argparse -import hashlib -import json -import locale -import os -from pathlib import Path -import platform -import shutil -import subprocess -import sys - -HERE = Path(__file__).resolve().parent -ROOT = HERE.parent.parent -sys.path.insert(0, str(HERE.parent)) -from bazel_common import build_lock, configure_windows_bash, write_changed - -RIDS = ('win-x64', 'win-arm64', 'win-x86', 'linux-x64', 'linux-arm64', - 'osx-x64', 'osx-arm64', 'android-arm64', 'android-arm', 'android-x64', 'android-x86') -LICENSES = {'game_cpp': 'game.cpp', 'ggml': 'ggml', 'pocketfft': 'pocketfft'} - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--rid', required=True, choices=RIDS) - parser.add_argument('--build-root', type=Path, default=ROOT / 'artifacts/game-bazel-build') - parser.add_argument('--install-root', type=Path, default=ROOT / 'artifacts/game-native') - parser.add_argument('--ndk', type=Path) - parser.add_argument('--bazel', default='bazel') - parser.add_argument('--test', action='store_true', help='Run upstream tests that need no external model/reference data on a matching host') - parser.add_argument('--update-lock', action='store_true') - args = parser.parse_args() - build = args.build_root.resolve() / args.rid - for destination in (build, args.install_root.resolve() / args.rid): - if destination.is_relative_to(HERE.parent) or HERE.parent.is_relative_to(destination): - parser.error(f'Build output overlaps native sources: {destination}') - with build_lock(build / '.build.lock'): - build_native(args, parser, build) - - -def build_native(args, parser, build): - host_os = {'Windows': 'win', 'Linux': 'linux', 'Darwin': 'osx'}[platform.system()] - host_arch = 'arm64' if platform.machine().lower() in ('aarch64', 'arm64') else 'x64' - if not args.rid.startswith(('android-', host_os + '-')): - parser.error(f'Cannot build {args.rid} on {host_os}') - if host_os != 'win' and not args.rid.startswith('android-') and args.rid != f'{host_os}-{host_arch}': - parser.error('Use a native runner for this architecture') - if args.test and args.rid != f'{host_os}-{host_arch}': - parser.error('Tests require a matching native host') - stage = build / 'workspace' - files = [p for p in HERE.iterdir() if p.is_file() and - (p.suffix in ('.bazel', '.BUILD', '.cpp') or p.name in ('.bazelversion', '.bazelrc', 'MODULE.bazel.lock'))] - for path in files: - write_changed(stage / path.name, path.read_bytes()) - version = (HERE / '.bazelversion').read_text().strip() - env = dict(os.environ) - if os.name == 'nt': - env = {key: value for key, value in env.items() if key.upper() != 'PATH'} - env['Path'] = os.environ.get('PATH', '') - configure_windows_bash(env) - if args.test and not env.get('BAZEL_SH'): - parser.error('Bazel tests require Git Bash. Set BAZEL_SH to bash.exe.') - if host_os == 'osx': - # Bazel 的 Apple 编译器包装器在独立版本探测时也需要 SDK 环境。 - env.setdefault('DEVELOPER_DIR', subprocess.run(['xcode-select', '-p'], check=True, capture_output=True, text=True).stdout.strip()) - env.setdefault('SDKROOT', subprocess.run(['xcrun', '--sdk', 'macosx', '--show-sdk-path'], check=True, capture_output=True, text=True).stdout.strip()) - env['USE_BAZEL_VERSION'] = version - env.setdefault('BAZELISK_HOME', str(ROOT / 'artifacts/bazelisk')) - options = [f'--platforms=//:{args.rid}', '--lockfile_mode=' + ('update' if args.update_lock else 'error')] - if args.rid.startswith('win-'): - options += ['--cxxopt=/std:c++17', '--conlyopt=/std:c11', '--copt=/utf-8', '--features=static_link_msvcrt'] - if args.rid == 'win-arm64': - if not env.get('BAZEL_LLVM'): - vswhere = Path(os.environ.get('ProgramFiles(x86)', 'C:/Program Files (x86)')) / 'Microsoft Visual Studio/Installer/vswhere.exe' - if vswhere.is_file(): - installation = subprocess.run([str(vswhere), '-latest', '-prerelease', '-products', '*', '-property', 'installationPath'], - check=True, capture_output=True, text=True).stdout.strip() - for arch in (host_arch, 'x64', 'ARM64'): - llvm = Path(installation) / 'VC/Tools/Llvm' / arch - if (llvm / 'bin/clang-cl.exe').is_file(): - env['BAZEL_LLVM'] = str(llvm) - break - if not env.get('BAZEL_LLVM'): - parser.error('Windows ARM64 GAME requires LLVM. Install the VS C++ Clang component or set BAZEL_LLVM.') - options += ['--copt=--target=aarch64-pc-windows-msvc', '--compiler=clang-cl', f'--host_platform=//:win-{host_arch}-clang-host', - '--extra_toolchains=@local_config_cc//:cc-toolchain-arm64_windows-clang-cl'] - elif args.rid == 'win-x86': - options += ['--extra_toolchains=@local_config_cc//:cc-toolchain-x64_x86_windows'] - else: - options += ['--cxxopt=-std=c++17', '--conlyopt=-std=c11', '--copt=-fPIC', '--copt=-fno-associative-math'] - if args.rid.startswith('osx-'): - options += ['--macos_minimum_os=10.15'] - if args.rid.startswith('android-'): - revision = (HERE / 'android-ndk-version.txt').read_text().strip() - sdk = os.environ.get('ANDROID_HOME') or os.environ.get('ANDROID_SDK_ROOT') - if not sdk: - sdk = str(Path(os.environ['LOCALAPPDATA']) / 'Android/Sdk') if os.name == 'nt' else str(Path.home() / ('Library/Android/sdk' if host_os == 'osx' else 'Android/Sdk')) - ndk = (args.ndk or Path(sdk) / 'ndk' / revision).resolve() - if not (ndk / 'source.properties').is_file(): - parser.error(f'Android NDK not installed: {ndk}') - env['ANDROID_NDK_HOME'] = ndk.as_posix() - options += ['--extra_toolchains=@androidndk//:all', '--linkopt=-Wl,-z,max-page-size=16384', - '--features=static_link_cpp_runtimes'] - bazel = shutil.which(args.bazel) - if not bazel: - parser.error('Bazelisk not found. Install Bazelisk or pass --bazel.') - command = [bazel, '--nohome_rc', '--nosystem_rc', f'--output_user_root={args.build_root.resolve() / "bazel"}'] - - def run(action, targets, capture=False): - return subprocess.run(command + [action] + options + targets, cwd=stage, env=env, - check=True, text=True, stdout=subprocess.PIPE if capture else None) - - try: - run('build', ['//:opum_game']) - if args.test: - # 上游数值对照用例依赖仓库外的 PyTorch 转储;辅助函数中的 GTEST_SKIP 不能终止测试体。 - # 默认明确选择无需外部数据的既有用例,完整测试目标仍保留全部源文件。 - run('test', ['@game_cpp//:core_tests', '--test_arg=--gtest_filter=Version.*:Backend.*:ParseFlatIntObject.*:GgufFile.RoundtripMockFile:WavIO.*:Decode.*:Slicer.*:MidiWriter.*:TextWriter.*']) - paths = run('cquery', ['set(//:opum_game ' + ' '.join('@' + name + '//:license' for name in LICENSES) + ')', '--output=files'], True).stdout.splitlines() - execution_root = Path(run('info', ['execution_root'], True).stdout.strip()) - actions = json.loads(run('aquery', ['mnemonic("CppCompile", deps(//:opum_game))', '--output=jsonproto', '--include_artifacts=false'], True).stdout) - finally: - if args.update_lock and (stage / 'MODULE.bazel.lock').is_file(): - write_changed(HERE / 'MODULE.bazel.lock', (stage / 'MODULE.bazel.lock').read_bytes()) - name = 'opum_game.dll' if args.rid.startswith('win-') else ('libopum_game.dylib' if args.rid.startswith('osx-') else 'libopum_game.so') - libraries = [stage / path for path in paths if Path(path).name == name] - destination = args.install_root.resolve() / args.rid - for repo, license_name in LICENSES.items(): - matches = [execution_root / path for path in paths if '+' + repo + '/' in path] - write_changed(destination / f'LICENSE.{license_name}.txt', matches[0].read_bytes()) - compiler_action = next(action for action in actions['actions'] if action['mnemonic'] == 'CppCompile') - compiler = compiler_action['arguments'][0] - compiler_path = Path(compiler) if Path(compiler).is_absolute() else execution_root / compiler - compiler_env = env | {item['key']: item['value'] for item in compiler_action.get('environmentVariables', [])} - result = subprocess.run([str(compiler_path), '/Bv' if compiler_path.name.lower() == 'cl.exe' else '--version'], - cwd=execution_root, env=compiler_env, capture_output=True) - compiler_info = (result.stdout + result.stderr).decode(locale.getpreferredencoding(False), errors='replace').strip() - if compiler_path.name.lower() == 'cl.exe': - compiler_info = compiler_info.splitlines()[0] - provenance = { - 'rid': args.rid, 'bazel': version, 'backend': 'cpu', 'compiler': compiler, - 'compiler_version': compiler_info, 'compiler_arguments': compiler_action['arguments'], - 'build_options': options, - 'dependencies': (HERE / 'MODULE.bazel').read_text(encoding='utf-8'), - 'lock_sha256': hashlib.sha256((stage / 'MODULE.bazel.lock').read_bytes()).hexdigest(), - 'build_adapter_sha256': {p.relative_to(HERE.parent).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() - for p in files + [HERE / 'build.py', HERE.parent / 'bazel_common.py']}, - 'library_sha256': hashlib.sha256(libraries[0].read_bytes()).hexdigest(), - } - if args.rid.startswith('android-'): - provenance['ndk'] = (ndk / 'source.properties').read_text().strip() - write_changed(destination / name, libraries[0].read_bytes()) - write_changed(destination / 'game-build.json', (json.dumps(provenance, indent=2) + '\n').encode()) - print(f'GAME {args.rid}: {destination / name}', flush=True) - - -if __name__ == '__main__': - main() diff --git a/native/game/game.BUILD b/native/game/game.BUILD index 0c5fd1de..05dfcf63 100644 --- a/native/game/game.BUILD +++ b/native/game/game.BUILD @@ -38,4 +38,3 @@ cc_test( }), deps = [":game", "@gtest//:gtest_main", "@dr_libs//:dr_wav"], ) -filegroup(name = "license", srcs = ["LICENSE"]) diff --git a/native/game/ggml.BUILD b/native/game/ggml.BUILD index cb2734cc..05f76a00 100644 --- a/native/game/ggml.BUILD +++ b/native/game/ggml.BUILD @@ -68,4 +68,3 @@ cc_library( }), linkstatic = True, ) -filegroup(name = "license", srcs = ["LICENSE"]) diff --git a/native/game/pocketfft.BUILD b/native/game/pocketfft.BUILD index f31f3db2..897ee764 100644 --- a/native/game/pocketfft.BUILD +++ b/native/game/pocketfft.BUILD @@ -1,4 +1,3 @@ load("@rules_cc//cc:cc_library.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) cc_library(name = "pocketfft", hdrs = ["pocketfft_hdronly.h"], includes = ["."]) -filegroup(name = "license", srcs = ["LICENSE.md"]) diff --git a/native/worldline/.bazelrc b/native/worldline/.bazelrc deleted file mode 100644 index 7819ea95..00000000 --- a/native/worldline/.bazelrc +++ /dev/null @@ -1,6 +0,0 @@ -build --compilation_mode=opt -build --jobs=2 -build --verbose_failures -build --incompatible_strict_action_env -build --define=absl=1 -test --test_output=errors diff --git a/native/worldline/.bazelversion b/native/worldline/.bazelversion deleted file mode 100644 index deeb3d66..00000000 --- a/native/worldline/.bazelversion +++ /dev/null @@ -1 +0,0 @@ -9.2.0 diff --git a/native/worldline/README.md b/native/worldline/README.md index 5ccc954d..b4ae6ca7 100644 --- a/native/worldline/README.md +++ b/native/worldline/README.md @@ -1,83 +1,12 @@ -# Worldline 源码构建 +# Worldline 源码适配 -`WorldlineNative.targets` 在 Windows、Linux、macOS、Android、iOS、Browser 的正常 Build / Publish 中运行 -`build.py`,使用 Bazelisk 1.29.0 / Bazel 9.2.0 从 `native/upstream_cpp` 构建。 -没有预编译库回退。iOS / Browser 使用同一入口构建静态库并链入宿主。 +构建入口、参数与增量规则见[原生构建](../README.md)。本目录保存 Worldline 的 Bazel 入口、 +固定依赖、上游修订号及构建适配器,源码来自 `../upstream_cpp`。 +旧 BUILD 只在工作副本中补充 Bazel 9 的规则加载,冻结源码保持不变。 -## 工具与平台 +桌面与 Android 使用动态库,iOS 与 Browser 使用包含传递依赖对象的静态归档。 +iOS 模块初始化器将 `DllImport("worldline")` 解析到主程序,SDK 符号项保留对应入口。 +Browser 使用 `worldline.a` 和 `NativeFileReference` 生成静态 P/Invoke 表。 +`TrackWorldlineWasmTrampolines` 补充 SDK 中 `runtime.c` 对跳板表的增量依赖。 -- 所有平台需要 Python 3.10+、Bazelisk 和 Git。Windows 的上游测试还需要 Git Bash。 -- Windows 使用 Visual Studio C++ 工具和 Windows SDK,静态链接 MSVC 运行库;ARM64 需要 ARM64 C++ 组件。 -- Linux 使用目标架构的本机 C/C++ 编译器;macOS 使用本机 Xcode Command Line Tools。两者在对应架构的 runner 构建。 -- Android 使用 `../game/android-ndk-version.txt` 固定的 NDK r30,最低 API 24,支持四 ABI。 - 静态链接 libc++,要求 ELF LOAD 对齐至少 16 KB。`AndroidNdkDirectory` 显式路径优先,否则使用 SDK 中的固定版本。 -- iOS 必须在 macOS 上安装完整 Xcode,支持 `ios-arm64`、`iossimulator-arm64`、`iossimulator-x64`。 - 使用所选 Xcode 的 Clang、ar 和对应 SDK;部署版本跟随宿主的 `SupportedOSPlatformVersion`(直接调用默认 15.0)。 -- Browser 支持 `browser-wasm`,使用当前 .NET `wasm-tools` 工作负载中的 Emscripten、LLVM、Node 和 sysroot。 - 线程、SIMD 和异常模式由 MSBuild 传入,与最终 .NET WASM 链接配置一致,不额外安装独立 Emscripten。 - -原生部分始终使用优化构建;应用 Debug / Release 不改变算法和浮点选项。不使用 `-march=native` 或额外的 fast-math。 - -## 构建隔离与依赖 - -冻结的 CPP subtree 不写入生成文件,也不直接修改。脚本在 `artifacts/worldline-build//workspace` -创建构建副本,仅给旧 BUILD 补上 Bazel 9 要求的规则加载,并叠加本目录的 Bzlmod 入口。 -同一 RID 的构建由进程锁保护;Bazel 每次检查依赖图,失败直接中止应用构建。 - -`MODULE.bazel` 保存上游依赖版本、下载校验和及 WORLD / libpyin / spline 补丁。 -absl、gtest、re2、xxhash 的旧构建文件只在下载副本中适配,避免构建工具的传递依赖升级冻结依赖。 -正常构建使用 `--lockfile_mode=error`;维护依赖时显式运行 `--update-lock`,审查本目录锁文件变更。 -用户与系统 `.bazelrc` 不参与此构建,平台选项由入口统一提供。 - -产物安装到 `artifacts/worldline-native/`。`worldline-build.json` 记录冻结提交、CPP 指纹、依赖与补丁指纹、 -编译器、NDK、Bazel、构建选项和库哈希。这是来源追踪,不表示不同编译器下能生成相同字节。 -许可证和来源清单进入应用的 `WorldlineLicenses`(Android 为 assets 下的同名目录)。 - -更新冻结上游时,也需同步审查 `upstream-revision.txt`、许可证、Bzlmod 依赖和适配器。 -首次构建使用正常 Build / Publish 收集原生资产。 - -## 直接构建 - -```powershell -python native/worldline/build.py --rid win-x64 --test -python native/worldline/build.py --rid android-arm64 -``` - -`--test` 运行上游已有的 worldline、effects、continuous_noise 测试,仅适用于宿主架构。 -音频设备测试需要硬件,不自动运行。 - -## iOS / Browser 静态链接 - -```sh -# macOS:真机和两种模拟器,分别生成 libworldline.a。 -python3 native/worldline/build.py --rid ios-arm64 -python3 native/worldline/build.py --rid iossimulator-arm64 -python3 native/worldline/build.py --rid iossimulator-x64 - -# 通过 .NET 提供精确的 Emscripten 工具和编译配置,生成 worldline.a。 -dotnet msbuild OpenUtauMobile.Browser/OpenUtauMobile.Browser.csproj -t:BuildWorldlineNative -``` - -`cc_static_library` 收集冻结上游的 Worldline、音频接口及传递依赖对象,生成独立归档。 -平台工具链按目标注册;来源清单记录 SDK、目标三元组与选项。 - -iOS 使用 `NativeReference`、C++ 运行库和系统音频框架。宿主模块初始化器将 Core 的 -`DllImport("worldline")` 解析到主程序;链接选项显式保留并导出这些函数。 - -Browser 使用文件名 `worldline.a` 配合 `NativeFileReference`,让 .NET 生成静态 P/Invoke 表, -不修改 Core。许可证和来源清单位于 `wwwroot/licenses/Worldline`。 - -本机 Windows 已验证 Browser 原生构建、Debug 应用链接、Release 发布与 Node 中的 WASM 调用;iOS 配置需在 Mac/CI 实测, -不能将 CI 任务定义视为构建或设备验收通过。现有 Browser Dummy 音频后端及 ONNX 能力边界不因静态库接入改变。 - -真实浏览器中也已通过 Core 的四种 F0 模式及配置初始化调用。接入时发现 .NET 10 的增量构建 -遗漏了 `runtime.c` 对 `wasm_m2n_invoke.g.h` 的依赖,可能复用缺少新 P/Invoke 签名的旧运行时对象。 -`TrackWorldlineWasmTrampolines` 在项目构建层补齐该依赖,无需修改 SDK 或定期手动清理 obj。 - -可选 MSBuild 属性:`WorldlinePythonExecutable`、`WorldlineBazelExecutable`、`WorldlineBuildRoot`、 -`WorldlineNativeRoot`。DesignTimeBuild 不编译或下载。 - -PR 工作流覆盖桌面六个 RID 和 Android 四 ABI 的源码构建。 -发布工作流通过相同 MSBuild 入口构建、打包并上传产物。 -Linux x64/ARM64 的 CI 编译环境固定为 Ubuntu 24.04,避免浮动 runner 自动抬高系统库基线。 -CI 暂不恢复或保存跨任务的 Bazel 编译缓存,每个矩阵任务独立构建;本地下载缓存与目标架构的编译目录分离。 +依赖版本、归档完整性与上游补丁在 `MODULE.bazel` 中声明;更新依赖时同步审查锁文件及适配器。 diff --git a/native/worldline/WorldlineNative.targets b/native/worldline/WorldlineNative.targets deleted file mode 100644 index 5f449a3e..00000000 --- a/native/worldline/WorldlineNative.targets +++ /dev/null @@ -1,99 +0,0 @@ - - - - <_WorldlineRid>$(RuntimeIdentifier) - <_WorldlineRid Condition="'$(_WorldlineRid)' == ''">$(NETCoreSdkRuntimeIdentifier) - <_WorldlineRid Condition="'$(RuntimeIdentifier)' == '' and '$(PlatformTarget)' == 'x86' and $([MSBuild]::IsOSPlatform('Windows'))">win-x86 - <_WorldlineRid Condition="'$(RuntimeIdentifier)' == '' and '$(PlatformTarget)' == 'ARM64' and $([MSBuild]::IsOSPlatform('Windows'))">win-arm64 - $(MSBuildThisFileDirectory)../../artifacts/worldline-native - $(MSBuildThisFileDirectory)../../artifacts/worldline-build - python - python3 - bazel - <_WorldlineResolveToolchainDependsOn Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">ResolveOpumAndroidNativeToolchain - <_WorldlineNativeName Condition="$([System.String]::Copy('$(_WorldlineRid)').StartsWith('win-'))">worldline.dll - <_WorldlineNativeName Condition="$([System.String]::Copy('$(_WorldlineRid)').StartsWith('linux-')) or $([System.String]::Copy('$(_WorldlineRid)').StartsWith('android-'))">libworldline.so - <_WorldlineNativeName Condition="$([System.String]::Copy('$(_WorldlineRid)').StartsWith('osx-'))">libworldline.dylib - <_WorldlineIsIos Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'ios'">true - <_WorldlineIsBrowser Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'browser'">true - <_WorldlineRid Condition="'$(_WorldlineIsBrowser)' == 'true'">browser-wasm - <_WorldlineNativeName Condition="'$(_WorldlineIsIos)' == 'true'">libworldline.a - <_WorldlineNativeName Condition="'$(_WorldlineIsBrowser)' == 'true'">worldline.a - <_WorldlineAbi Condition="'$(_WorldlineRid)' == 'android-arm64'">arm64-v8a - <_WorldlineAbi Condition="'$(_WorldlineRid)' == 'android-arm'">armeabi-v7a - <_WorldlineAbi Condition="'$(_WorldlineRid)' == 'android-x64'">x86_64 - <_WorldlineAbi Condition="'$(_WorldlineRid)' == 'android-x86'">x86 - <_WorldlineRuntimeDirectory>$(WorldlineNativeRoot)/$(_WorldlineRid) - - - - - - - - - <_WorldlineRid>$(RuntimeIdentifier) - <_WorldlineRuntimeDirectory>$(WorldlineNativeRoot)/$(_WorldlineRid) - - - - - - <_WorldlineNdkArgument Condition="'$(_WorldlineAbi)' != ''">--ndk "$(_OpumAndroidNdkDirectory)" - <_WorldlinePlatformArguments Condition="'$(_WorldlineIsIos)' == 'true'">--ios-minimum "$(SupportedOSPlatformVersion)" - <_WorldlineWasmThreads Condition="'$(WasmEnableThreads)' == 'true'">true - <_WorldlineWasmThreads Condition="'$(_WorldlineWasmThreads)' == ''">false - <_WorldlineWasmSimd Condition="'$(WasmEnableSIMD)' == 'true'">true - <_WorldlineWasmSimd Condition="'$(_WorldlineWasmSimd)' == ''">false - <_WorldlineWasmExceptions Condition="'$(WasmEnableExceptionHandling)' == 'true'">true - <_WorldlineWasmExceptions Condition="'$(_WorldlineWasmExceptions)' == ''">false - <_WorldlineNodeName Condition="$([MSBuild]::IsOSPlatform('Windows'))">node.exe - <_WorldlineNodeName Condition="'$(_WorldlineNodeName)' == ''">node - <_WorldlinePlatformArguments Condition="'$(_WorldlineIsBrowser)' == 'true'">--emscripten "$(EmscriptenSdkToolsPath)." --emscripten-cache "$(EmscriptenCacheSdkCacheDir)." --emscripten-node "$(EmscriptenNodeToolsPath)bin/$(_WorldlineNodeName)" --wasm-threads $(_WorldlineWasmThreads) --wasm-simd $(_WorldlineWasmSimd) --wasm-exceptions $(_WorldlineWasmExceptions) - - - - - - <_WorldlineLibrary Include="$(_WorldlineRuntimeDirectory)/$(_WorldlineNativeName)" /> - <_WorldlineMetadata Include="$(_WorldlineRuntimeDirectory)/LICENSE.*.txt;$(_WorldlineRuntimeDirectory)/worldline-build.json" /> - - - - - - - - - - <_WorldlineExport Include="F0FrameCount;F0;DecodeMgc;DecodeBap;InitAnalysisConfig;WorldAnalysisF0In;WorldSynthesisSampleCount;WorldSynthesis;HnAnalysisF0In;WorldSynthesisContinuousNoise;ou_get_audio_device_infos;ou_free_audio_device_infos;ou_init_audio_device;ou_init_audio_device_auto;ou_get_audio_device_api;ou_get_audio_device_name;ou_free_audio_device;ou_audio_device_start;ou_audio_device_stop;ou_audio_get_error_message" /> - - - - - - - - - - - - - - - - <_WasmRuntimePackSrcFile Update="@(_WasmRuntimePackSrcFile)" - Condition="'%(_WasmRuntimePackSrcFile.Filename)' == 'runtime'"> - %(_WasmRuntimePackSrcFile.Dependencies);$(_WasmInterpToNativeTablePath) - - - - diff --git a/native/worldline/build.py b/native/worldline/build.py deleted file mode 100644 index 510c37a6..00000000 --- a/native/worldline/build.py +++ /dev/null @@ -1,225 +0,0 @@ -"""在独立构建副本中用固定 Bazel 编译冻结的 Worldline 源码。""" -import argparse -import hashlib -import json -import locale -import os -from pathlib import Path -import platform -import re -import shutil -import subprocess -import sys - -sys.path.insert(0, str(Path(__file__).resolve().parents[1])) -from bazel_common import build_lock, configure_windows_bash, write_changed -from static_platforms import STATIC_RIDS, configure - -HERE = Path(__file__).resolve().parent -ROOT = HERE.parent.parent -SOURCE = HERE.parent / 'upstream_cpp' -RIDS = ('win-x64', 'win-arm64', 'win-x86', 'linux-x64', 'linux-arm64', - 'osx-x64', 'osx-arm64', 'android-arm64', 'android-arm', 'android-x64', 'android-x86') + STATIC_RIDS -LICENSES = ('world', 'libgvps', 'libnpy', 'libpyin', 'spline', 'miniaudio', 'xxhash') - - -def stage_sources(destination): - files = {} - source_hash = hashlib.sha256() - for source in sorted(SOURCE.rglob('*')): - if not source.is_file(): - continue - relative = source.relative_to(SOURCE).as_posix() - content = source.read_bytes() - source_hash.update(relative.encode() + b'\0' + content + b'\0') - if relative in ('.bazelrc', '.bazelversion', 'MODULE.bazel', 'MODULE.bazel.lock', 'WORKSPACE.bazel'): - continue - if source.name == 'BUILD.bazel' or source.suffix == '.BUILD': - # 只补 Bazel 9 的显式规则加载;源文件、目标依赖和上游补丁保持原样。 - rules = sorted(set(re.findall(rb'^\s*(cc_\w+)\(', content, re.MULTILINE))) - loads = b''.join(b'load("@rules_cc//cc:' + rule + b'.bzl", "' + rule + b'")\n' for rule in rules) - content = loads + content - if source.suffix == '.BUILD': - pattern = '["*.c", "*.h"]' if source.stem == 'libpyin' else '["LICENSE*"]' - content += ('\nfilegroup(name = "opum_license", srcs = glob(' + pattern + '))\n').encode() - files[relative] = content - for name in ('.bazelversion', '.bazelrc', 'MODULE.bazel', 'BUILD.bazel', 'MODULE.bazel.lock', - 'frozen_archive.bzl', 'adapt_build.py', 'xxhash.BUILD', 'static_toolchain.bzl'): - source = HERE / name - if source.is_file(): - files[name] = source.read_bytes() - manifest = destination / '.opum-files.json' - if manifest.is_file(): - for relative in set(json.loads(manifest.read_text())) - files.keys(): - obsolete = (destination / relative).resolve() - if not obsolete.is_relative_to(destination.resolve()): - raise ValueError('Invalid generated-file manifest path') - obsolete.unlink(missing_ok=True) - for relative, content in files.items(): - write_changed(destination / relative, content) - write_changed(manifest, json.dumps(sorted(files)).encode()) - return source_hash.hexdigest() - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--rid', required=True, choices=RIDS) - parser.add_argument('--build-root', type=Path, default=ROOT / 'artifacts/worldline-build') - parser.add_argument('--install-root', type=Path, default=ROOT / 'artifacts/worldline-native') - parser.add_argument('--ndk', type=Path) - parser.add_argument('--emscripten', type=Path) - parser.add_argument('--emscripten-cache', type=Path) - parser.add_argument('--emscripten-node', type=Path) - parser.add_argument('--wasm-threads', choices=('true', 'false'), default='true') - parser.add_argument('--wasm-simd', choices=('true', 'false'), default='true') - parser.add_argument('--wasm-exceptions', choices=('true', 'false'), default='true') - parser.add_argument('--ios-minimum', default='15.0') - parser.add_argument('--bazel', default='bazel') - parser.add_argument('--test', action='store_true') - parser.add_argument('--update-lock', action='store_true') - args = parser.parse_args() - build = args.build_root.resolve() / args.rid - for destination in (build / 'workspace', args.install_root.resolve() / args.rid): - for protected in (SOURCE, HERE): - if destination.is_relative_to(protected) or protected.is_relative_to(destination): - parser.error(f'Build output overlaps source: {destination}') - with build_lock(build / '.build.lock'): - build_native(args, parser, build) - - -def build_native(args, parser, build): - host_os = {'Windows': 'win', 'Linux': 'linux', 'Darwin': 'osx'}[platform.system()] - host_arch = 'arm64' if platform.machine().lower() in ('aarch64', 'arm64') else 'x64' - is_static = args.rid in STATIC_RIDS - if not is_static and not args.rid.startswith('android-') and not args.rid.startswith(host_os + '-'): - parser.error(f'Cannot build {args.rid} on {host_os}') - if not is_static and host_os != 'win' and not args.rid.startswith('android-') and args.rid != f'{host_os}-{host_arch}': - parser.error('Use a native runner for this architecture') - if args.test and args.rid != f'{host_os}-{host_arch}': - parser.error('Tests require a matching native host') - stage = build / 'workspace' - digest = stage_sources(stage) - static_sdk = configure(args, parser, stage) if is_static else None - adapter_hashes = {path.name: hashlib.sha256(path.read_bytes()).hexdigest() for path in sorted(HERE.iterdir()) - if path.is_file() and (path.suffix in ('.py', '.bzl', '.bazel', '.BUILD') or path.name in ('.bazelrc', '.bazelversion'))} - upstream_commit = (HERE / 'upstream-revision.txt').read_text().strip() - version = (HERE / '.bazelversion').read_text().strip() - # Windows 环境变量名不区分大小写,避免宿主注入 PATH/Path 导致 MSBuild 启动失败。 - env = dict(os.environ) - if os.name == 'nt': - path = os.environ.get('PATH', '') - env = {key: value for key, value in env.items() if key.upper() != 'PATH'} - env['Path'] = path - configure_windows_bash(env) - if args.test and not env.get('BAZEL_SH'): - parser.error('Bazel tests require Git Bash. Set BAZEL_SH to bash.exe.') - if host_os == 'osx': - # Bazel 的 Apple 编译器包装器在独立版本探测时也需要 SDK 环境。 - env.setdefault('DEVELOPER_DIR', subprocess.run(['xcode-select', '-p'], check=True, capture_output=True, text=True).stdout.strip()) - env.setdefault('SDKROOT', subprocess.run(['xcrun', '--sdk', 'macosx', '--show-sdk-path'], check=True, capture_output=True, text=True).stdout.strip()) - env['USE_BAZEL_VERSION'] = version - env['OPUM_WORLDLINE_PYTHON'] = sys.executable - env.setdefault('BAZELISK_HOME', str(ROOT / 'artifacts/bazelisk')) - options = [f'--platforms=//:{args.rid}', '--lockfile_mode=' + ('update' if args.update_lock else 'error')] - if is_static: - options += ['--extra_toolchains=//sdk_toolchain:toolchain'] - if args.rid != 'browser-wasm': - options += ['--per_file_copt=worldline/audio_output[.]cc@-x,objective-c++'] - if args.rid.startswith('win-'): - options += ['--cxxopt=/std:c++17', '--copt=/utf-8', '--features=static_link_msvcrt'] - if args.rid == 'win-x86': - options += ['--extra_toolchains=@local_config_cc//:cc-toolchain-x64_x86_windows'] - else: - options += ['--cxxopt=-std=c++17'] - if args.rid.startswith('osx-'): - options += ['--macos_minimum_os=10.12'] - if args.rid.startswith('linux-'): - options += ['--linkopt=-lm'] - if args.rid.startswith('android-'): - revision = (HERE.parent / 'game/android-ndk-version.txt').read_text().strip() - sdk = os.environ.get('ANDROID_HOME') or os.environ.get('ANDROID_SDK_ROOT') - if not sdk: - sdk = str(Path(os.environ['LOCALAPPDATA']) / 'Android/Sdk') if os.name == 'nt' else str(Path.home() / ('Library/Android/sdk' if host_os == 'osx' else 'Android/Sdk')) - ndk = (args.ndk or Path(sdk) / 'ndk' / revision).resolve() - if not (ndk / 'source.properties').is_file(): - parser.error(f'Android NDK not installed: {ndk}') - env['ANDROID_NDK_HOME'] = ndk.as_posix() - options += ['--extra_toolchains=@androidndk//:all', - '--linkopt=-Wl,-z,max-page-size=16384', '--features=static_link_cpp_runtimes'] - bazel = shutil.which(args.bazel) - if not bazel: - parser.error('Bazelisk not found. Install Bazelisk or pass --bazel.') - command = [bazel, '--nohome_rc', '--nosystem_rc', - f'--output_user_root={args.build_root.resolve() / "bazel"}'] - - def run(action, targets, capture=False): - return subprocess.run(command + [action] + options + targets, cwd=stage, env=env, - check=True, text=True, stdout=subprocess.PIPE if capture else None) - - try: - target = '//:worldline_static' if is_static else '//worldline:worldline' - run('build', [target]) - if args.test: - run('test', ['//worldline:worldline_test', '//worldline/model:effects_test', '//worldline/model:continuous_noise_test']) - paths = run('cquery', ['set(' + target + ' ' + ' '.join('@' + name + '//:opum_license' for name in LICENSES) + ')', '--output=files'], capture=True).stdout.splitlines() - license_paths = [path for path in paths if path.startswith('external/')] - actions = json.loads(run('aquery', ['mnemonic("CppCompile", deps(' + target + '))', - '--output=jsonproto', '--include_artifacts=false'], capture=True).stdout) - execution_root = Path(run('info', ['execution_root'], capture=True).stdout.strip()) - finally: - generated_lock = stage / 'MODULE.bazel.lock' - if args.update_lock and generated_lock.is_file(): - write_changed(HERE / 'MODULE.bazel.lock', generated_lock.read_bytes()) - name = 'worldline.dll' if args.rid.startswith('win-') else ('libworldline.dylib' if args.rid.startswith('osx-') else 'libworldline.so') - if is_static: - name = 'libworldline_static.a' - libraries = [stage / path for path in paths if Path(path).name == name] - destination = args.install_root.resolve() / args.rid - if is_static: - name = 'worldline.a' if args.rid == 'browser-wasm' else 'libworldline.a' - licenses = {name: [] for name in LICENSES} - for path in license_paths: - repo = next((name for name in LICENSES if '+' + name + '/' in path), None) - content = (execution_root / path).read_text(encoding='utf-8') - if repo == 'libpyin': - notices = re.findall(r'/\*.*?\*/', content, re.DOTALL) - content = '\n\n'.join(notice for notice in notices if 'Copyright' in notice and 'Redistribution' in notice) - if content.strip() and content not in licenses[repo]: - licenses[repo].append(content) - for license_name, contents in licenses.items(): - write_changed(destination / f'LICENSE.{license_name}.txt', ('\n\n'.join(contents) + '\n').encode()) - write_changed(destination / 'LICENSE.worldline.txt', (HERE / 'LICENSE.worldline.txt').read_bytes()) - write_changed(destination / name, libraries[0].read_bytes()) - compiler_action = next(action for action in actions['actions'] if action['mnemonic'] == 'CppCompile') - compiler = compiler_action['arguments'][0] - compiler_path = Path(compiler) if Path(compiler).is_absolute() else execution_root / compiler - compiler_env = env | {item['key']: item['value'] for item in compiler_action.get('environmentVariables', [])} - compiler_result = subprocess.run([str(compiler_path), '/Bv' if compiler_path.name.lower() == 'cl.exe' else '--version'], - cwd=execution_root, env=compiler_env, capture_output=True) - compiler_info = (compiler_result.stdout + compiler_result.stderr).decode(locale.getpreferredencoding(False), errors='replace').strip() - if is_static: - compiler_info = static_sdk['compiler_version'] - if compiler_path.name.lower() == 'cl.exe': - # cl /Bv 输出版本后因没有输入文件返回非零;保留首行版本与目标架构。 - compiler_info = compiler_info.splitlines()[0] - provenance = {'rid': args.rid, 'bazel': version, 'source_sha256': digest, - 'upstream_commit': upstream_commit, - 'compiler': static_sdk['compiler'] if is_static else compiler, 'compiler_version': compiler_info, - 'compiler_arguments': compiler_action['arguments'], - 'build_options': options, - 'module_sha256': hashlib.sha256((stage / 'MODULE.bazel').read_bytes()).hexdigest(), - 'lock_sha256': hashlib.sha256((stage / 'MODULE.bazel.lock').read_bytes()).hexdigest(), - 'build_adapter_sha256': adapter_hashes, - 'dependencies': (stage / 'MODULE.bazel').read_text(encoding='utf-8'), - 'patches': {path.name: hashlib.sha256(path.read_bytes()).hexdigest() for path in sorted((SOURCE / 'third_party').glob('*.patch'))}, - 'library_sha256': hashlib.sha256(libraries[0].read_bytes()).hexdigest()} - if args.rid.startswith('android-'): - provenance['ndk'] = (ndk / 'source.properties').read_text().strip() - if is_static: - provenance['static_sdk'] = static_sdk - write_changed(destination / 'worldline-build.json', (json.dumps(provenance, indent=2) + '\n').encode()) - print(f'Worldline {args.rid}: {destination / name}', flush=True) - - -if __name__ == '__main__': - main() diff --git a/native/worldline/frozen_archive.bzl b/native/worldline/frozen_archive.bzl index 0e1a41ac..bb187ba1 100644 --- a/native/worldline/frozen_archive.bzl +++ b/native/worldline/frozen_archive.bzl @@ -9,8 +9,6 @@ def _frozen_archive_impl(ctx): if ctx.attr.build_file: ctx.file("BUILD.bazel", ctx.read(ctx.attr.build_file)) python = ctx.os.environ.get("OPUM_WORLDLINE_PYTHON") - if not python: - fail("Use native/worldline/build.py to provide the Python build adapter.") result = ctx.execute([python, ctx.path(ctx.attr._adapter)], timeout = 60) if result.return_code: fail("Bazel build adaptation failed: " + result.stderr) diff --git a/native/worldline/static_platforms.py b/native/worldline/static_platforms.py deleted file mode 100644 index 28d7be29..00000000 --- a/native/worldline/static_platforms.py +++ /dev/null @@ -1,120 +0,0 @@ -"""为 iOS 和 .NET Browser 生成使用宿主 SDK 的 Bazel 工具链。""" -import hashlib -import json -import os -import platform -from pathlib import Path -import subprocess -import sys - -from bazel_common import write_changed - -STATIC_RIDS = ('ios-arm64', 'iossimulator-arm64', 'iossimulator-x64', 'browser-wasm') - - -def configure(args, parser, stage): - def output(command): - return subprocess.run(command, check=True, capture_output=True, text=True).stdout.strip() - - environment = {} - if args.rid == 'browser-wasm': - if not args.emscripten or not args.emscripten_cache: - parser.error('Browser requires --emscripten and --emscripten-cache from the .NET wasm-tools workload; use MSBuild BuildWorldlineNative.') - sdk = args.emscripten.resolve() - sysroot = args.emscripten_cache.resolve() / 'sysroot' - suffix = '.exe' if platform.system() == 'Windows' else '' - compiler = sdk / ('bin/clang' + suffix) - driver = Path(sys.executable) - archiver = sdk / ('bin/llvm-ar' + suffix) - nm = sdk / ('bin/llvm-nm' + suffix) - target = 'wasm32-unknown-emscripten' - flags = [(sdk / 'emscripten/emcc.py').as_posix(), '-fno-fast-math'] - node = args.emscripten_node - if node is None: - node_pack = sdk.parent.parent.name.replace('.Sdk.', '.Node.') - node = sdk.parents[2] / node_pack / sdk.parent.name / 'tools/bin' / ('node' + suffix) - if not node.is_file(): - parser.error(f'Missing .NET Emscripten Node: {node}') - environment = {'DOTNET_EMSCRIPTEN_LLVM_ROOT': (sdk / 'bin').as_posix(), - 'DOTNET_EMSCRIPTEN_BINARYEN_ROOT': sdk.as_posix(), - 'DOTNET_EMSCRIPTEN_NODE_JS': node.resolve().as_posix(), - 'EM_CACHE': args.emscripten_cache.resolve().as_posix(), - 'PYTHONUTF8': '1'} - if args.wasm_threads == 'true': - flags += ['-pthread'] - if args.wasm_simd == 'true': - flags += ['-msimd128'] - flags += ['-fwasm-exceptions' if args.wasm_exceptions == 'true' else '-fexceptions'] - sdk_version = (sdk / 'emscripten/emscripten-version.txt').read_text().strip() - constraints = ['@platforms//os:emscripten', '@platforms//cpu:wasm32'] - else: - if platform.system() != 'Darwin': - parser.error('iOS source builds require macOS and Xcode (including the iOS SDK).') - sdk_name = 'iphoneos' if args.rid == 'ios-arm64' else 'iphonesimulator' - sysroot = Path(output(['xcrun', '--sdk', sdk_name, '--show-sdk-path'])) - compiler = Path(output(['xcrun', '--sdk', sdk_name, '--find', 'clang'])) - driver = compiler - archiver = Path(output(['xcrun', '--sdk', sdk_name, '--find', 'ar'])) - nm = Path(output(['xcrun', '--sdk', sdk_name, '--find', 'nm'])) - sdk = compiler.parent.parent - arch = 'x86_64' if args.rid.endswith('-x64') else 'arm64' - target = arch + '-apple-ios' + args.ios_minimum - if sdk_name == 'iphonesimulator': - target += '-simulator' - flags = ['--target=' + target, '-isysroot', sysroot.as_posix(), '-fPIC', '-fno-fast-math'] - sdk_version = output(['xcrun', '--sdk', sdk_name, '--show-sdk-version']) - constraints = ['@platforms//os:ios', '@platforms//cpu:' + arch, - '//:ios_device' if sdk_name == 'iphoneos' else '//:ios_simulator'] - for required in (compiler, archiver, nm, sysroot): - if not required.exists(): - parser.error(f'Missing SDK component: {required}') - # 查询实际的系统头文件搜索路径;不能用 / 放行所有未声明头文件。 - probe = subprocess.run([str(driver), *flags, '-x', 'c++', '-E', '-v', '-'], - env=os.environ | environment, input='', text=True, capture_output=True, check=True) - includes = [] - collecting = False - for line in probe.stderr.splitlines(): - if '#include <...> search starts here:' in line: - collecting = True - elif 'End of search list.' in line: - collecting = False - elif collecting: - includes.append(Path(line.strip().removesuffix(' (framework directory)')).as_posix()) - if not includes: - raise RuntimeError('Clang did not report system include directories') - if args.rid != 'browser-wasm': - # Xcode 27 将 SDKSettings.json 也写入依赖文件;限于选定 SDK,兼容 Xcode 路径符号链接。 - includes += [sysroot.as_posix(), sysroot.resolve().as_posix()] - compiler_version = output([str(compiler), '--version']) - # SDK 原地升级时也使 Bazel 编译动作失效,不仅依靠安装路径区分版本。 - environment['OPUM_WORLDLINE_SDK_FINGERPRINT'] = hashlib.sha256((sdk_version + compiler_version).encode()).hexdigest() - flags += ['-O2', '-DNDEBUG'] - quote = json.dumps - config = f'''load("@rules_cc//cc/toolchains:cc_toolchain.bzl", "cc_toolchain") -load("//:static_toolchain.bzl", "static_toolchain_config") -package(default_visibility = ["//visibility:public"]) -filegroup(name = "empty") -static_toolchain_config( - name = "config", compiler_path = {quote(driver.as_posix())}, - archiver_path = {quote(archiver.as_posix())}, target = {quote(target)}, - cpu = {quote(args.rid.split('-')[1])}, flags = {quote(flags)}, - builtin_includes = {quote(includes)}, - environment = {quote(environment)}, - archive_param_file = {args.rid == 'browser-wasm'}, -) -cc_toolchain( - name = "cc", toolchain_identifier = "opum-worldline-static", - toolchain_config = ":config", all_files = ":empty", compiler_files = ":empty", - linker_files = ":empty", ar_files = ":empty", as_files = ":empty", - dwp_files = ":empty", objcopy_files = ":empty", strip_files = ":empty", - supports_param_files = 1, -) -toolchain(name = "toolchain", toolchain = ":cc", - toolchain_type = "@bazel_tools//tools/cpp:toolchain_type", - target_compatible_with = {quote(constraints)}) -''' - write_changed(stage / 'sdk_toolchain/BUILD.bazel', config.encode()) - return {'sdk': str(sdk), 'sdk_version': sdk_version, 'sysroot': str(sysroot), - 'target': target, 'flags': flags, 'nm': str(nm), 'environment': environment, - 'compiler': str(compiler), 'compiler_version': compiler_version, - 'toolchain_sha256': hashlib.sha256(config.encode()).hexdigest()} diff --git a/native/worldline/xxhash.BUILD b/native/worldline/xxhash.BUILD index 713584c8..96ce0154 100644 --- a/native/worldline/xxhash.BUILD +++ b/native/worldline/xxhash.BUILD @@ -1,7 +1,5 @@ load("@rules_cc//cc:cc_library.bzl", "cc_library") -filegroup(name = "opum_license", srcs = ["LICENSE"], visibility = ["//visibility:public"]) - cc_library( name = "xxhash", srcs = ["xxhash.c"], From cffeff8cf1fe265e7498380a98bd42fc4c7bdc8f Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:29:25 +0800 Subject: [PATCH 10/45] =?UTF-8?q?fix:=20=E5=8E=BB=E9=99=A4=E9=87=8D?= =?UTF-8?q?=E5=A4=8Dndk=E6=89=AB=E6=8F=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- native/.bazelrc | 2 + native/NativeBuild.targets | 3 +- native/README.md | 2 + native/android-ndk-inputs.patch | 186 ++++++++++++++++++++++++++++++++ native/build.py | 2 +- native/game/BUILD.bazel | 2 +- native/game/MODULE.bazel | 6 ++ native/worldline/BUILD.bazel | 2 +- native/worldline/MODULE.bazel | 6 ++ 9 files changed, 207 insertions(+), 4 deletions(-) create mode 100644 native/android-ndk-inputs.patch diff --git a/native/.bazelrc b/native/.bazelrc index 516ec9d7..128e0738 100644 --- a/native/.bazelrc +++ b/native/.bazelrc @@ -8,6 +8,8 @@ build:unix --cxxopt=-std=c++17 build:worldline --define=absl=1 build:game-unix --copt=-fno-associative-math build:android --extra_toolchains=@androidndk//:all --linkopt=-Wl,-z,max-page-size=16384 --features=static_link_cpp_runtimes +# NDK 使用本机安装的 SDK;头文件由 -MD 跟踪,编译动作直接访问 SDK,避免沙箱复制整棵目录。 +build:android --spawn_strategy=local build:worldline-linux --linkopt=-lm build:worldline-osx --macos_minimum_os=10.12 build:game-osx --macos_minimum_os=10.15 diff --git a/native/NativeBuild.targets b/native/NativeBuild.targets index 1aa6bee2..847431a9 100644 --- a/native/NativeBuild.targets +++ b/native/NativeBuild.targets @@ -48,7 +48,8 @@ - <_NativeCommonSource Include="$(_NativeRoot)build.py;$(_NativeRoot)NativeBuild.targets;$(_NativeRoot).bazelrc;$(_NativeRoot).bazelversion;$(_NativeRoot)android-ndk-version.txt" /> + <_NativeCommonSource Include="$(_NativeRoot)build.py;$(_NativeRoot)NativeBuild.targets;$(_NativeRoot).bazelrc;$(_NativeRoot).bazelversion" /> + <_NativeCommonSource Include="$(_NativeRoot)android-ndk-version.txt;$(_NativeRoot)android-ndk-inputs.patch" Condition="'$(_NativePlatform)' == 'android'" /> <_WorldlineSource Include="$(_NativeRoot)upstream_cpp/**/*;$(_NativeRoot)worldline/**/*" Exclude="$(_NativeRoot)**/__pycache__/**;$(_NativeRoot)**/*.md;$(_NativeRoot)**/LICENSE*;$(_NativeRoot)worldline/WorldlineIosResolver.cs" /> <_GameSource Include="$(_NativeRoot)game/**/*" Exclude="$(_NativeRoot)**/__pycache__/**;$(_NativeRoot)**/*.md" /> diff --git a/native/README.md b/native/README.md index f30dc582..17334b53 100644 --- a/native/README.md +++ b/native/README.md @@ -8,6 +8,8 @@ Worldline 和 GAME 的源码与 Bazel 依赖分别位于各自目录;冻结的 - 项目的 TFM、`RuntimeIdentifier(s)`、`Configuration` 和 SDK 解析结果决定构建目标。 - 共同的 C/C++ 编译选项放在 `.bazelrc`,沿用原有的优化构建,Debug/Release 共用算法与浮点选项。 - Android NDK 版本由 `android-ndk-version.txt` 指定。SDK 解析安装根目录,两个库使用同一路径。 +- 两库共用 `android-ndk-inputs.patch` 收窄 NDK 工具链输入;系统头文件由编译器 `-MD` 结果记录实际依赖,运行库按 ABI 和 API 选择。 +- Android 原生动作使用本地执行策略,直接访问所选 SDK;Linux 构建机同样无需把整个 SDK 头文件树复制进沙箱。 - iOS、Browser 的静态工具链使用项目所选的系统 SDK 或 .NET 工作负载,最低系统版本与 WASM 特性跟随项目。 - Python 读取 MSBuild 生成的 `.inputs` 文件,不另设 RID、SDK 路径或编译开关默认值。 diff --git a/native/android-ndk-inputs.patch b/native/android-ndk-inputs.patch new file mode 100644 index 00000000..c47a3a31 --- /dev/null +++ b/native/android-ndk-inputs.patch @@ -0,0 +1,186 @@ +diff --git a/BUILD.ndk_clang.tpl b/BUILD.ndk_clang.tpl +--- a/BUILD.ndk_clang.tpl ++++ b/BUILD.ndk_clang.tpl +@@ -18,7 +18,7 @@ + + [cc_toolchain( + name = "cc_toolchain_%s" % target_system_name, +- all_files = ":all_files", ++ all_files = ":all_files_%s" % target_system_name, + ar_files = ":ar_files", + as_files = ":as_files", + compiler_files = ":compiler_files_%s" % target_system_name, +@@ -44,24 +44,36 @@ + toolchain_identifier = "toolchain_identifier_%s" % target_system_name, + ) for target_system_name in TARGET_SYSTEM_NAMES] + ++# 只登记工具链实际调用的程序及其宿主动态库,不扫描包装脚本、调试器和 Python。 + filegroup( + name = "all_binaries", +- srcs = glob( +- [ +- "bin/*", +- "lib64/**/*", +- "lib/**/*", +- ], +- # Need to allow_empty here because previous NDK versions had +- # "lib" & "lib64" directories but recent ones only have "lib". +- allow_empty = True, +- ), ++ srcs = [ ++ "bin/clang{executable_extension}", ++ "bin/clang++{executable_extension}", ++ "bin/ld{executable_extension}", ++ "bin/ld.lld{executable_extension}", ++ "bin/llvm-ar{executable_extension}", ++ "bin/llvm-dwp{executable_extension}", ++ "bin/llvm-nm{executable_extension}", ++ "bin/llvm-objcopy{executable_extension}", ++ "bin/llvm-objdump{executable_extension}", ++ "bin/llvm-strip{executable_extension}", ++ ] + glob([ ++ "bin/libwinpthread-1.dll", ++ "lib/*.so*", ++ "lib/*.dylib", ++ "lib64/*.so*", ++ ], allow_empty = True), + ) + +-filegroup( +- name = "all_files", +- srcs = glob(["**/*"]) + ["//{sysroot_directory}:all_files"], +-) ++[filegroup( ++ name = "all_files_%s" % target_system_name, ++ srcs = [ ++ ":compiler_files_%s" % target_system_name, ++ ":linker_files_%s" % target_system_name, ++ ":strip_files", ++ ], ++) for target_system_name in TARGET_SYSTEM_NAMES] + + filegroup( + name = "ar_files", +@@ -75,24 +87,12 @@ + output_licenses = ["unencumbered"], + ) + ++# 系统头文件由编译器 -MD 结果加入实际输入,不将整个 SDK 头文件树设为每个动作的强制输入。 + [filegroup( + name = "compiler_files_%s" % target_system_name, + srcs = [ +- "bin/clang{executable_extension}", +- ":ar_files", +- ":as_files", +- ":objcopy_files", +- "//{sysroot_directory}:sysroot_includes", +- ] + glob( +- [ +- "prebuilt_include/**", +- "include/**", +- "lib/gcc/%s/**" % target_system_name, +- "lib64/**/*", +- "lib/**/*", +- ], +- allow_empty = True, +- ), ++ ":all_binaries", ++ ], + output_licenses = ["unencumbered"], + ) for target_system_name in TARGET_SYSTEM_NAMES] + +@@ -118,19 +118,17 @@ + srcs = ["//{sysroot_directory}:libc_top_%s" % target_system_name], + ) for target_system_name in TARGET_SYSTEM_NAMES] + ++# 链接只依赖当前 ABI 的运行库及所选 API 的存根,不纳入其他 API 目录。 + [filegroup( + name = "linker_files_%s" % target_system_name, + srcs = [ + ":all_binaries", +- ":static_runtime_lib_%s" % target_system_name, +- ] + glob( +- [ +- "lib/gcc/%s/**" % target_system_name, +- "lib64/**", +- "lib/**", +- ], +- allow_empty = True, +- ), ++ "//{sysroot_directory}:libraries_%s" % target_system_name, ++ ] + glob([ ++ "{clang_resource_directory}/lib/linux/libclang_rt.*-%s-android*" % target_system_name.split("-")[0], ++ "{clang_resource_directory}/lib/linux/liborc_rt-%s-android.a" % target_system_name.split("-")[0], ++ "{clang_resource_directory}/lib/linux/%s/*" % {"i686": "i386"}.get(target_system_name.split("-")[0], target_system_name.split("-")[0]), ++ ], allow_empty = True), + ) for target_system_name in TARGET_SYSTEM_NAMES] + + filegroup( +@@ -146,6 +144,6 @@ + + filegroup( + name = "strip_files", +- srcs = [":all_files"], ++ srcs = [":all_binaries"], + output_licenses = ["unencumbered"], + ) +diff --git a/BUILD.ndk_sysroot.tpl b/BUILD.ndk_sysroot.tpl +--- a/BUILD.ndk_sysroot.tpl ++++ b/BUILD.ndk_sysroot.tpl +@@ -4,11 +4,13 @@ + + load("//:target_systems.bzl", "TARGET_SYSTEM_NAMES") + +-filegroup( +- name = "all_files", +- srcs = glob(["**/*"]), +- visibility = ["//visibility:public"], +-) ++[filegroup( ++ name = "libraries_%s" % target_system_name, ++ srcs = glob([ ++ "usr/lib/%s/*" % target_system_name, ++ "usr/lib/%s/{api_level}/*" % target_system_name, ++ ]), ++) for target_system_name in TARGET_SYSTEM_NAMES] + + [filegroup( + name = "libc_top_%s" % target_system_name, +@@ -21,10 +23,7 @@ + + [filegroup( + name = "dynamic_runtime_lib_%s" % target_system_name, +- srcs = glob([ +- # "usr/lib/%s/**/*.so" % target_system_name, +- # "usr/lib/%s/**/*.a" % target_system_name, +- ], allow_empty = True), ++ srcs = [], + ) for target_system_name in TARGET_SYSTEM_NAMES] + + [filegroup( +@@ -32,24 +31,5 @@ + srcs = [ + "usr/lib/%s/libc++_static.a" % target_system_name, + "usr/lib/%s/libc++abi.a" % target_system_name, +- ] + { +- # libandroid_support was removed in NDK 26, so use a glob +- # for backward compatibility. +- "arm-linux-androideabi": glob([ +- "usr/lib/arm-linux-androideabi/libandroid_support.a", +- ], allow_empty = True), +- "i686-linux-android": glob([ +- "usr/lib/i686-linux-android/libandroid_support.a", +- ], allow_empty = True), +- }.get( +- target_system_name, +- [], +- ), ++ ], + ) for target_system_name in TARGET_SYSTEM_NAMES] +- +-filegroup( +- name = "sysroot_includes", +- srcs = glob([ +- "**/include/**/*", +- ]), +-) diff --git a/native/build.py b/native/build.py index dd2938a2..d18587f9 100644 --- a/native/build.py +++ b/native/build.py @@ -71,7 +71,7 @@ def stage_sources(library, destination): for source in (HERE / library).iterdir(): if source.is_file() and (source.suffix in ('.bazel', '.BUILD', '.bzl', '.cpp', '.py') or source.name == 'MODULE.bazel.lock'): files[source.name] = source.read_bytes() - for name in ('.bazelrc', '.bazelversion'): + for name in ('.bazelrc', '.bazelversion', 'android-ndk-inputs.patch'): files[name] = (HERE / name).read_bytes() manifest = destination / '.opum-files.json' if manifest.is_file(): diff --git a/native/game/BUILD.bazel b/native/game/BUILD.bazel index 96b5065a..7c788506 100644 --- a/native/game/BUILD.bazel +++ b/native/game/BUILD.bazel @@ -1,6 +1,6 @@ load("@rules_cc//cc:cc_binary.bzl", "cc_binary") package(default_visibility = ["//visibility:public"]) -exports_files(["game.BUILD", "ggml.BUILD", "pocketfft.BUILD", "gtest.BUILD", "dr_libs.BUILD"]) +exports_files(["game.BUILD", "ggml.BUILD", "pocketfft.BUILD", "gtest.BUILD", "dr_libs.BUILD", "android-ndk-inputs.patch"]) cc_binary( name = "opum_game", srcs = ["game_bridge.cpp"], diff --git a/native/game/MODULE.bazel b/native/game/MODULE.bazel index 3a87cfe2..73fb1368 100644 --- a/native/game/MODULE.bazel +++ b/native/game/MODULE.bazel @@ -4,6 +4,12 @@ bazel_dep(name = "rules_cc", version = "0.2.25") bazel_dep(name = "platforms", version = "1.1.0") bazel_dep(name = "rules_android_ndk", version = "0.1.5") +single_version_override( + module_name = "rules_android_ndk", + patches = ["//:android-ndk-inputs.patch"], + patch_strip = 1, +) + cc_configure = use_extension("@rules_cc//cc:extensions.bzl", "cc_configure_extension") use_repo(cc_configure, "local_config_cc") android_ndk = use_extension("@rules_android_ndk//:extension.bzl", "android_ndk_repository_extension") diff --git a/native/worldline/BUILD.bazel b/native/worldline/BUILD.bazel index e495591f..e48ace42 100644 --- a/native/worldline/BUILD.bazel +++ b/native/worldline/BUILD.bazel @@ -1,7 +1,7 @@ load("@rules_cc//cc:cc_static_library.bzl", "cc_static_library") package(default_visibility = ["//visibility:public"]) -exports_files(["adapt_build.py", "xxhash.BUILD"]) +exports_files(["adapt_build.py", "xxhash.BUILD", "android-ndk-inputs.patch"]) platform(name = "win-x64", constraint_values = ["@platforms//os:windows", "@platforms//cpu:x86_64"]) platform(name = "win-arm64", constraint_values = ["@platforms//os:windows", "@platforms//cpu:arm64"]) diff --git a/native/worldline/MODULE.bazel b/native/worldline/MODULE.bazel index 634e95b1..3f9ca4aa 100644 --- a/native/worldline/MODULE.bazel +++ b/native/worldline/MODULE.bazel @@ -5,6 +5,12 @@ bazel_dep(name = "platforms", version = "1.1.0") bazel_dep(name = "rules_android_ndk", version = "0.1.5") bazel_dep(name = "bazel_skylib", version = "1.9.2") +single_version_override( + module_name = "rules_android_ndk", + patches = ["//:android-ndk-inputs.patch"], + patch_strip = 1, +) + cc_configure = use_extension("@rules_cc//cc:extensions.bzl", "cc_configure_extension") use_repo(cc_configure, "local_config_cc") From f3bf53b0a17683d20c95bd5bc1dbd1409b967005 Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:48:02 +0800 Subject: [PATCH 11/45] =?UTF-8?q?performance:=20=E6=8F=90=E5=8D=87Android?= =?UTF-8?q?=E6=89=93=E5=8C=85=E9=80=9F=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- OpenUtauMobile.Android/OpenUtauMobile.Android.csproj | 2 ++ 1 file changed, 2 insertions(+) diff --git a/OpenUtauMobile.Android/OpenUtauMobile.Android.csproj b/OpenUtauMobile.Android/OpenUtauMobile.Android.csproj index 387aee1b..5b59a136 100644 --- a/OpenUtauMobile.Android/OpenUtauMobile.Android.csproj +++ b/OpenUtauMobile.Android/OpenUtauMobile.Android.csproj @@ -17,6 +17,8 @@ $(BaseApplicationId).debug + + true From f511d0a842713b351cc51e63c9f2103b2ee9a44d Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Tue, 3 Nov 2026 19:15:33 +0800 Subject: [PATCH 12/45] =?UTF-8?q?chore:=20=E4=BF=AE=E6=94=B9=E9=BB=98?= =?UTF-8?q?=E8=AE=A4=E9=92=A2=E7=90=B4=E5=8D=B7=E5=B8=98=E7=BA=B5=E5=90=91?= =?UTF-8?q?=E6=BB=9A=E5=8A=A8=E8=A1=8C=E4=B8=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- OpenUtau.Core/Util/Preferences.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/OpenUtau.Core/Util/Preferences.cs b/OpenUtau.Core/Util/Preferences.cs index 3460b38b..f5caea38 100644 --- a/OpenUtau.Core/Util/Preferences.cs +++ b/OpenUtau.Core/Util/Preferences.cs @@ -368,7 +368,7 @@ public class SerializablePreferences { public double PlaybackRefreshRate = 20.0; /// 回放时钢琴卷帘纵向滚动:0 = 关闭,1 = 边界滚动,2 = 保持居中。 - public int PlaybackVerticalScroll = 0; + public int PlaybackVerticalScroll = 2; /// /// Android 全屏模式:0 = 始终,1 = 仅编辑页,2 = 关闭。 @@ -380,8 +380,8 @@ public class SerializablePreferences { /// public bool AndroidKeepScreenAwakeWhileEditing = true; -/// - /// Piano key behavior: 0=Silent, 1=SineWave, 2=SoundFont + /// + /// 钢琴键行为:0=静音,1=正弦波,2=SoundFont采样 /// public int PianoKeyBehavior = 1; @@ -402,14 +402,14 @@ public class SerializablePreferences { public string SoundFontPath = string.Empty; /// - /// Preferred audio backend. Empty string means auto-select based on platform. + /// 偏好的音频后端。空字符串表示根据平台自动选择。 /// Supported values: - /// - "" or "Auto": Auto-select (default) + /// - "" or "Auto": 自动 (default) /// - "MiniAudio": Use MiniAudio (Windows/Linux/macOS/Android) /// - "NAudio": Use NAudio (Windows only) /// - "AudioTrack": Use Android AudioTrack (Android only) /// - "Dummy": Use dummy audio output (all platforms, no sound) - /// Platform-specific availability: + /// 特定平台的可用性: /// - Windows: MiniAudio, NAudio, Dummy /// - Linux/macOS: MiniAudio, Dummy /// - Android: MiniAudio, AudioTrack, Dummy From b7449e6f921ff20f06c2fab1b60b474786a745a9 Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Tue, 3 Nov 2026 23:37:12 +0800 Subject: [PATCH 13/45] =?UTF-8?q?feature:=20=E5=9C=A8=E5=AE=89=E8=A3=85?= =?UTF-8?q?=E6=8F=92=E4=BB=B6=E5=89=8D=E8=AD=A6=E5=91=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- OpenUtauMobile/Assets/Lang/Strings.en.resx | 12 ++++++++ OpenUtauMobile/Assets/Lang/Strings.ja.resx | 12 ++++++++ OpenUtauMobile/Assets/Lang/Strings.ru.resx | 12 ++++++++ OpenUtauMobile/Assets/Lang/Strings.uk.resx | 12 ++++++++ .../Assets/Lang/Strings.zh-Hans.resx | 12 ++++++++ .../Services/PluginManagementService.cs | 28 +++++++++++++++---- .../ViewModels/PluginManagerViewModel.cs | 12 ++++++++ OpenUtauMobile/Views/PluginManagerView.axaml | 23 +++------------ OpenUtauMobile/Views/SettingsView.axaml | 4 +-- 9 files changed, 100 insertions(+), 27 deletions(-) diff --git a/OpenUtauMobile/Assets/Lang/Strings.en.resx b/OpenUtauMobile/Assets/Lang/Strings.en.resx index e87e7335..03a79a0b 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.en.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.en.resx @@ -2200,6 +2200,18 @@ Select DLL plugin + + Trust plugin + + + Do you trust the plugin “{0}”? + + + Plugins have the same permissions as this app. Malicious plugins may read or leak personal information, modify or delete files, or perform other harmful actions. The OpenUtau Mobile developers are not responsible for plugin behavior. Only install plugins from trusted sources. + + + Continue + Checking managed assembly… diff --git a/OpenUtauMobile/Assets/Lang/Strings.ja.resx b/OpenUtauMobile/Assets/Lang/Strings.ja.resx index d55dad52..04587399 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.ja.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.ja.resx @@ -2196,6 +2196,18 @@ DLL プラグインを選択 + + プラグインの信頼 + + + プラグイン「{0}」を信頼しますか? + + + プラグインは本アプリと同じ権限を持ちます。悪意のあるプラグインは、個人情報の読み取りや漏えい、ファイルの変更や削除、その他の有害な操作を行う可能性があります。 OpenUtau Mobile の開発者はプラグインの動作に責任を負いません。信頼できる提供元のプラグインのみをインストールしてください。 + + + 続行 + マネージドアセンブリを確認中… diff --git a/OpenUtauMobile/Assets/Lang/Strings.ru.resx b/OpenUtauMobile/Assets/Lang/Strings.ru.resx index e67224c8..eb7e1be9 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.ru.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.ru.resx @@ -2155,6 +2155,18 @@ Выберите DLL-плагин + + Доверие плагину + + + Вы доверяете плагину «{0}»? + + + Плагины имеют те же разрешения, что и приложение. Вредоносные плагины могут читать или раскрывать личную информацию, изменять или удалять файлы либо выполнять другие вредоносные действия. Разработчики OpenUtau Mobile не несут ответственности за поведение плагинов. Устанавливайте плагины только из надёжных источников. + + + Продолжить + Проверка управляемой сборки… diff --git a/OpenUtauMobile/Assets/Lang/Strings.uk.resx b/OpenUtauMobile/Assets/Lang/Strings.uk.resx index 603418c9..a8ff9033 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.uk.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.uk.resx @@ -2155,6 +2155,18 @@ Виберіть DLL-плагін + + Довіра до плагіна + + + Чи довіряєте ви плагіну «{0}»? + + + Плагіни мають ті самі дозволи, що й застосунок. Шкідливі плагіни можуть читати або розголошувати особисту інформацію, змінювати чи видаляти файли або виконувати інші шкідливі дії. Розробники OpenUtau Mobile не несуть відповідальності за поведінку плагінів. Встановлюйте плагіни лише з надійних джерел. + + + Продовжити + Перевірка керованої збірки… diff --git a/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx b/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx index 60fcb3f0..6da506f8 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx @@ -2200,6 +2200,18 @@ 选择 DLL 插件 + + 信任插件 + + + 是否信任插件“{0}”? + + + 插件拥有和本软件相同的权限,恶意插件可能会读取或泄露个人信息、修改或删除文件,或执行其他有害操作。 OpenUtau Mobile 开发者不对插件的行为负责。请仅安装来自可信来源的插件。 + + + 继续 + 正在检查托管程序集… diff --git a/OpenUtauMobile/Services/PluginManagementService.cs b/OpenUtauMobile/Services/PluginManagementService.cs index 68b151df..e494c461 100644 --- a/OpenUtauMobile/Services/PluginManagementService.cs +++ b/OpenUtauMobile/Services/PluginManagementService.cs @@ -47,24 +47,40 @@ public static IReadOnlyList ListFiles() .ToArray(); } - public static async Task InstallAsync(string sourcePath, LoadingPopupViewModel loading) + /// 在询问信任前检查安装条件,仅读取元数据,不加载程序集。 + public static void ValidateForInstall(string sourcePath) + { + using FileStream source = new(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read); + ValidateForInstall(sourcePath, source); + } + + /// 校验安装条件并返回目标路径,不写入插件目录。 + private static string ValidateForInstall(string sourcePath, Stream source) { - // TODO:补充 iOS 外部程序集执行能力和 Web 导入、加载链路的专门适配。 string fileName = Path.GetFileName(sourcePath); if (!string.Equals(Path.GetExtension(fileName), ".dll", StringComparison.OrdinalIgnoreCase)) throw new InvalidDataException(L.S("PluginManager.InvalidAssembly")); if (string.Equals(fileName, BuiltinFileName, StringComparison.OrdinalIgnoreCase)) throw new InvalidDataException(L.S("PluginManager.BuiltinNotAllowed")); - await using FileStream source = new(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read); - loading.UpdateProgress(0, L.S("PluginManager.Checking")); ValidateAssembly(source); - source.Position = 0; - Directory.CreateDirectory(Root); string destination = ResolvePluginPath(fileName); if (File.Exists(destination) || ReadPendingDeletions().Contains(fileName)) throw new IOException(L.S("PluginManager.AlreadyExists")); + return destination; + } + + /// 重新校验并复制已获用户信任的插件,不加载程序集。 + public static async Task InstallAsync(string sourcePath, LoadingPopupViewModel loading) + { + // TODO:补充 iOS 外部程序集执行能力和 Web 导入、加载链路的专门适配。 + await using FileStream source = new(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read); + loading.UpdateProgress(0, L.S("PluginManager.Checking")); + // 确认期间源文件或安装状态可能变化,复制前再次检查。 + string destination = ValidateForInstall(sourcePath, source); + source.Position = 0; + Directory.CreateDirectory(Root); // 临时文件不使用 DLL 扩展名,只有完整复制后才进入插件列表。 string temporaryPath = Path.Combine(Root, $".{Guid.NewGuid():N}.installing"); diff --git a/OpenUtauMobile/ViewModels/PluginManagerViewModel.cs b/OpenUtauMobile/ViewModels/PluginManagerViewModel.cs index 09aa83e9..23456f18 100644 --- a/OpenUtauMobile/ViewModels/PluginManagerViewModel.cs +++ b/OpenUtauMobile/ViewModels/PluginManagerViewModel.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Reactive; using System.Threading.Tasks; using DynamicData.Binding; @@ -83,6 +84,17 @@ private async Task InstallAsync() { string path = await FilePicker.PickSingleFileAsync(L.S("PluginManager.SelectFile"), ["*.dll"]); if (string.IsNullOrEmpty(path)) return; + await LoadingPopupService.RunAsync(L.S("PluginManager.Checking"), + _ => Task.Run(() => PluginManagementService.ValidateForInstall(path))); + string? answer = await OptionConfirmPopupService.ShowAsync( + L.S("PluginManager.TrustTitle"), + string.Format(L.S("PluginManager.TrustQuestion"), Path.GetFileName(path)) + + Environment.NewLine + Environment.NewLine + L.S("PluginManager.TrustMessage"), + [ + new OptionConfirmOption(L.S("Common.Cancel"), "cancel", isDefault: true), + new OptionConfirmOption(L.S("PluginManager.Continue"), "continue", isDestructive: true), + ]); + if (answer != "continue") return; await LoadingPopupService.RunAsync(L.S("PluginManager.Checking"), 0, async loading => { await Task.Run(() => PluginManagementService.InstallAsync(path, loading)); diff --git a/OpenUtauMobile/Views/PluginManagerView.axaml b/OpenUtauMobile/Views/PluginManagerView.axaml index d928def6..ffdfd98d 100644 --- a/OpenUtauMobile/Views/PluginManagerView.axaml +++ b/OpenUtauMobile/Views/PluginManagerView.axaml @@ -7,19 +7,6 @@ xmlns:icons="https://github.com/MahApps/IconPacks.Avalonia" x:Class="OpenUtauMobile.Views.PluginManagerView" x:DataType="vm:PluginManagerViewModel"> - - - - @@ -50,8 +37,7 @@ - + @@ -62,15 +48,14 @@ - + private void OnAudioDevicePickerLoaded(object? sender, RoutedEventArgs e) + { + if (sender is ContentControl { Content: null } host) + { + host.Content = ServiceHub.AudioDevicePickerFactory?.Invoke(RefreshAudioRoute); + } + } + + /// 系统路由变化后同步设置页中的实际输出设备。 + private void RefreshAudioRoute() + { + if (DataContext is SettingsViewModel vm && vm.ArePreferencesInitialized) + { + _ = vm.RefreshAudioDevicesAsync(); + } + } + private void OnSizeChanged(object? sender, SizeChangedEventArgs e) { if (DataContext is SettingsViewModel vm) From 888866882be7a186ce7c71a7713f65b14e80e48d Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Wed, 4 Nov 2026 01:00:19 +0800 Subject: [PATCH 15/45] =?UTF-8?q?feature:=20=E6=B5=8F=E8=A7=88=E5=99=A8?= =?UTF-8?q?=E9=9F=B3=E9=A2=91=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- OpenUtauMobile.Browser/Program.cs | 13 +- OpenUtauMobile.Browser/README.md | 6 +- .../Audio/BrowserAudioDevicePicker.cs | 32 ++ .../Services/Audio/BrowserAudioInterop.cs | 121 +++++++ .../Services/Audio/BrowserAudioOutput.cs | 342 ++++++++++++++++++ .../wwwroot/audio-output-buffer.js | 5 + .../wwwroot/audio-output-worklet.js | 52 +++ .../wwwroot/audio-output.js | 234 ++++++++++++ .../ViewModels/SettingsViewModel.cs | 7 +- 9 files changed, 807 insertions(+), 5 deletions(-) create mode 100644 OpenUtauMobile.Browser/Services/Audio/BrowserAudioDevicePicker.cs create mode 100644 OpenUtauMobile.Browser/Services/Audio/BrowserAudioInterop.cs create mode 100644 OpenUtauMobile.Browser/Services/Audio/BrowserAudioOutput.cs create mode 100644 OpenUtauMobile.Browser/wwwroot/audio-output-buffer.js create mode 100644 OpenUtauMobile.Browser/wwwroot/audio-output-worklet.js create mode 100644 OpenUtauMobile.Browser/wwwroot/audio-output.js diff --git a/OpenUtauMobile.Browser/Program.cs b/OpenUtauMobile.Browser/Program.cs index a08598a9..8d305a96 100644 --- a/OpenUtauMobile.Browser/Program.cs +++ b/OpenUtauMobile.Browser/Program.cs @@ -17,6 +17,7 @@ using OpenUtauMobile.Browser.Services.Graphics; using OpenUtauMobile.Browser.Services.Platform; using OpenUtauMobile.Browser.Services; +using OpenUtauMobile.Browser.Services.Audio; using Serilog; internal sealed partial class Program @@ -31,6 +32,12 @@ private static async Task Main(string[] args) reactiveUIBuilder.WithExceptionHandler(Observer.Create(HandleReactiveException)); }); await BrowserExternalUrlLauncher.InitializeAsync(); + await BrowserAudioInterop.InitializeAsync(); + if (BrowserAudioInterop.CanSelectDevice) + { + ServiceHub.AudioDevicePickerFactory = onRouteChanged => new BrowserAudioDevicePicker(onRouteChanged); + ServiceHub.GetSystemAudioOutputDevices = BrowserAudioInterop.GetCurrentDevices; + } BrowserGraphicsBackendPreferenceStore graphicsStore = await BrowserGraphicsBackendPreferenceStore.CreateAsync(); BrowserGraphicsBackendProvider graphicsProvider = new(); GraphicsBackendService graphicsService = new(graphicsProvider, graphicsStore); @@ -133,7 +140,7 @@ private static void InitAudioOutput() Log.Warning("Preferred backend {Backend} failed to initialize; falling back.", pref); } - string[] fallbackOrder = ["Dummy"]; + string[] fallbackOrder = ["WebAudio", "Dummy"]; foreach (string backend in fallbackOrder) { @@ -152,6 +159,10 @@ private static bool TryInitAudioBackend(string backend) { switch (backend) { + case "WebAudio": + PlaybackManager.Inst.AudioOutput = new BrowserAudioOutput(); + Log.Information("Using Web Audio output."); + return true; case "Dummy": PlaybackManager.Inst.AudioOutput = new DummyAudioOutput(); Log.Information("Using Dummy audio backend (silent)."); diff --git a/OpenUtauMobile.Browser/README.md b/OpenUtauMobile.Browser/README.md index 1d74e93c..66286731 100644 --- a/OpenUtauMobile.Browser/README.md +++ b/OpenUtauMobile.Browser/README.md @@ -14,7 +14,7 @@ dotnet run --project OpenUtauMobile.Browser/OpenUtauMobile.Browser.csproj -c Deb - Worldline 在 Build / Publish 中通过 Bazel 源码构建为静态 WASM 归档,随后由 .NET 链入运行时。 除 `wasm-tools` 外需要 Python 3.10+、Git 和 Bazelisk;Emscripten 使用工作负载配套版本。 - 详见 [Worldline 构建说明](../native/worldline/README.md)。这不包含 ONNX 后端或浏览器音频播放接入。 + 详见 [Worldline 构建说明](../native/worldline/README.md)。这不包含 ONNX 后端。 - 启用 `WasmEnableThreads`,保留音素化与短语构建后台线程。SDK 开发服务器会自动附加跨源隔离响应头。 - 浏览器控制台默认记录 Information 及以上级别,不全局监听 FirstChanceException。已捕获异常和正常任务取消不应逐次创建后台日志任务;拖动命令的 Debug 日志也不应逐条跨线程输出到控制台。 - Debug 的原生编译使用 `-Oz`,原生链接使用 `-O2`。本机 .NET 10.0.12 的 `-O0` 多线程原生构建在运行时初始化时断言失败;这些设置保留 C# 的 Debug 配置和调试符号。相关上游记录:。 @@ -58,6 +58,8 @@ IDBFS 会把已保存的文件加载到内存,适合先接通现有同步文 当前 .NET 10 多线程 WASM 仍存在致命定时器锁异常风险:`System.Threading.Lock.Exit` → `TimerQueueTimer.Fire/Dispose` → `Task.Delay`,随后可能出现 GC 等待线程暂停失败并使页面失去响应。该堆栈已在 Chromium 内核浏览器中通过并发定时器、可取消延时复现;移除 FirstChanceException 日志任务、关闭 JITerpreter 均不能消除它。相关上游问题仍未关闭:[dotnet/runtime#129900](https://github.com/dotnet/runtime/issues/129900)。这些日志优化不代表多线程稳定性问题已经修复。当前后端会直接创建音素化和短语构建线程,单独关闭 `WasmEnableThreads` 会破坏初始化,不能作为现有架构的直接替代方案。 -启动、托管外部音素器扫描与后台音素化可以运行,但这不代表所有桌面插件和音频引擎都适用于浏览器。当前音频输出仍是既有的 Dummy 后端。ONNX 原生库在浏览器中不可用,重新读取偏好时的 ONNX 设备校验会记录异常;这不影响已验证的普通托管音素器。 +音频默认使用 Web Audio:后台读取采样源,AudioWorklet 消费有界缓冲。首次播放需要点击或按键授权;系统挂起后可再次操作恢复。设置中可选择 Web Audio 或 Dummy,后端切换重启后生效。支持设备授权及 `AudioContext.setSinkId` 的浏览器提供输出设备选择,否则使用系统默认设备。设备授权不请求麦克风权限。 + +启动、托管外部音素器扫描与后台音素化可以运行,但这不代表所有桌面插件和渲染器都适用于浏览器。ONNX 原生库在浏览器中不可用,重新读取偏好时的 ONNX 设备校验会记录异常;这不影响已验证的普通托管音素器。 持久化已验证工程保存后的页面刷新与浏览器关闭后重新打开,以及中文路径、覆盖、重命名、删除和写入失败后的重试。实际歌手导入与安装流程尚未验证。 diff --git a/OpenUtauMobile.Browser/Services/Audio/BrowserAudioDevicePicker.cs b/OpenUtauMobile.Browser/Services/Audio/BrowserAudioDevicePicker.cs new file mode 100644 index 00000000..1a6ea136 --- /dev/null +++ b/OpenUtauMobile.Browser/Services/Audio/BrowserAudioDevicePicker.cs @@ -0,0 +1,32 @@ +using System; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Interactivity; + +namespace OpenUtauMobile.Browser.Services.Audio; + +/// 通过用户点击请求浏览器设备授权,并展示切换成功后的实际路由。 +internal sealed class BrowserAudioDevicePicker : Button +{ + /// 复用设置页按钮样式,在控件存活期间监听系统设备变化。 + public BrowserAudioDevicePicker(Action onRouteChanged) + { + this.Bind(ContentProperty, this.GetResourceObservable("Settings.Render.OutputDevice")); + Classes.Add("filled"); + Click += SelectOutput; + Loaded += (_, _) => BrowserAudioInterop.DevicesChanged += onRouteChanged; + Unloaded += (_, _) => BrowserAudioInterop.DevicesChanged -= onRouteChanged; + } + + /// 直接从点击事件调用浏览器,保留系统选择器要求的用户激活。 + private async void SelectOutput(object? sender, RoutedEventArgs args) + { + try + { + IsEnabled = false; + await BrowserAudioInterop.SelectOutputAsync(); + } + catch (Exception exception) { BrowserAudioInterop.ReportError(0, exception.Message); } + finally { IsEnabled = true; } + } +} diff --git a/OpenUtauMobile.Browser/Services/Audio/BrowserAudioInterop.cs b/OpenUtauMobile.Browser/Services/Audio/BrowserAudioInterop.cs new file mode 100644 index 00000000..8d4d7edc --- /dev/null +++ b/OpenUtauMobile.Browser/Services/Audio/BrowserAudioInterop.cs @@ -0,0 +1,121 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices.JavaScript; +using System.Threading.Tasks; +using Avalonia.Threading; +using OpenUtau.Audio; +using OpenUtau.Core; +using OpenUtauMobile.Tools; +using Serilog; + +namespace OpenUtauMobile.Browser.Services.Audio; + +/// 在浏览器主线程连接 Web Audio,并为后台音频对象提供能力快照。 +internal static partial class BrowserAudioInterop +{ + private const string ModuleName = "OpenUtauMobileAudio"; + private static readonly object deviceLock = new(); + private static List currentDevices = []; + + /// 初始化成功后提供给浏览器宿主的输出采样率。 + internal static int SampleRate { get; private set; } + /// 是否可以通过浏览器的系统设备选择器切换输出。 + internal static bool CanSelectDevice { get; private set; } + internal static event Action? DevicesChanged; + + /// 预先加载音频线程,在用户首次操作之前准备好暂停的上下文。 + internal static async Task InitializeAsync() + { + try + { + await JSHost.ImportAsync(ModuleName, "/audio-output.js"); + SampleRate = await Initialize(JSHost.DotnetInstance); + CanSelectDevice = CanSelectOutput(); + } + catch (Exception exception) + { + SampleRate = 0; + Log.Error(exception, "浏览器音频初始化失败,将使用静音后端"); + } + } + + /// 返回当前已选路由的快照,不从后台线程调用浏览器 API。 + internal static List GetCurrentDevices() + { + lock (deviceLock) + { + return [.. currentDevices]; + } + } + + /// 音频线程通过主线程通知请求下一批样本。 + [JSExport] + public static async Task RequestData(int generation) + { + await Dispatcher.UIThread.InvokeAsync(() => BrowserAudioOutput.Active?.Pump(generation)); + } + + /// 将消费时钟与上下文状态同步到托管快照。 + [JSExport] + public static async Task UpdateStatus(int generation, double frames, int state, double latency) + { + await Dispatcher.UIThread.InvokeAsync(() => BrowserAudioOutput.Active?.UpdateStatus(generation, frames, state, latency)); + } + + /// 异步接收浏览器错误,避免从 JS 主线程同步进入托管运行时。 + [JSExport] + public static async Task ReceiveError(int generation, string message) + { + await Dispatcher.UIThread.InvokeAsync(() => ReportError(generation, message)); + } + + /// 将浏览器错误送入现有通知系统,保留用户重新授权的机会。 + internal static void ReportError(int generation, string message) + { + Log.Error("浏览器音频错误: {Message}", message); + DocManager.Inst.ExecuteCmd(new ErrorMessageNotification(new InvalidOperationException(message))); + } + + /// 设备切换成功后更新实际路由,设置页仅展示这个结果。 + [JSExport] + public static async Task UpdateDevice(string id, string name) + { + await Dispatcher.UIThread.InvokeAsync(() => + { + lock (deviceLock) + { + currentDevices = string.IsNullOrEmpty(id) || string.IsNullOrEmpty(name) + ? [] + : [new AudioOutputDevice + { + api = "WebAudio", + name = name, + deviceNumber = 0, + guid = GuidTools.CreateGuidFromStrings("WebAudio", id), + }]; + } + DevicesChanged?.Invoke(); + }); + } + + [JSImport("initialize", ModuleName)] + private static partial Task Initialize(JSObject runtime); + + [JSImport("canSelectOutput", ModuleName)] + private static partial bool CanSelectOutput(); + + [JSImport("setPlayback", ModuleName)] + internal static partial void SetPlayback(int generation, int state); + + [JSImport("writableFrames", ModuleName)] + internal static partial int WritableFrames(int generation); + + [JSImport("writeSamples", ModuleName)] + internal static partial void WriteSamples(int generation, byte[] samples, int count); + + [JSImport("endInput", ModuleName)] + internal static partial void EndInput(int generation); + + [JSImport("selectOutput", ModuleName)] + internal static partial Task SelectOutputAsync(); +} \ No newline at end of file diff --git a/OpenUtauMobile.Browser/Services/Audio/BrowserAudioOutput.cs b/OpenUtauMobile.Browser/Services/Audio/BrowserAudioOutput.cs new file mode 100644 index 00000000..9dc4bd03 --- /dev/null +++ b/OpenUtauMobile.Browser/Services/Audio/BrowserAudioOutput.cs @@ -0,0 +1,342 @@ +using System; +using System.Buffers; +using System.Collections.Generic; +using System.Threading; +using Avalonia.Threading; +using NAudio.Wave; +using NAudio.Wave.SampleProviders; +using OpenUtau.Audio; +using OpenUtauMobile.Services.Performance; +using Serilog; + +namespace OpenUtauMobile.Browser.Services.Audio; + +/// 后台生产浮点采样,通过主线程有界搬运到浏览器音频线程。 +internal sealed class BrowserAudioOutput : IAudioOutput, IAudioLatencySource, IDisposable +{ + private const int Channels = 2; + private const int BlockSamples = 1024 * Channels; + private const int QueueBlockCount = 2; + private static BrowserAudioOutput? active; + private static int nextGeneration; + private readonly object syncRoot = new(); + private readonly Queue blocks = new(); + private readonly byte[] transferBuffer = new byte[BlockSamples * sizeof(float)]; + private ISampleProvider? sampleProvider; + private PlaybackState playbackState; + private int generation = Interlocked.Increment(ref nextGeneration); + private int requestedState; + private int queuedSamples; + private double consumedFrames; + private double transportLatency; + private bool inputEnded; + private bool synchronizationPosted; + private bool pumpPosted; + private bool disposed; + + /// 原生音频线程不会进入托管运行时,由这个后台线程读取采样源。 + public BrowserAudioOutput() + { + if (BrowserAudioInterop.SampleRate == 0) + { + throw new InvalidOperationException("Web Audio is unavailable."); + } + if (Interlocked.CompareExchange(ref active, this, null) != null) + { + throw new InvalidOperationException("A browser audio output is already active."); + } + Thread producer = new(ProduceSamples) { IsBackground = true, Name = "Browser audio producer" }; + try + { + producer.Start(); + } + catch + { + Interlocked.CompareExchange(ref active, null, this); + throw; + } + } + + /// 主线程回调访问的唯一输出实例。 + internal static BrowserAudioOutput? Active => Volatile.Read(ref active); + + /// 读取已同步的传输状态;等待用户激活时保持可继续的暂停状态。 + public PlaybackState PlaybackState + { + get { lock (syncRoot) return playbackState; } + } + + /// 路由由浏览器选择器管理,不持久化枚举序号。 + public int DeviceNumber => 0; + + /// 包括托管队列、音频线程队列及浏览器可报告的设备延迟。 + public double? OutputLatencyMilliseconds + { + get + { + lock (syncRoot) + { + return transportLatency + queuedSamples * 1000.0 / Channels / BrowserAudioInterop.SampleRate; + } + } + } + + /// 设备列表仅反映已授权且实际选中的系统路由。 + public List GetOutputDevices() => BrowserAudioInterop.GetCurrentDevices(); + + /// 设备授权与切换必须通过设置页的用户操作完成。 + public void SelectDevice(Guid guid, int deviceNumber) + { + if (guid != Guid.Empty && !GetOutputDevices().Exists(device => device.guid == guid)) + { + throw new NotSupportedException("Select an audio output using the browser device picker."); + } + } + + /// 准备匹配上下文采样率的立体声源,并丢弃上一代缓冲。 + public void Init(ISampleProvider provider) + { + ISampleProvider prepared = provider; + if (provider.WaveFormat.SampleRate != BrowserAudioInterop.SampleRate) + { + prepared = new WdlResamplingSampleProvider(provider, BrowserAudioInterop.SampleRate); + } + prepared = prepared.ToStereo(); + lock (syncRoot) + { + ObjectDisposedException.ThrowIf(disposed, this); + ResetLocked(); + sampleProvider = prepared; + ScheduleSynchronizationLocked(); + } + } + + /// 请求播放,等待上下文解锁及首批数据后再报告实际播放状态。 + public void Play() + { + lock (syncRoot) + { + ObjectDisposedException.ThrowIf(disposed, this); + if (sampleProvider == null) return; + requestedState = 1; + playbackState = PlaybackState.Paused; + ScheduleSynchronizationLocked(); + Monitor.PulseAll(syncRoot); + } + } + + /// 保留两侧缓冲和输入位置,暂停时不再读取采样源。 + public void Pause() + { + lock (syncRoot) + { + if (requestedState == 0 || disposed) return; + requestedState = 2; + playbackState = PlaybackState.Paused; + ScheduleSynchronizationLocked(); + } + } + + /// 切换播放代次,使旧的回调和未播放样本全部失效。 + public void Stop() + { + lock (syncRoot) + { + if (disposed) return; + ResetLocked(); + ScheduleSynchronizationLocked(); + } + } + + /// 按播放管理器约定返回 44100 Hz 工程帧数乘四的字节位置。 + public long GetPosition() + { + lock (syncRoot) + { + return (long)(consumedFrames * 44100 / BrowserAudioInterop.SampleRate) * sizeof(float); + } + } + + /// 唤醒并结束生产线程,释放缓冲;不在浏览器主线程等待线程退出。 + public void Dispose() + { + lock (syncRoot) + { + if (disposed) return; + ResetLocked(); + sampleProvider = null; + ScheduleSynchronizationLocked(); + disposed = true; + Monitor.PulseAll(syncRoot); + } + } + + /// 清空本代输入与队列,调用者须持有状态锁。 + private void ResetLocked() + { + generation = Interlocked.Increment(ref nextGeneration); + requestedState = 0; + playbackState = PlaybackState.Stopped; + inputEnded = false; + consumedFrames = transportLatency = 0; + queuedSamples = 0; + while (blocks.TryDequeue(out AudioBlock block)) ArrayPool.Shared.Return(block.Samples); + } + + /// 合并控制请求,主线程始终应用最新的播放意图。 + private void ScheduleSynchronizationLocked() + { + if (synchronizationPosted) return; + synchronizationPosted = true; + Dispatcher.UIThread.Post(SynchronizeTransport); + } + + /// 不持有状态锁调用 JS,防止浏览器回调与后台生产相互等待。 + private void SynchronizeTransport() + { + int version, state; + lock (syncRoot) + { + synchronizationPosted = false; + version = generation; + state = requestedState; + } + try + { + BrowserAudioInterop.SetPlayback(version, state); + Pump(version); + } + catch (Exception exception) { Fail(version, exception, synchronize: false); } + if (disposed) Interlocked.CompareExchange(ref active, null, this); + } + + /// 在后台读取采样源;任何时刻最多保留两块尚未传输的音频。 + private void ProduceSamples() + { + while (true) + { + int version; + ISampleProvider provider; + lock (syncRoot) + { + while (!disposed && (requestedState != 1 || inputEnded || blocks.Count >= QueueBlockCount)) + Monitor.Wait(syncRoot); + if (disposed) return; + version = generation; + provider = sampleProvider!; + } + float[] samples = ArrayPool.Shared.Rent(BlockSamples); + try + { + int count = provider.Read(samples, 0, BlockSamples); + lock (syncRoot) + { + if (!disposed && version == generation) + { + if (count > 0) + { + blocks.Enqueue(new AudioBlock(samples, count)); + queuedSamples += count; + samples = null!; + } + else inputEnded = true; + if (!pumpPosted) + { + pumpPosted = true; + Dispatcher.UIThread.Post(PumpCurrentGeneration); + } + } + } + } + catch (Exception exception) { Fail(version, exception); } + finally { if (samples != null) ArrayPool.Shared.Return(samples); } + } + } + + /// 处理生产线程合并投递的数据通知。 + private void PumpCurrentGeneration() + { + int version; + lock (syncRoot) { pumpPosted = false; version = generation; } + Pump(version); + } + + /// 每次仅批量搬运有空位的样本,不在音频回调中等待后台线程。 + internal void Pump(int version) + { + try + { + for (int batch = 0; batch < 4; batch++) + { + int writable = BrowserAudioInterop.WritableFrames(version); + AudioBlock block; + bool ended; + lock (syncRoot) + { + if (disposed || version != generation || requestedState != 1) return; + ended = inputEnded && blocks.Count == 0; + if (!blocks.TryPeek(out block)) + { + if (!ended) return; + } + else + { + if (writable < block.Count / Channels) return; + blocks.Dequeue(); + queuedSamples -= block.Count; + Monitor.PulseAll(syncRoot); + } + } + if (ended) { BrowserAudioInterop.EndInput(version); return; } + try + { + Buffer.BlockCopy(block.Samples, 0, transferBuffer, 0, block.Count * sizeof(float)); + BrowserAudioInterop.WriteSamples(version, transferBuffer, block.Count); + } + finally { ArrayPool.Shared.Return(block.Samples); } + } + } + catch (Exception exception) { Fail(version, exception); } + } + + /// 只接受本代消费时钟,输入结束须等浏览器排空后才进入停止状态。 + internal void UpdateStatus(int version, double frames, int state, double latency) + { + lock (syncRoot) + { + if (version != generation || disposed) return; + if (state == 3) + { + ResetLocked(); + sampleProvider = null; + return; + } + consumedFrames = Math.Max(consumedFrames, frames); + transportLatency = latency; + playbackState = requestedState == 0 ? PlaybackState.Stopped + : state == 1 && requestedState == 1 ? PlaybackState.Playing : PlaybackState.Paused; + if (state == 0 && inputEnded && blocks.Count == 0) + { + requestedState = 0; + playbackState = PlaybackState.Stopped; + } + } + } + + /// 采样或传输失败后停止本代播放,并回到主线程报告异常。 + private void Fail(int version, Exception exception, bool synchronize = true) + { + lock (syncRoot) + { + if (version != generation || disposed) return; + ResetLocked(); + sampleProvider = null; + if (synchronize) ScheduleSynchronizationLocked(); + } + Log.Error(exception, "浏览器音频输出失败"); + Dispatcher.UIThread.Post(() => BrowserAudioInterop.ReportError(version, exception.Message)); + } + + /// 保存池化采样块及其有效交错样本数量。 + private readonly record struct AudioBlock(float[] Samples, int Count); +} diff --git a/OpenUtauMobile.Browser/wwwroot/audio-output-buffer.js b/OpenUtauMobile.Browser/wwwroot/audio-output-buffer.js new file mode 100644 index 00000000..a3fbd62d --- /dev/null +++ b/OpenUtauMobile.Browser/wwwroot/audio-output-buffer.js @@ -0,0 +1,5 @@ +// 两个线程共同使用的队列协议;索引与计数均以立体声帧为单位。 +export const Read = 0, Write = 1, Playing = 2, Ended = 3, Consumed = 4, Requested = 5; +export const headerLength = 8; +export const capacity = 4096; +export const targetFrames = 2048; diff --git a/OpenUtauMobile.Browser/wwwroot/audio-output-worklet.js b/OpenUtauMobile.Browser/wwwroot/audio-output-worklet.js new file mode 100644 index 00000000..2f9d5644 --- /dev/null +++ b/OpenUtauMobile.Browser/wwwroot/audio-output-worklet.js @@ -0,0 +1,52 @@ +// 主线程和音频线程共用的帧队列;每一代播放使用独立内存,避免重置时覆盖旧读指针。 +import { Read, Write, Playing, Ended, Consumed, Requested, headerLength, capacity, targetFrames } from './audio-output-buffer.js'; + +class OpenUtauAudioProcessor extends AudioWorkletProcessor { + constructor() { + super(); + this.generation = 0; + this.header = null; + this.framesSinceReport = 0; + this.port.onmessage = ({ data }) => { + if (data.type === "configure") { + this.generation = data.generation; + this.header = new Int32Array(data.buffer, 0, headerLength); + this.samples = new Float32Array(data.buffer, headerLength * 4); + this.framesSinceReport = 0; + } + }; + } + + process(inputs, outputs) { + const output = outputs[0]; + if (!output?.length || !this.header || !Atomics.load(this.header, Playing)) return true; + const header = this.header; + const read = Atomics.load(header, Read) >>> 0; + const write = Atomics.load(header, Write) >>> 0; + const available = (write - read) >>> 0; + const count = Math.min(output[0].length, available); + for (let frame = 0; frame < count; frame++) { + const offset = ((read + frame) % capacity) * 2; + output[0][frame] = this.samples[offset]; + if (output[1]) output[1][frame] = this.samples[offset + 1]; + } + // 欠载补零不推进输入时钟;采样源返回的静音仍作为正常输入消费。 + Atomics.store(header, Read, (read + count) | 0); + Atomics.add(header, Consumed, count); + const remaining = available - count; + if (remaining <= targetFrames / 2 && !Atomics.exchange(header, Requested, 1)) { + this.port.postMessage({ type: "need", generation: this.generation }); + } + this.framesSinceReport += output[0].length; + if (remaining === 0 && Atomics.load(header, Ended)) { + Atomics.store(header, Playing, 0); + this.port.postMessage({ type: "ended", generation: this.generation }); + } else if (this.framesSinceReport >= sampleRate / 50) { + this.framesSinceReport = 0; + this.port.postMessage({ type: "position", generation: this.generation }); + } + return true; + } +} + +registerProcessor("openutau-audio-output", OpenUtauAudioProcessor); diff --git a/OpenUtauMobile.Browser/wwwroot/audio-output.js b/OpenUtauMobile.Browser/wwwroot/audio-output.js new file mode 100644 index 00000000..e20b5ed7 --- /dev/null +++ b/OpenUtauMobile.Browser/wwwroot/audio-output.js @@ -0,0 +1,234 @@ +// 此模块只在浏览器主线程访问 AudioContext,音频线程只消费共享帧队列。 +import { Read, Write, Playing, Ended, Consumed, Requested, headerLength, capacity, targetFrames } from './audio-output-buffer.js'; +const deviceStorageKey = "OpenUtauMobile.AudioOutput.Device"; +let context, node, header, samples; +let generation = -1, intent = 0, consumedBase = 0, lastConsumed = 0; +let onNeedData, onStatus, onError, onDeviceChanged; +let selectedId = "", selectedName = "", selectionVersion = 0; +let resumePending = null; +let failed = false; + +export async function initialize(runtime) { + const exports = await runtime.getAssemblyExports("OpenUtauMobile.Browser"); + const bridge = exports.OpenUtauMobile.Browser.Services.Audio.BrowserAudioInterop; + return initializeTransport(bridge.RequestData, bridge.UpdateStatus, bridge.ReceiveError, bridge.UpdateDevice); +} + +export async function initializeTransport(needData, status, error, deviceChanged) { + onNeedData = needData; + onStatus = status; + onError = error; + onDeviceChanged = deviceChanged; + if (!globalThis.crossOriginIsolated || typeof SharedArrayBuffer !== "function") { + throw new Error("Browser audio requires cross-origin isolation."); + } + try { + try { context = new AudioContext({ sampleRate: 44100, latencyHint: "interactive" }); } + catch (error) { + if (error.name !== "NotSupportedError") throw error; + context = new AudioContext({ latencyHint: "interactive" }); + } + await context.suspend(); + await context.audioWorklet.addModule(new URL("./audio-output-worklet.js", import.meta.url)); + node = new AudioWorkletNode(context, "openutau-audio-output", { + numberOfInputs: 0, numberOfOutputs: 1, outputChannelCount: [2] + }); + node.connect(context.destination); + node.port.onmessage = ({ data }) => { + if (data.generation !== generation) return; + if (data.type === "need") notify(onNeedData, generation); + if (data.type === "ended") intent = 0; + report(); + }; + node.onprocessorerror = () => fail(new Error("The browser audio processor stopped.")); + context.onstatechange = report; + document.addEventListener("pointerdown", unlock, true); + document.addEventListener("keydown", unlock, true); + document.addEventListener("visibilitychange", visibilityChanged); + window.addEventListener("pagehide", pageHidden); + window.addEventListener("pageshow", visibilityChanged); + navigator.mediaDevices?.addEventListener("devicechange", devicesChanged); + await restoreDevice(); + return context.sampleRate; + } catch (error) { + await dispose(); + throw error; + } +} + +export function canSelectOutput() { + return typeof context?.setSinkId === "function" + && typeof navigator.mediaDevices?.selectAudioOutput === "function"; +} + +// 在用户原始事件中恢复上下文,允许之后的后台渲染完成时直接开始播放。 +function unlock(event) { + if (event.isTrusted) resume(true); +} + +function resume(force = false) { + if (!context || context.state === "closed" || context.state === "running" || document.hidden) return; + if (force || !resumePending) { + const attempt = context.resume().catch(error => { + if (intent === 1) notify(onError, generation, error.message ?? String(error)); + }).finally(() => { + if (resumePending === attempt) resumePending = null; + report(); + }); + resumePending = attempt; + } +} + +export function setPlayback(nextGeneration, nextIntent) { + if (failed) throw new Error("Reload the page to restart the browser audio processor."); + if (nextGeneration !== generation) { + if (header) Atomics.store(header, Playing, 0); + generation = nextGeneration; + consumedBase = lastConsumed = 0; + const buffer = new SharedArrayBuffer(headerLength * 4 + capacity * 2 * 4); + header = new Int32Array(buffer, 0, headerLength); + samples = new Float32Array(buffer, headerLength * 4); + node.port.postMessage({ type: "configure", generation, buffer }); + } + intent = nextIntent; + Atomics.store(header, Playing, intent === 1 ? 1 : 0); + if (intent === 1) resume(); + report(); +} + +export function writableFrames(expectedGeneration) { + if (!header || expectedGeneration !== generation || intent !== 1) return 0; + const queued = ((Atomics.load(header, Write) >>> 0) - (Atomics.load(header, Read) >>> 0)) >>> 0; + return Math.max(0, targetFrames - queued); +} + +export function writeSamples(expectedGeneration, bytes, count) { + if (expectedGeneration !== generation || intent !== 1) return; + const data = new Float32Array(bytes.buffer, bytes.byteOffset, count); + const write = Atomics.load(header, Write) >>> 0; + for (let frame = 0; frame < count / 2; frame++) { + const offset = ((write + frame) % capacity) * 2; + samples[offset] = data[frame * 2]; + samples[offset + 1] = data[frame * 2 + 1]; + } + Atomics.store(header, Write, (write + count / 2) | 0); + Atomics.store(header, Requested, 0); + report(); +} + +export function endInput(expectedGeneration) { + if (expectedGeneration === generation) Atomics.store(header, Ended, 1); +} + +function report() { + if (!header || !onStatus) return; + const consumed = Atomics.load(header, Consumed) >>> 0; + if (consumed < lastConsumed) consumedBase += 0x100000000; + lastConsumed = consumed; + const queued = ((Atomics.load(header, Write) >>> 0) - (Atomics.load(header, Read) >>> 0)) >>> 0; + const state = failed ? 3 : intent === 0 ? 0 + : intent === 1 && context.state === "running" && (queued > 0 || consumed > 0) ? 1 : 2; + notify(onStatus, generation, consumedBase + consumed, state, latencyMilliseconds()); +} + +// .NET 多线程模式要求异步导出;通知不阻塞浏览器主线程,也不跨语言同步重入。 +function notify(callback, ...args) { + if (callback) Promise.resolve().then(() => callback(...args)).catch(error => console.error("Audio callback failed:", error)); +} + +export function latencyMilliseconds() { + if (!header) return 0; + const queued = ((Atomics.load(header, Write) >>> 0) - (Atomics.load(header, Read) >>> 0)) >>> 0; + return (queued / context.sampleRate + (context.baseLatency || 0) + (context.outputLatency || 0)) * 1000; +} + +function fail(error) { + failed = true; + intent = 0; + if (header) Atomics.store(header, Playing, 0); + notify(onError, generation, error.message ?? String(error)); + report(); +} + +function visibilityChanged() { + if (document.hidden) context?.suspend().catch(fail); + else if (intent === 1) { + if (header) Atomics.store(header, Playing, 1); + resume(); + } +} + +function pageHidden() { + if (header) Atomics.store(header, Playing, 0); + context?.suspend().catch(fail); +} + +async function restoreDevice() { + if (!canSelectOutput()) return; + let saved; + try { saved = localStorage.getItem(deviceStorageKey); } catch { return; } + if (!saved) return; + try { + const devices = await navigator.mediaDevices.enumerateDevices(); + const device = devices.find(item => item.kind === "audiooutput" && item.deviceId === saved); + if (!device) { + setDevice("", ""); + return; + } + await context.setSinkId(saved); + setDevice(saved, device.label); + } catch { + // 失效的设备或权限不妨碍默认播放,也不在启动时弹出授权窗口。 + setDevice("", ""); + } +} + +export async function selectOutput() { + if (!canSelectOutput()) return; + const version = ++selectionVersion; + // 必须在首次 await 之前请求系统选择器,以保留用户激活。 + try { + const device = await navigator.mediaDevices.selectAudioOutput(); + if (version !== selectionVersion) return; + await context.setSinkId(device.deviceId); + if (version === selectionVersion) setDevice(device.deviceId, device.label); + } catch (error) { + if (error.name !== "NotAllowedError" && error.name !== "AbortError") throw error; + } +} + +function setDevice(id, name) { + selectedId = id; + selectedName = name; + try { + if (id) localStorage.setItem(deviceStorageKey, id); + else localStorage.removeItem(deviceStorageKey); + } catch { /* 存储被禁用时,本次设备选择仍然有效。 */ } + notify(onDeviceChanged, selectedId, selectedName); +} + +async function devicesChanged() { + if (!selectedId) return; + try { + const devices = await navigator.mediaDevices.enumerateDevices(); + if (!devices.some(device => device.kind === "audiooutput" && device.deviceId === selectedId)) { + ++selectionVersion; + await context.setSinkId(""); + setDevice("", ""); + } + } catch (error) { notify(onError, generation, error.message ?? String(error)); } +} + +export async function dispose() { + intent = 0; + if (header) Atomics.store(header, Playing, 0); + document.removeEventListener("pointerdown", unlock, true); + document.removeEventListener("keydown", unlock, true); + document.removeEventListener("visibilitychange", visibilityChanged); + window.removeEventListener("pagehide", pageHidden); + window.removeEventListener("pageshow", visibilityChanged); + navigator.mediaDevices?.removeEventListener("devicechange", devicesChanged); + if (node) { node.port.onmessage = null; node.disconnect(); node.port.close(); } + if (context) { context.onstatechange = null; await context.close(); } + context = node = header = samples = null; +} diff --git a/OpenUtauMobile/ViewModels/SettingsViewModel.cs b/OpenUtauMobile/ViewModels/SettingsViewModel.cs index 2b697a96..11ded081 100644 --- a/OpenUtauMobile/ViewModels/SettingsViewModel.cs +++ b/OpenUtauMobile/ViewModels/SettingsViewModel.cs @@ -1541,7 +1541,11 @@ private static List GetAvailableAudioBackends() List backends = [new("", L.S("Settings.Audio.AutoSelect"))]; // 根据平台添加可用后端 - if (OperatingSystem.IsIOS()) + if (OperatingSystem.IsBrowser()) + { + backends.Add(new AudioBackendOption("WebAudio", "Web Audio")); + } + else if (OperatingSystem.IsIOS()) { backends.Add(new AudioBackendOption("AVAudioEngine", "AVAudioEngine")); backends.Add(new AudioBackendOption("MiniAudio", "MiniAudio")); @@ -1561,7 +1565,6 @@ private static List GetAvailableAudioBackends() { backends.Add(new AudioBackendOption("MiniAudio", "MiniAudio")); } - // Browser 目前只支持 Dummy backends.Add(new AudioBackendOption("Dummy", L.S("Settings.Audio.Dummy"))); return backends; From fb61c04282bfa45f90f22f1f8ecb2c6094b7720e Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Wed, 4 Nov 2026 17:23:47 +0800 Subject: [PATCH 16/45] =?UTF-8?q?feature:=20=E6=94=AF=E6=8C=81=E6=8F=92?= =?UTF-8?q?=E4=BB=B6=E9=80=9A=E8=BF=87webui=E9=85=8D=E7=BD=AE=EF=BC=8C?= =?UTF-8?q?=E5=B9=B6=E7=A7=BB=E9=99=A4=E6=97=A7=E7=9A=84=E5=A3=B0=E6=98=8E?= =?UTF-8?q?=E5=BC=8F=E8=AE=BE=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Discovery/SingerDiscovery.cs | 2 +- .../Installation/InstallServices.cs | 2 +- .../PluginContracts.cs | 13 +- OpenUtauMobile.Plugin.Abstractions/README.md | 4 +- .../Settings/PluginSettings.cs | 53 ----- .../Settings/PluginWebSettings.cs | 24 +++ OpenUtauMobile/Assets/Lang/Strings.en.resx | 14 +- OpenUtauMobile/Assets/Lang/Strings.ja.resx | 14 +- OpenUtauMobile/Assets/Lang/Strings.ru.resx | 14 +- OpenUtauMobile/Assets/Lang/Strings.uk.resx | 14 +- .../Assets/Lang/Strings.zh-Hans.resx | 14 +- .../Controls/PluginSettingsPanel.axaml | 17 -- .../Controls/PluginSettingsPanel.axaml.cs | 9 - OpenUtauMobile/OpenUtauMobile.csproj | 1 + .../Installation/SingerInstallController.cs | 6 +- .../SingerPlugins/PluginSettingsService.cs | 195 ------------------ .../SingerPlugins/PluginWebSettingsService.cs | 53 +++++ .../SingerPlugins/SingerDiscoveryService.cs | 2 +- .../SingerPlugins/SingerPluginRegistration.cs | 26 --- .../SingerPlugins/SingerPluginRegistry.cs | 4 +- .../SingerPlugins/SingerPluginRuntime.cs | 6 +- .../SingerPlugins/SingerPluginSnapshot.cs | 8 +- .../ViewModels/PluginCardViewModel.cs | 19 ++ .../ViewModels/PluginManagerViewModel.cs | 83 +++++++- .../ViewModels/PluginSettingsViewModel.cs | 139 ------------- .../ViewModels/PluginWebSettingsViewModel.cs | 116 +++++++++++ .../ViewModels/SettingsViewModel.Plugins.cs | 118 ----------- .../ViewModels/SettingsViewModel.cs | 6 +- .../ViewModels/TrackSettingsPopupViewModel.cs | 16 +- OpenUtauMobile/Views/PluginManagerView.axaml | 14 +- .../Views/PluginWebSettingsView.axaml | 28 +++ .../Views/PluginWebSettingsView.axaml.cs | 64 ++++++ OpenUtauMobile/Views/SettingsView.axaml | 85 +------- docs/PLUGIN_WEB_SETTINGS.md | 49 +++++ 34 files changed, 511 insertions(+), 721 deletions(-) delete mode 100644 OpenUtauMobile.Plugin.Abstractions/Settings/PluginSettings.cs create mode 100644 OpenUtauMobile.Plugin.Abstractions/Settings/PluginWebSettings.cs delete mode 100644 OpenUtauMobile/Controls/PluginSettingsPanel.axaml delete mode 100644 OpenUtauMobile/Controls/PluginSettingsPanel.axaml.cs delete mode 100644 OpenUtauMobile/Services/SingerPlugins/PluginSettingsService.cs create mode 100644 OpenUtauMobile/Services/SingerPlugins/PluginWebSettingsService.cs create mode 100644 OpenUtauMobile/ViewModels/PluginCardViewModel.cs delete mode 100644 OpenUtauMobile/ViewModels/PluginSettingsViewModel.cs create mode 100644 OpenUtauMobile/ViewModels/PluginWebSettingsViewModel.cs delete mode 100644 OpenUtauMobile/ViewModels/SettingsViewModel.Plugins.cs create mode 100644 OpenUtauMobile/Views/PluginWebSettingsView.axaml create mode 100644 OpenUtauMobile/Views/PluginWebSettingsView.axaml.cs create mode 100644 docs/PLUGIN_WEB_SETTINGS.md diff --git a/OpenUtauMobile.Plugin.Abstractions/Discovery/SingerDiscovery.cs b/OpenUtauMobile.Plugin.Abstractions/Discovery/SingerDiscovery.cs index 91d1e62b..45622314 100644 --- a/OpenUtauMobile.Plugin.Abstractions/Discovery/SingerDiscovery.cs +++ b/OpenUtauMobile.Plugin.Abstractions/Discovery/SingerDiscovery.cs @@ -38,7 +38,7 @@ public sealed record SingerDiscoveryProgress(string Message, long Completed = 0, public sealed record SingerDiscoveryContext( ImmutableArray Roots, CultureInfo Culture, - IPluginSettingsReader Settings, + PluginStorageContext Storage, IPluginLog Log); /// 执行时重新读取根目录权限,不能沿用扫描时已过期的删除授权。 diff --git a/OpenUtauMobile.Plugin.Abstractions/Installation/InstallServices.cs b/OpenUtauMobile.Plugin.Abstractions/Installation/InstallServices.cs index b1d040b9..745536f0 100644 --- a/OpenUtauMobile.Plugin.Abstractions/Installation/InstallServices.cs +++ b/OpenUtauMobile.Plugin.Abstractions/Installation/InstallServices.cs @@ -71,5 +71,5 @@ public sealed record SingerInstallContext(Guid SessionId, CultureInfo Culture, I IInstallWorkspace Workspace, ImmutableArray SingerRoots, ImmutableArray InstallTargets, string DefaultTargetId, IInstalledSingerLookup InstalledSingers, IInstallFileOperations Files, - IPluginSettingsReader Settings, IPluginLog Log); + PluginStorageContext Storage, IPluginLog Log); } diff --git a/OpenUtauMobile.Plugin.Abstractions/PluginContracts.cs b/OpenUtauMobile.Plugin.Abstractions/PluginContracts.cs index 2032c0ed..6746abde 100644 --- a/OpenUtauMobile.Plugin.Abstractions/PluginContracts.cs +++ b/OpenUtauMobile.Plugin.Abstractions/PluginContracts.cs @@ -6,7 +6,7 @@ namespace OpenUtauMobile.Plugin.Abstractions public static class SingerPluginContract { /// 当前支持的契约版本。 - public const int Version = 1; + public const int Version = 2; /// 外部类型数值的起点;数值只用于桥接,不作为位标志。 public const int ExternalTypeMinimum = 0x10000000; } @@ -34,6 +34,15 @@ public interface ISingerPlugin SingerPluginDescriptor Descriptor { get; } /// 提交本插件的能力描述;宿主验证全部登记后统一发布。 void Register(ISingerPluginRegistrar registrar); + + /// 运行时动态查询 Web 设置能力;必须无副作用,不在查询时启动服务。 + ValueTask GetWebSettingsAsync(PluginWebSettingsContext context, + CancellationToken cancellationToken) => ValueTask.FromResult(null); + + /// 用户点击设置后创建网页会话;服务生命周期由返回对象管理。 + ValueTask OpenWebSettingsAsync(PluginWebSettingsContext context, + CancellationToken cancellationToken) => ValueTask.FromException( + new NotSupportedException("当前插件没有 Web 设置。")); } /// 宿主收集插件本轮登记,不向插件公开宿主服务容器。 @@ -45,7 +54,5 @@ public interface ISingerPluginRegistrar void RegisterProvider(ISingerProvider provider); /// 登记由用户手选的文件安装器,不自动探测包内容。 void RegisterInstaller(ISingerPackageInstaller installer); - /// 登记设置描述和设置操作处理器。 - void RegisterSettings(IPluginSettingsHandler settings); } } diff --git a/OpenUtauMobile.Plugin.Abstractions/README.md b/OpenUtauMobile.Plugin.Abstractions/README.md index 71bd70f7..c372e9fd 100644 --- a/OpenUtauMobile.Plugin.Abstractions/README.md +++ b/OpenUtauMobile.Plugin.Abstractions/README.md @@ -1,8 +1,8 @@ -# 歌手插件契约 v1 +# 歌手插件契约 v2 插件引用本程序集与 `OpenUtau.Core` 时设置 `Private="false"`,安装包只携带插件自身文件。 -使用 `[assembly: SingerPlugin(typeof(PluginEntry))]` 声明实现 `ISingerPlugin` 的公开无参入口。在 `Register` 内同步登记类型、发现提供方、安装器和设置,不执行扫描或安装。 +使用 `[assembly: SingerPlugin(typeof(PluginEntry))]` 声明实现 `ISingerPlugin` 的公开无参入口。在 `Register` 内同步登记类型、发现提供方和安装器,不执行扫描或安装。设置通过运行时 WebUI 会话提供,详见 [Web 设置契约](../docs/PLUGIN_WEB_SETTINGS.md)。 - 插件 ID 使用小写字母开头,允许数字、点、下划线和短横线;`opum.` 为保留前缀。能力 ID 使用 `:<名称>`。 - 类型桥接值固定在 `0x10000000` 至 `int.MaxValue` 内,宿主检查冲突。 diff --git a/OpenUtauMobile.Plugin.Abstractions/Settings/PluginSettings.cs b/OpenUtauMobile.Plugin.Abstractions/Settings/PluginSettings.cs deleted file mode 100644 index 707ec8ae..00000000 --- a/OpenUtauMobile.Plugin.Abstractions/Settings/PluginSettings.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System.Collections.Immutable; - -namespace OpenUtauMobile.Plugin.Abstractions -{ - /// 设置成功保存后的实际生效方式。 - public enum PluginSettingApplication - { - Immediate, - ReloadResources, - Restart, - } - - /// 设置字段及其生效策略,与临时安装输入分离。 - public sealed record PluginSettingDescriptor(PluginFieldDescriptor Field, - PluginSettingApplication Application = PluginSettingApplication.Restart); - - /// 插件设置描述,配置按插件隔离并携带数据版本。 - public sealed record PluginSettingsDescriptor(int SchemaVersion, string DisplayName, - ImmutableArray Fields); - - /// 只读设置快照,安装及发现不能借此改动全局配置。 - public interface IPluginSettingsReader - { - /// 该插件独占的资源目录,原生代码只接收这里或选择器返回的真实路径。 - string ResourceDirectory => ""; - /// 已保存配置的数据版本。 - int SchemaVersion { get; } - /// 获取当前插件的类型化设置。 - bool TryGet(string key, out PluginValue? value); - } - - /// 设置保存的校验结果。 - public sealed record PluginSettingsValidation(ImmutableArray Diagnostics) - { - /// 存在错误时宿主不能提交草稿。 - public bool IsValid => Diagnostics.IsDefaultOrEmpty || Diagnostics.All(item => item.Severity != PluginDiagnosticSeverity.Error); - } - - /// 插件声明设置并负责校验,宿主负责呈现与持久化。 - public interface IPluginSettingsHandler - { - /// 设置分组与字段。 - PluginSettingsDescriptor Descriptor { get; } - /// 接收本进程实际生效的快照;重启生效的字段在保存时不会提前应用。 - void Apply(IPluginSettingsReader settings) { } - /// 保存前校验完整草稿,实际持久化由宿主完成。 - ValueTask ValidateAsync(ImmutableDictionary values, - CancellationToken cancellationToken); - /// 将旧数据转换到当前版本,保留需要延续的未知字段。 - ImmutableDictionary Upgrade(int previousVersion, - ImmutableDictionary values); - } -} diff --git a/OpenUtauMobile.Plugin.Abstractions/Settings/PluginWebSettings.cs b/OpenUtauMobile.Plugin.Abstractions/Settings/PluginWebSettings.cs new file mode 100644 index 00000000..a064aa41 --- /dev/null +++ b/OpenUtauMobile.Plugin.Abstractions/Settings/PluginWebSettings.cs @@ -0,0 +1,24 @@ +namespace OpenUtauMobile.Plugin.Abstractions +{ + /// 插件独占的持久化目录,配置格式和迁移由插件自己管理。 + public sealed record PluginStorageContext(string DataDirectory) + { + /// 插件资源目录,与旧版资源位置保持一致。 + public string ResourceDirectory => Path.Combine(DataDirectory, "Resources"); + } + + /// 每次查询和打开设置时提供的宿主上下文。 + public sealed record PluginWebSettingsContext(PluginStorageContext Storage, IPluginLog Log); + + /// 当前可用的 Web 设置声明;查询返回 null 表示此刻没有设置入口。 + public sealed record PluginWebSettingsDescriptor(string Title); + + /// 插件创建的网页会话;宿主离开页面时等待释放本地服务等资源。 + public interface IPluginWebSettingsSession : IAsyncDisposable + { + /// 可由系统 WebView 或外部浏览器打开的 HTTP/HTTPS 地址。 + Uri Address { get; } + /// 关闭设置后是否重新发现歌手,默认刷新。 + bool ReloadResourcesOnClose => true; + } +} diff --git a/OpenUtauMobile/Assets/Lang/Strings.en.resx b/OpenUtauMobile/Assets/Lang/Strings.en.resx index 03a79a0b..1dbb8d34 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.en.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.en.resx @@ -2623,13 +2623,13 @@ Applying replaces the source of this input. Voicebank version Reading metadata… Could not parse metadata - Plugin settings - No plugin is being configured. - Saved. Restart to apply. - Saved. - Processing. Please wait. Singer not found. Check plugins and singer folders. Ready - Plugins - Not selected + Plugin settings + Open in system browser + Web settings are currently unavailable. + The plugin returned an invalid web address. + Could not open plugin settings. + Could not open the system browser. + The system WebView could not load this page. Use the top-right button to open it in your browser. diff --git a/OpenUtauMobile/Assets/Lang/Strings.ja.resx b/OpenUtauMobile/Assets/Lang/Strings.ja.resx index 04587399..2aea4a9e 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.ja.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.ja.resx @@ -2619,13 +2619,13 @@ Applying replaces the source of this input. 音源バージョン メタデータを読み込み中… メタデータを解析できませんでした - プラグイン設定 - 設定中のプラグインはありません。 - 保存しました。再起動後に適用されます。 - 保存しました。 - 処理中です。しばらくお待ちください。 シンガーが見つかりません。プラグインとフォルダーを確認してください。 利用可能 - プラグイン - 未選択 + プラグイン設定 + システムブラウザーで開く + 現在、Web 設定は利用できません。 + プラグインの Web アドレスが無効です。 + プラグイン設定を開けませんでした。 + システムブラウザーを開けませんでした。 + システム WebView で読み込めません。右上のボタンからブラウザーで開いてください。 diff --git a/OpenUtauMobile/Assets/Lang/Strings.ru.resx b/OpenUtauMobile/Assets/Lang/Strings.ru.resx index eb7e1be9..785fbee3 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.ru.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.ru.resx @@ -2578,13 +2578,13 @@ Applying replaces the source of this input. Версия голосового банка Чтение метаданных… Не удалось прочитать метаданные - Настройки плагинов - Ни один плагин не выбран для настройки. - Сохранено. Перезапустите приложение. - Сохранено. - Обработка. Подождите. Певец не найден. Проверьте плагины и папки певцов. Готов - Плагины - Не выбрано + Настройки плагина + Открыть в системном браузере + Веб-настройки сейчас недоступны. + Плагин вернул недопустимый веб-адрес. + Не удалось открыть настройки плагина. + Не удалось открыть системный браузер. + Системный WebView не смог загрузить страницу. Откройте её в браузере кнопкой справа вверху. diff --git a/OpenUtauMobile/Assets/Lang/Strings.uk.resx b/OpenUtauMobile/Assets/Lang/Strings.uk.resx index a8ff9033..c08f3538 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.uk.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.uk.resx @@ -2578,13 +2578,13 @@ Applying replaces the source of this input. Версія голосового банку Читання метаданих… Не вдалося прочитати метадані - Налаштування плагінів - Жоден плагін не вибрано для налаштування. - Збережено. Перезапустіть застосунок. - Збережено. - Обробка. Зачекайте. Співака не знайдено. Перевірте плагіни та папки співаків. Готовий - Плагіни - Не вибрано + Налаштування плагіна + Відкрити в системному браузері + Вебналаштування зараз недоступні. + Плагін повернув недійсну вебадресу. + Не вдалося відкрити налаштування плагіна. + Не вдалося відкрити системний браузер. + Системний WebView не завантажив сторінку. Відкрийте її у браузері кнопкою праворуч угорі. diff --git a/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx b/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx index 6da506f8..e2b3aacf 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx @@ -2623,13 +2623,13 @@ 声库版本 正在读取元数据… 未能解析元数据 - 插件设置 - 没有正在配置的插件。 - 已保存,重启后生效。 - 已保存。 - 正在处理,请稍候。 找不到歌手,请检查插件和歌手目录。 可用 - 插件 - 未选择 + 插件设置 + 在系统浏览器打开 + 当前插件没有可用的网页设置。 + 插件返回了无效的网页地址。 + 无法打开插件设置。 + 无法打开系统浏览器。 + 系统 WebView 无法加载页面,可使用右上角按钮在系统浏览器打开。 diff --git a/OpenUtauMobile/Controls/PluginSettingsPanel.axaml b/OpenUtauMobile/Controls/PluginSettingsPanel.axaml deleted file mode 100644 index e9defa7d..00000000 --- a/OpenUtauMobile/Controls/PluginSettingsPanel.axaml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - diff --git a/OpenUtauMobile/Controls/PluginSettingsPanel.axaml.cs b/OpenUtauMobile/Controls/PluginSettingsPanel.axaml.cs deleted file mode 100644 index b72812d2..00000000 --- a/OpenUtauMobile/Controls/PluginSettingsPanel.axaml.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Avalonia.Controls; - -namespace OpenUtauMobile.Controls; - -/// 设置页内的插件字段区域,不提供独立导航。 -public partial class PluginSettingsPanel : UserControl -{ - public PluginSettingsPanel() => InitializeComponent(); -} diff --git a/OpenUtauMobile/OpenUtauMobile.csproj b/OpenUtauMobile/OpenUtauMobile.csproj index 94f9a24d..e9a80fc4 100644 --- a/OpenUtauMobile/OpenUtauMobile.csproj +++ b/OpenUtauMobile/OpenUtauMobile.csproj @@ -28,6 +28,7 @@ + diff --git a/OpenUtauMobile/Services/SingerPlugins/Installation/SingerInstallController.cs b/OpenUtauMobile/Services/SingerPlugins/Installation/SingerInstallController.cs index df7b6385..6e54b4d7 100644 --- a/OpenUtauMobile/Services/SingerPlugins/Installation/SingerInstallController.cs +++ b/OpenUtauMobile/Services/SingerPlugins/Installation/SingerInstallController.cs @@ -43,13 +43,13 @@ public SingerInstallController(RegisteredSingerInstaller installer, string sourc PathManager.Inst.SingersInstallPath)]; string fullSource = Path.GetFullPath(sourcePath); ImmutableArray roots = SingerPluginRuntime.Roots(); - // 设置读取或应用失败时尚未创建会话,避免构造失败遗留临时目录。 - IPluginSettingsReader settings = SingerPluginRuntime.Settings(installer.PluginId); + // 只提供插件目录,配置格式和兼容性由插件负责。 + PluginStorageContext storage = SingerPluginRuntime.Storage(installer.PluginId); InstallWorkspace workspace = new(PathManager.Inst.CachePath, id); files = new(workspace, targets, id); context = new(id, CultureInfo.CurrentUICulture, new InstallSource(fullSource, workspace), workspace, roots, targets, targets[0].Id, new InstalledLookup(), files, - settings, new SingerPluginRuntime.PluginLog(installer.PluginId)); + storage, new SingerPluginRuntime.PluginLog(installer.PluginId)); } /// 创建失败与分析失败均等待释放插件句柄,再清理缓存。 diff --git a/OpenUtauMobile/Services/SingerPlugins/PluginSettingsService.cs b/OpenUtauMobile/Services/SingerPlugins/PluginSettingsService.cs deleted file mode 100644 index e7ef64a7..00000000 --- a/OpenUtauMobile/Services/SingerPlugins/PluginSettingsService.cs +++ /dev/null @@ -1,195 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.IO; -using System.Linq; -using System.Security.Cryptography; -using System.Text; -using System.Text.Json; -using System.Text.Json.Nodes; -using System.Threading; -using System.Threading.Tasks; -using OpenUtau.Core; -using OpenUtauMobile.Plugin.Abstractions; - -namespace OpenUtauMobile.Services.SingerPlugins -{ - /// 校验错误携带字段定位,不允许失败的草稿覆盖原设置。 - public sealed class PluginSettingsValidationException(ImmutableArray diagnostics) - : Exception(string.Join("\n", diagnostics.Select(item => item.Message))) - { - public ImmutableArray Diagnostics { get; } = diagnostics; - } - - /// 按插件隔离版本化配置;保留未知 JSON 字段,原子提交并检测并发编辑。 - public static class PluginSettingsService - { - private static readonly ConcurrentDictionary effective = new(StringComparer.Ordinal); - private static readonly ConcurrentDictionary gates = new(StringComparer.Ordinal); - private static readonly JsonSerializerOptions json = new() { WriteIndented = true }; - - /// 插件标识通过散列映射目录,不能成为宿主路径的一部分。 - public static string DirectoryFor(string pluginId) => Path.Combine(PathManager.Inst.DataPath, "PluginData", - Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(pluginId))).ToLowerInvariant()); - - /// 首次使用固定当前有效值;保存 Restart 字段不改变此快照。 - public static IPluginSettingsReader Effective(string pluginId) - { - string directory = DirectoryFor(pluginId); - lock (effective) - { - if (effective.TryGetValue(directory, out Snapshot? cached)) return cached; - RegisteredPluginSettings? registration = SingerPluginService.Registry.Snapshot.Settings.GetValueOrDefault(pluginId); - Snapshot snapshot = registration == null ? new(0, Path.Combine(directory, "Resources"), ImmutableDictionary.Empty) - : Read(registration).Snapshot; - registration?.Instance.Apply(snapshot); - effective[directory] = snapshot; - return snapshot; - } - } - - /// 打开独立草稿,损坏或未来版本配置只报错,不回退成可覆盖的空配置。 - public static PluginSettingsSession Open(RegisteredPluginSettings registration) - { - _ = Effective(registration.PluginId); - Document document = Read(registration); - return new(registration, document.Snapshot.Values, document.Fingerprint); - } - - /// 读取时只解释已知的类型化值,未来字段的原始节点保留在文档内。 - private static Document Read(RegisteredPluginSettings registration) - { - string directory = DirectoryFor(registration.PluginId); - string path = Path.Combine(directory, "settings.json"); - bool exists = File.Exists(path); - if (exists && new FileInfo(path).Length is 0 or > 1024 * 1024) throw new InvalidDataException("插件设置文件为空或过大。"); - byte[] bytes = exists ? File.ReadAllBytes(path) : []; - JsonObject root = bytes.Length == 0 ? new() : JsonNode.Parse(bytes)?.AsObject() - ?? throw new InvalidDataException("插件设置为空。"); - int version = root["schemaVersion"]?.GetValue() ?? (bytes.Length == 0 ? registration.Descriptor.SchemaVersion : 0); - if (version < 1 || version > registration.Descriptor.SchemaVersion) - throw new InvalidDataException($"不支持插件设置版本 {version},文件未修改:{path}"); - JsonObject raw = root["values"] is JsonObject values ? values : bytes.Length == 0 ? new() - : throw new InvalidDataException("插件设置缺少 values 对象。"); - ImmutableDictionary.Builder parsed = ImmutableDictionary.CreateBuilder(StringComparer.Ordinal); - foreach (PluginSettingDescriptor field in registration.Descriptor.Fields) - { - if (raw.TryGetPropertyValue(field.Field.Id, out JsonNode? node)) - parsed[field.Field.Id] = node?.Deserialize() ?? throw new InvalidDataException($"设置 {field.Field.Id} 为空。"); - else if (field.Field.DefaultValue is { } fallback) parsed[field.Field.Id] = fallback; - } - // 旧版本转换可读取可识别的未知值;无法识别的扩展数据始终按原样保留。 - foreach ((string key, JsonNode? node) in raw) - { - if (parsed.ContainsKey(key)) continue; - try { if (node?.Deserialize() is { } value) parsed[key] = value; } - catch (JsonException) { } - } - ImmutableDictionary result = parsed.ToImmutable(); - if (version < registration.Descriptor.SchemaVersion) result = registration.Instance.Upgrade(version, result); - ValidateFields(registration.Descriptor.Fields.Select(field => field.Field).Where(field => result.ContainsKey(field.Id)), result); - return new(root, raw, Convert.ToHexString(SHA256.HashData(bytes)), - new(registration.Descriptor.SchemaVersion, Path.Combine(directory, "Resources"), result)); - } - - /// 同一插件的保存互斥,过期会话必须重新打开。 - internal static async Task SaveAsync(PluginSettingsSession session, ImmutableDictionary values, - CancellationToken cancellationToken) - { - SemaphoreSlim gate = gates.GetOrAdd(DirectoryFor(session.Registration.PluginId), _ => new(1, 1)); - await gate.WaitAsync(cancellationToken); - try { await CommitAsync(session, values, cancellationToken); } - finally { gate.Release(); } - } - - private static async Task CommitAsync(PluginSettingsSession session, ImmutableDictionary values, - CancellationToken cancellationToken) - { - RegisteredPluginSettings registration = session.Registration; - Document current = Read(registration); - if (current.Fingerprint != session.Fingerprint) throw new IOException("插件设置已改变,请重新打开设置页面。"); - ValidateFields(registration.Descriptor.Fields.Select(field => field.Field), values); - PluginSettingsValidation validation = await registration.Instance.ValidateAsync(values, cancellationToken); - if (!validation.IsValid) throw new PluginSettingsValidationException(validation.Diagnostics); - JsonObject raw = (JsonObject)current.Raw.DeepClone(); - foreach ((string key, PluginValue value) in values) - if (!raw.ContainsKey(key) || registration.Descriptor.Fields.Any(field => field.Field.Id == key)) - raw[key] = JsonSerializer.SerializeToNode(value, json); - current.Root["values"] = raw; - current.Root["schemaVersion"] = registration.Descriptor.SchemaVersion; - string directory = DirectoryFor(registration.PluginId); - Directory.CreateDirectory(directory); - string path = Path.Combine(directory, "settings.json"); - string temporary = Path.Combine(directory, Guid.NewGuid().ToString("N") + ".tmp"); - byte[] bytes = JsonSerializer.SerializeToUtf8Bytes(current.Root, json); - try - { - await File.WriteAllBytesAsync(temporary, bytes, cancellationToken); - cancellationToken.ThrowIfCancellationRequested(); - File.Move(temporary, path, true); - } - finally { if (File.Exists(temporary)) File.Delete(temporary); } - session.Accept(values, Convert.ToHexString(SHA256.HashData(bytes))); - lock (effective) - { - Snapshot previous = effective[directory]; - ImmutableDictionary applied = previous.Values; - foreach (PluginSettingDescriptor field in registration.Descriptor.Fields) - if (field.Application != PluginSettingApplication.Restart && values.TryGetValue(field.Field.Id, out PluginValue? value)) - applied = applied.SetItem(field.Field.Id, value); - Snapshot updated = previous with { Values = applied }; - registration.Instance.Apply(updated); - effective[directory] = updated; - } - } - - /// 在插件回调前统一校验类型、必填、数值范围与选项,不默默修复损坏的保存值。 - private static void ValidateFields(IEnumerable fields, ImmutableDictionary values) - { - List diagnostics = []; - foreach (PluginFieldDescriptor field in fields) - { - values.TryGetValue(field.Id, out PluginValue? value); - bool valid = value == null ? !field.IsRequired : field.Kind switch - { - PluginFieldKind.Text => value is PluginValue.Text text && (!field.IsRequired || !string.IsNullOrWhiteSpace(text.Value)), - PluginFieldKind.Boolean => value is PluginValue.Boolean boolean && (!field.IsRequired || boolean.Value), - PluginFieldKind.Number => value is PluginValue.Number number && !(number.Value < field.Minimum || number.Value > field.Maximum), - PluginFieldKind.Selection => value is PluginValue.Selection selection && - ((!field.IsRequired && string.IsNullOrEmpty(selection.Value)) || (!field.Options.IsDefault && field.Options.Any(option => option.Id == selection.Value))), - PluginFieldKind.MultipleSelection => value is PluginValue.MultipleSelection multiple && - (!field.IsRequired || !multiple.Values.IsDefaultOrEmpty) && (multiple.Values.IsDefaultOrEmpty || - (!field.Options.IsDefault && multiple.Values.All(id => field.Options.Any(option => option.Id == id)))), - PluginFieldKind.File or PluginFieldKind.Directory => value is PluginValue.Path path && - path.IsDirectory == (field.Kind == PluginFieldKind.Directory) && (!field.IsRequired || !string.IsNullOrWhiteSpace(path.Value)), - _ => false, - }; - if (!valid) diagnostics.Add(new("settings.invalid-field", $"{field.Label}:无效的设置值。", FieldId: field.Id)); - } - if (diagnostics.Count > 0) throw new PluginSettingsValidationException([.. diagnostics]); - } - - private sealed record Snapshot(int SchemaVersion, string ResourceDirectory, - ImmutableDictionary Values) : IPluginSettingsReader - { - public bool TryGet(string key, out PluginValue? value) => Values.TryGetValue(key, out value); - } - private sealed record Document(JsonObject Root, JsonObject Raw, string Fingerprint, Snapshot Snapshot); - } - - /// 页面持有的独立编辑会话;保留未展示的字段与读取版本。 - public sealed class PluginSettingsSession - { - internal RegisteredPluginSettings Registration { get; } - internal string Fingerprint { get; private set; } - public ImmutableDictionary Values { get; private set; } - internal PluginSettingsSession(RegisteredPluginSettings registration, ImmutableDictionary values, string fingerprint) - { Registration = registration; Values = values; Fingerprint = fingerprint; } - internal void Accept(ImmutableDictionary values, string fingerprint) - { Values = values; Fingerprint = fingerprint; } - /// 后台执行完整校验及原子保存。 - public Task SaveAsync(ImmutableDictionary values, CancellationToken cancellationToken = default) => - Task.Run(() => PluginSettingsService.SaveAsync(this, values, cancellationToken), cancellationToken); - } -} diff --git a/OpenUtauMobile/Services/SingerPlugins/PluginWebSettingsService.cs b/OpenUtauMobile/Services/SingerPlugins/PluginWebSettingsService.cs new file mode 100644 index 00000000..45a10e63 --- /dev/null +++ b/OpenUtauMobile/Services/SingerPlugins/PluginWebSettingsService.cs @@ -0,0 +1,53 @@ +using System; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using OpenUtau.Core; +using OpenUtauMobile.Plugin.Abstractions; + +namespace OpenUtauMobile.Services.SingerPlugins; + +/// 按插件隔离存储;只在用户打开页面时创建插件网页会话。 +public static class PluginWebSettingsService +{ + /// 保持已有插件目录映射,不读取或改写旧设置文件。 + public static PluginStorageContext Storage(string pluginId) => new(Path.Combine(PathManager.Inst.DataPath, + "PluginData", Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(pluginId))).ToLowerInvariant())); + + /// 映射已成功登记的插件,不加载未激活的 DLL。 + public static RegisteredSingerPlugin? FindPlugin(string relativePath) + { + string path = Path.GetFullPath(Path.Combine(PathManager.Inst.PluginsPath, relativePath)); + StringComparison comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + return SingerPluginService.Registry.Snapshot.Instances.Values.FirstOrDefault(plugin => + !plugin.Assembly.IsDynamic && string.Equals(Path.GetFullPath(plugin.Assembly.Location), path, comparison)); + } + + private static PluginWebSettingsContext Context(string pluginId) => new(Storage(pluginId), new SingerPluginRuntime.PluginLog(pluginId)); + + /// 查询当前声明,不缓存登记时的能力状态。 + public static ValueTask QueryAsync(RegisteredSingerPlugin plugin, CancellationToken token) => + plugin.Instance.GetWebSettingsAsync(Context(plugin.PluginId), token); + + /// 再次查询后打开,处理查询与点击之间能力改变的情况。 + public static async Task OpenAsync(RegisteredSingerPlugin plugin, CancellationToken token) + { + PluginWebSettingsContext context = Context(plugin.PluginId); + if (await plugin.Instance.GetWebSettingsAsync(context, token) == null) + throw new InvalidOperationException(Helpers.L.S("PluginWebSettings.Unavailable")); + Directory.CreateDirectory(context.Storage.DataDirectory); + IPluginWebSettingsSession session = await plugin.Instance.OpenWebSettingsAsync(context, token); + try + { + token.ThrowIfCancellationRequested(); + if (session.Address is not { IsAbsoluteUri: true } address || + (address.Scheme != Uri.UriSchemeHttp && address.Scheme != Uri.UriSchemeHttps)) + throw new InvalidOperationException(Helpers.L.S("PluginWebSettings.InvalidAddress")); + return session; + } + catch { await session.DisposeAsync(); throw; } + } +} diff --git a/OpenUtauMobile/Services/SingerPlugins/SingerDiscoveryService.cs b/OpenUtauMobile/Services/SingerPlugins/SingerDiscoveryService.cs index d211d492..6e0c52ca 100644 --- a/OpenUtauMobile/Services/SingerPlugins/SingerDiscoveryService.cs +++ b/OpenUtauMobile/Services/SingerPlugins/SingerDiscoveryService.cs @@ -96,7 +96,7 @@ public async Task RefreshAsync(CancellationToken cancellationToken = default, bo CultureInfo culture = CultureInfo.CurrentUICulture; SingerDiscoveryResult result = await Task.Run(async () => { - SingerDiscoveryContext context = new(roots, culture, SingerPluginRuntime.Settings(provider.PluginId), log); + SingerDiscoveryContext context = new(roots, culture, SingerPluginRuntime.Storage(provider.PluginId), log); return await provider.Instance.DiscoverAsync(context, new Progress(), cancellationToken); }, cancellationToken); foreach (PluginDiagnostic diagnostic in result.Diagnostics.IsDefault ? [] : result.Diagnostics) diff --git a/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistration.cs b/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistration.cs index 8f8fe186..8e320e58 100644 --- a/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistration.cs +++ b/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistration.cs @@ -23,7 +23,6 @@ internal sealed class SingerPluginRegistration : ISingerPluginRegistrar internal IReadOnlyCollection Types => types.Values; internal IReadOnlyCollection Providers => providers.Values; internal IReadOnlyCollection Installers => installers.Values; - internal RegisteredPluginSettings? Settings { get; private set; } internal SingerPluginRegistration(SingerPluginDescriptor plugin, Assembly assembly) { @@ -97,31 +96,6 @@ public void RegisterInstaller(ISingerPackageInstaller installer) Add(installers, descriptor.Id, new(plugin.Id, descriptor, installer)); } - /// 每个插件登记一个设置分组;描述中没有任意控件或脚本。 - public void RegisterSettings(IPluginSettingsHandler settings) - { - RequireOpen(); - ArgumentNullException.ThrowIfNull(settings); - if (Settings != null) - { - throw new InvalidOperationException("同一插件只能登记一个设置分组。"); - } - PluginSettingsDescriptor descriptor = settings.Descriptor - ?? throw new InvalidOperationException("设置缺少描述。"); - RequireText(descriptor.DisplayName, "设置名称"); - if (descriptor.SchemaVersion < 1) - { - throw new InvalidOperationException("设置数据版本必须为正整数。"); - } - ImmutableArray fields = OrEmpty(descriptor.Fields); - ValidateFields(fields.Select(field => field.Field)); - if (fields.Any(field => !Enum.IsDefined(field.Application))) - { - throw new InvalidOperationException("设置包含未知生效方式。"); - } - Settings = new(plugin.Id, descriptor with { Fields = fields }, settings); - } - internal void Close() => closed = true; /// 校验整批引用与工厂;允许先登记提供方再登记类型。 diff --git a/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistry.cs b/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistry.cs index 1353cc66..cec3d475 100644 --- a/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistry.cs +++ b/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistry.cs @@ -60,7 +60,7 @@ internal void Register(ISingerPlugin plugin, Assembly assembly) current.TypesByBridge.AddRange(batch.Types.Select(type => new KeyValuePair(type.Descriptor.BridgeValue, type))), current.Providers.AddRange(batch.Providers.Select(provider => new KeyValuePair(provider.Id, provider))), current.Installers.AddRange(batch.Installers.Select(installer => new KeyValuePair(installer.Descriptor.Id, installer))), - batch.Settings is { } settings ? current.Settings.Add(descriptor.Id, settings) : current.Settings); + current.Instances.Add(descriptor.Id, new(descriptor.Id, assembly, plugin))); Volatile.Write(ref snapshot, next); } } @@ -119,7 +119,7 @@ private static SingerPluginSnapshot CreateBuiltinSnapshot() types.ToImmutableDictionary(type => type.Descriptor.BridgeValue), ImmutableDictionary.Empty.WithComparers(StringComparer.Ordinal), ImmutableDictionary.Empty.WithComparers(StringComparer.Ordinal), - ImmutableDictionary.Empty.WithComparers(StringComparer.Ordinal)); + ImmutableDictionary.Empty.WithComparers(StringComparer.Ordinal)); } } } diff --git a/OpenUtauMobile/Services/SingerPlugins/SingerPluginRuntime.cs b/OpenUtauMobile/Services/SingerPlugins/SingerPluginRuntime.cs index 47ec1149..4abfb7e1 100644 --- a/OpenUtauMobile/Services/SingerPlugins/SingerPluginRuntime.cs +++ b/OpenUtauMobile/Services/SingerPlugins/SingerPluginRuntime.cs @@ -17,9 +17,9 @@ internal static ImmutableArray Roots() => PathManager.Inst.SingersPa string.Equals(Path.GetFullPath(path), Path.GetFullPath(PathManager.Inst.SingersInstallPath), Installation.InstallPaths.Comparison))).ToImmutableArray(); - /// 向发现和安装提供本进程已生效的只读设置。 - internal static IPluginSettingsReader Settings(string pluginId) => - PluginSettingsService.Effective(pluginId); + /// 发现和安装提供方使用插件独占目录,自行读取持久化配置。 + internal static PluginStorageContext Storage(string pluginId) => + PluginWebSettingsService.Storage(pluginId); /// 将契约诊断写入宿主日志。 internal sealed class PluginLog(string pluginId) : IPluginLog diff --git a/OpenUtauMobile/Services/SingerPlugins/SingerPluginSnapshot.cs b/OpenUtauMobile/Services/SingerPlugins/SingerPluginSnapshot.cs index 06657fa9..0db762aa 100644 --- a/OpenUtauMobile/Services/SingerPlugins/SingerPluginSnapshot.cs +++ b/OpenUtauMobile/Services/SingerPlugins/SingerPluginSnapshot.cs @@ -15,9 +15,9 @@ public sealed record RegisteredSingerProvider(string PluginId, string Id, public sealed record RegisteredSingerInstaller(string PluginId, SingerInstallerDescriptor Descriptor, ISingerPackageInstaller Instance); - /// 登记时固定描述的插件设置处理器。 - public sealed record RegisteredPluginSettings(string PluginId, PluginSettingsDescriptor Descriptor, - IPluginSettingsHandler Instance); + /// 已登记的插件入口,用于运行时查询 Web 设置能力。 + public sealed record RegisteredSingerPlugin(string PluginId, System.Reflection.Assembly Assembly, + ISingerPlugin Instance); /// 一次性发布的能力目录;消费者应持有同一快照完成查询。 public sealed record SingerPluginSnapshot( @@ -26,5 +26,5 @@ public sealed record SingerPluginSnapshot( ImmutableDictionary TypesByBridge, ImmutableDictionary Providers, ImmutableDictionary Installers, - ImmutableDictionary Settings); + ImmutableDictionary Instances); } diff --git a/OpenUtauMobile/ViewModels/PluginCardViewModel.cs b/OpenUtauMobile/ViewModels/PluginCardViewModel.cs new file mode 100644 index 00000000..0556c834 --- /dev/null +++ b/OpenUtauMobile/ViewModels/PluginCardViewModel.cs @@ -0,0 +1,19 @@ +using OpenUtauMobile.Services; +using OpenUtauMobile.Services.SingerPlugins; +using ReactiveUI; +using ReactiveUI.Fody.Helpers; + +namespace OpenUtauMobile.ViewModels; + +/// 文件信息与动态设置能力分离,不因状态变化重建整张卡片。 +public sealed class PluginCardViewModel(PluginFileEntry entry) : ReactiveObject +{ + public PluginFileEntry Entry { get; } = entry; + public string FileName => Entry.FileName; + public string RelativePath => Entry.RelativePath; + public string SizeText => Entry.SizeText; + public bool IsPendingDeletion => Entry.IsPendingDeletion; + internal RegisteredSingerPlugin? Plugin { get; } = PluginWebSettingsService.FindPlugin(entry.RelativePath); + [Reactive] public bool HasWebSettings { get; internal set; } + [Reactive] public string SettingsTitle { get; internal set; } = ""; +} diff --git a/OpenUtauMobile/ViewModels/PluginManagerViewModel.cs b/OpenUtauMobile/ViewModels/PluginManagerViewModel.cs index 23456f18..f78b5e54 100644 --- a/OpenUtauMobile/ViewModels/PluginManagerViewModel.cs +++ b/OpenUtauMobile/ViewModels/PluginManagerViewModel.cs @@ -2,12 +2,14 @@ using System.Collections.Generic; using System.IO; using System.Reactive; +using System.Threading; using System.Threading.Tasks; using DynamicData.Binding; using OpenUtau.Core; using OpenUtauMobile.Helpers; using OpenUtauMobile.Services; using OpenUtauMobile.Services.Dialogs; +using OpenUtauMobile.Services.SingerPlugins; using OpenUtauMobile.Storage; using ReactiveUI; using ReactiveUI.Fody.Helpers; @@ -15,9 +17,11 @@ namespace OpenUtauMobile.ViewModels; -public class PluginManagerViewModel : NavigateViewModelBase +public class PluginManagerViewModel : NavigateViewModelBase, IDisposable { - public ObservableCollectionExtended Plugins { get; } = []; + public ObservableCollectionExtended Plugins { get; } = []; + private readonly SemaphoreSlim queryGate = new(1, 1); + private bool disposed; [Reactive] public bool IsBusy { get; private set; } [Reactive] public bool IsEmpty { get; private set; } [Reactive] public bool HasError { get; private set; } @@ -26,8 +30,9 @@ public class PluginManagerViewModel : NavigateViewModelBase public ReactiveCommand BackCommand { get; } public ReactiveCommand RefreshCommand { get; } public ReactiveCommand InstallCommand { get; } - public ReactiveCommand DeleteCommand { get; } - public ReactiveCommand CancelDeletionCommand { get; } + public ReactiveCommand DeleteCommand { get; } + public ReactiveCommand CancelDeletionCommand { get; } + public ReactiveCommand OpenSettingsCommand { get; } public PluginManagerViewModel(MainViewModel navigator) : base(navigator) { @@ -35,8 +40,9 @@ public PluginManagerViewModel(MainViewModel navigator) : base(navigator) BackCommand = ReactiveCommand.Create(() => Navigator.NavigateBack(this), canOperate); RefreshCommand = ReactiveCommand.CreateFromTask(RefreshAsync, canOperate); InstallCommand = ReactiveCommand.CreateFromTask(InstallAsync, canOperate); - DeleteCommand = ReactiveCommand.CreateFromTask(DeleteAsync, canOperate); - CancelDeletionCommand = ReactiveCommand.CreateFromTask(CancelDeletionAsync, canOperate); + DeleteCommand = ReactiveCommand.CreateFromTask(DeleteAsync, canOperate); + CancelDeletionCommand = ReactiveCommand.CreateFromTask(CancelDeletionAsync, canOperate); + OpenSettingsCommand = ReactiveCommand.CreateFromTask(OpenSettingsAsync, canOperate); } public override void OnNavigatedTo() => _ = RefreshAsync(); @@ -59,7 +65,8 @@ private async Task RefreshEntriesAsync() try { IReadOnlyList entries = await Task.Run(PluginManagementService.ListFiles); - Plugins.Load(entries); + Plugins.Load([.. System.Linq.Enumerable.Select(entries, entry => new PluginCardViewModel(entry))]); + await QuerySettingsAsync(CancellationToken.None); IsEmpty = entries.Count == 0; HasError = false; ErrorMessage = string.Empty; @@ -121,7 +128,7 @@ await OptionConfirmPopupService.ShowAsync( finally { IsBusy = false; } } - private async Task DeleteAsync(PluginFileEntry entry) + private async Task DeleteAsync(PluginCardViewModel entry) { if (IsBusy) return; IsBusy = true; @@ -151,7 +158,7 @@ private async Task DeleteAsync(PluginFileEntry entry) } } - private async Task CancelDeletionAsync(PluginFileEntry entry) + private async Task CancelDeletionAsync(PluginCardViewModel entry) { if (IsBusy) return; IsBusy = true; @@ -177,4 +184,62 @@ private static void ShowError(string key, Exception exception) Log.Error(exception, "Plugin management operation failed: {Operation}", key); ErrorDialogService.Show(new ErrorDialogViewModel(new ErrorMessageNotification(L.S(key), exception))); } + + private async Task QuerySettingsAsync(CancellationToken token) + { + await queryGate.WaitAsync(token); + try + { + PluginCardViewModel[] cards = [.. Plugins]; + foreach (PluginCardViewModel card in cards) + { + if (disposed) return; + if (card.Plugin == null || card.IsPendingDeletion) { card.HasWebSettings = false; continue; } + using CancellationTokenSource query = CancellationTokenSource.CreateLinkedTokenSource(token); + query.CancelAfter(TimeSpan.FromSeconds(5)); + try + { + var descriptor = await Task.Run(async () => await PluginWebSettingsService.QueryAsync(card.Plugin, query.Token), query.Token) + .WaitAsync(query.Token); + token.ThrowIfCancellationRequested(); + if (disposed) return; + card.SettingsTitle = descriptor?.Title ?? ""; + card.HasWebSettings = descriptor != null; + } + catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; } + catch (Exception exception) + { + card.HasWebSettings = false; + Log.Debug(exception, "Plugin web settings query failed {PluginId}", card.Plugin.PluginId); + } + } + } + finally { queryGate.Release(); } + } + + private async Task OpenSettingsAsync(PluginCardViewModel card) + { + if (IsBusy || card.Plugin == null || card.IsPendingDeletion) return; + IsBusy = true; + try + { + using CancellationTokenSource query = new(TimeSpan.FromSeconds(5)); + var descriptor = await Task.Run(async () => await PluginWebSettingsService.QueryAsync(card.Plugin, query.Token), query.Token) + .WaitAsync(query.Token); + if (disposed) return; + if (descriptor == null) { card.HasWebSettings = false; return; } + Navigator.Navigate(new PluginWebSettingsViewModel(Navigator, card.Plugin, + string.IsNullOrWhiteSpace(descriptor.Title) ? card.FileName : descriptor.Title)); + } + catch (Exception exception) { ShowError("PluginWebSettings.OpenFailed", exception); } + finally { IsBusy = false; } + } + + public void Dispose() + { + if (disposed) return; + disposed = true; + BackCommand.Dispose(); RefreshCommand.Dispose(); InstallCommand.Dispose(); + DeleteCommand.Dispose(); CancelDeletionCommand.Dispose(); OpenSettingsCommand.Dispose(); + } } diff --git a/OpenUtauMobile/ViewModels/PluginSettingsViewModel.cs b/OpenUtauMobile/ViewModels/PluginSettingsViewModel.cs deleted file mode 100644 index b2862393..00000000 --- a/OpenUtauMobile/ViewModels/PluginSettingsViewModel.cs +++ /dev/null @@ -1,139 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using OpenUtauMobile.Helpers; -using OpenUtauMobile.Plugin.Abstractions; -using OpenUtauMobile.Services.SingerPlugins; -using ReactiveUI; -using ReactiveUI.Fody.Helpers; -using Serilog; - -namespace OpenUtauMobile.ViewModels -{ - /// 设置页内的插件字段,变更后串行校验保存,不提供独立保存或取消流程。 - public sealed class PluginSettingsViewModel : ViewModelBase, IDisposable - { - private readonly RegisteredPluginSettings registration; - private PluginSettingsSession? session; - private CancellationTokenSource? operation; - private bool disposed; - private long editRevision; - private long pendingRevision; - private ImmutableDictionary? pendingValues; - private Task saveTask = Task.CompletedTask; - [Reactive] public ImmutableArray Fields { get; private set; } = []; - [Reactive] public bool IsBusy { get; private set; } - [Reactive] public bool IsSaving { get; private set; } - [Reactive] public bool IsLoaded { get; private set; } - [Reactive] public string Error { get; private set; } = ""; - [Reactive] public string Message { get; private set; } = ""; - - /// 绑定一个插件的设置,初始化时异步读取文件。 - public PluginSettingsViewModel(RegisteredPluginSettings registration) - { - this.registration = registration; - } - - /// 由设置页选中插件后调用,初始化不触发保存。 - public Task InitializeAsync() => IsLoaded ? Task.CompletedTask : RunAsync(async token => - { - session = await Task.Run(() => PluginSettingsService.Open(registration), token); - token.ThrowIfCancellationRequested(); - if (disposed) return; - Fields = [.. registration.Descriptor.Fields.Select(item => new PluginFieldViewModel( - session.Values.TryGetValue(item.Field.Id, out PluginValue? value) ? item.Field with { DefaultValue = value } : item.Field, - OnFieldChanged))]; - IsLoaded = true; - }); - - private ImmutableDictionary ReadValues() => session!.Values.SetItems( - Fields.Select(field => KeyValuePair.Create(field.Descriptor.Id, field.Read()))); - - /// 在界面线程截取不可变快照;快速连续修改只保留尚未提交的最新一份。 - private void OnFieldChanged() - { - if (!IsLoaded || disposed) return; - editRevision++; - Error = ""; - Message = ""; - try { pendingValues = ReadValues(); pendingRevision = editRevision; } - catch (Exception exception) { pendingValues = null; ShowError(exception); return; } - if (!IsSaving) saveTask = SavePendingAsync(); - } - - /// 串行持久化,不重建字段或禁用输入,防止旧值覆盖新值及焦点跳动。 - private async Task SavePendingAsync() - { - IsSaving = true; - try - { - while (pendingValues is { } values) - { - long revision = pendingRevision; - pendingValues = null; - try - { - await session!.SaveAsync(values); - await NotifyCommittedAsync(); - if (!disposed && revision == editRevision) - { - Error = ""; - Message = registration.Descriptor.Fields.Any(field => field.Application == PluginSettingApplication.Restart) - ? L.S("PluginSettings.SavedRestart") : ""; - } - } - catch (Exception exception) - { - if (disposed) Log.Warning(exception, "Failed to persist plugin settings {Plugin}", registration.PluginId); - else if (revision == editRevision) ShowError(exception); - } - } - } - finally { IsSaving = false; } - } - - /// 切换插件或离开设置页时等待已经排队的变更,不出现草稿确认。 - public Task FlushAsync() => saveTask; - - private async Task NotifyCommittedAsync() - { - await Services.ServiceHub.FlushFileSystemAsync(); - if (registration.Descriptor.Fields.Any(field => field.Application == PluginSettingApplication.ReloadResources)) - await SingerDiscoveryService.Instance.RefreshAsync(); - } - - private async Task RunAsync(Func action) - { - if (IsBusy || disposed) return; - using CancellationTokenSource cancellation = new(); - operation = cancellation; - IsBusy = true; - Error = ""; - Message = ""; - try { await action(cancellation.Token); } - catch (OperationCanceledException) when (cancellation.IsCancellationRequested) { } - catch (Exception exception) { if (!disposed) ShowError(exception); } - finally { operation = null; IsBusy = false; } - } - - private void ShowError(Exception exception) - { - Error = exception.Message; - if (exception is PluginSettingsValidationException validation) - foreach (PluginDiagnostic diagnostic in validation.Diagnostics) - Fields.FirstOrDefault(field => field.Descriptor.Id == diagnostic.FieldId)?.SetError( - diagnostic.Code == "settings.invalid-field" ? L.S("SingerSetup.InvalidValue") : diagnostic.Message); - } - - public void Dispose() - { - disposed = true; - operation?.Cancel(); - // 已捕获的保存快照继续写完,离开页面不会撤销已输入的有效设置。 - foreach (PluginFieldViewModel field in Fields) field.Dispose(); - } - } -} diff --git a/OpenUtauMobile/ViewModels/PluginWebSettingsViewModel.cs b/OpenUtauMobile/ViewModels/PluginWebSettingsViewModel.cs new file mode 100644 index 00000000..1cedbee1 --- /dev/null +++ b/OpenUtauMobile/ViewModels/PluginWebSettingsViewModel.cs @@ -0,0 +1,116 @@ +using System; +using System.Reactive; +using System.Reactive.Linq; +using System.Threading; +using System.Threading.Tasks; +using OpenUtauMobile.Helpers; +using OpenUtauMobile.Plugin.Abstractions; +using OpenUtauMobile.Services; +using OpenUtauMobile.Services.Platform; +using OpenUtauMobile.Services.SingerPlugins; +using ReactiveUI; +using ReactiveUI.Fody.Helpers; +using Serilog; + +namespace OpenUtauMobile.ViewModels; + +/// 独立网页设置页面,拥有一次插件会话和取消令牌。 +public sealed class PluginWebSettingsViewModel : NavigateViewModelBase, IDisposable +{ + private readonly RegisteredSingerPlugin plugin; + private readonly CancellationTokenSource lifetime = new(); + private IPluginWebSettingsSession? session; + private Task opening = Task.CompletedTask; + private Task? closing; + private bool started; + private bool disposed; + public string Title { get; } + [Reactive] public Uri? Address { get; private set; } + [Reactive] public bool IsBusy { get; private set; } = true; + [Reactive] public string Error { get; private set; } = ""; + public ReactiveCommand BackCommand { get; } + public ReactiveCommand OpenBrowserCommand { get; } + + public PluginWebSettingsViewModel(MainViewModel navigator, RegisteredSingerPlugin plugin, string title) : base(navigator) + { + this.plugin = plugin; + Title = title; + BackCommand = ReactiveCommand.Create(OnBackRequested); + OpenBrowserCommand = ReactiveCommand.CreateFromTask(OpenBrowserAsync, this.WhenAnyValue(vm => vm.Address).Select(value => value != null)); + } + + public override void OnNavigatedTo() + { + if (!started) { started = true; opening = OpenAsync(); } + } + + private async Task OpenAsync() + { + try + { + session = await PluginWebSettingsService.OpenAsync(plugin, lifetime.Token); + if (!lifetime.IsCancellationRequested) Address = session.Address; + } + catch (OperationCanceledException) when (lifetime.IsCancellationRequested) { } + catch (Exception exception) + { + Log.Error(exception, "Failed to open plugin web settings {PluginId}", plugin.PluginId); + if (!disposed) Error = L.S("PluginWebSettings.OpenFailed"); + } + finally { if (!disposed) IsBusy = false; } + } + + private async Task OpenBrowserAsync() + { + if (Address == null) return; + ExternalUrlLaunchResult result = await ExternalUrlService.OpenAsync(Address.AbsoluteUri); + if (!result.Succeeded) Error = L.S("PluginWebSettings.BrowserFailed"); + } + + /// 系统 WebView 不可用时保留外部浏览器入口。 + public void ReportWebViewFailure() => Error = L.S("PluginWebSettings.WebViewFailed"); + + public override void OnBackRequested() => _ = LeaveAsync(); + + private async Task LeaveAsync() + { + await CloseAsync(); + if (!disposed) Navigator.NavigateBack(this); + } + + /// 关闭任务只创建一次,等服务释放后再刷新资源。 + private Task CloseAsync() => closing ??= CloseCoreAsync(); + + private async Task CloseCoreAsync() + { + lifetime.Cancel(); + await opening; + IPluginWebSettingsSession? current = session; + session = null; + if (current == null) return; + bool refresh = current.ReloadResourcesOnClose; + try { await current.DisposeAsync(); } + catch (Exception exception) { Log.Error(exception, "Failed to close plugin web settings {PluginId}", plugin.PluginId); } + try + { + await ServiceHub.FlushFileSystemAsync(); + if (refresh) await SingerDiscoveryService.Instance.RefreshAsync(); + } + catch (Exception exception) { Log.Error(exception, "Failed to refresh resources after plugin settings {PluginId}", plugin.PluginId); } + } + + public void Dispose() + { + if (disposed) return; + disposed = true; + _ = FinishDisposeAsync(); + BackCommand.Dispose(); + OpenBrowserCommand.Dispose(); + } + + private async Task FinishDisposeAsync() + { + try { await CloseAsync(); } + finally { lifetime.Dispose(); } + } +} diff --git a/OpenUtauMobile/ViewModels/SettingsViewModel.Plugins.cs b/OpenUtauMobile/ViewModels/SettingsViewModel.Plugins.cs deleted file mode 100644 index 71cd7c5f..00000000 --- a/OpenUtauMobile/ViewModels/SettingsViewModel.Plugins.cs +++ /dev/null @@ -1,118 +0,0 @@ -using System; -using System.Collections.Immutable; -using System.ComponentModel; -using System.Linq; -using System.Reactive.Linq; -using System.Threading.Tasks; -using Avalonia.Threading; -using OpenUtauMobile.Helpers; -using OpenUtauMobile.Services.Dialogs; -using OpenUtauMobile.Services.SingerPlugins; -using ReactiveUI; -using ReactiveUI.Fody.Helpers; - -namespace OpenUtauMobile.ViewModels; - -/// 插件下拉选项,空注册表示明确的“未选择”。 -public sealed record SettingsPluginOption(RegisteredPluginSettings? Registration) -{ - public bool IsUnselected => Registration == null; - public string DisplayName => Registration?.Descriptor.DisplayName ?? ""; -} - -/// 插件设置由设置页持有,切换分类保留当前字段实例。 -public partial class SettingsViewModel -{ - private SettingsPluginOption selectedPlugin = null!; - private bool switchingPlugin; - private bool leavingSettings; - public ImmutableArray PluginOptions { get; private set; } = []; - [Reactive] public PluginSettingsViewModel? PluginSettings { get; private set; } - public bool IsPluginTab => SelectedCategory == SettingsCategory.Plugins; - public bool HasSelectedPlugin => PluginSettings != null; - public bool CanSelectPlugin => !switchingPlugin && PluginSettings?.IsBusy != true && PluginSettings?.IsSaving != true; - - /// 选项变更等待实时保存,操作忙碌时恢复原选择。 - public SettingsPluginOption SelectedPlugin - { - get => selectedPlugin; - set - { - if (value != null && value != selectedPlugin) _ = SelectPluginAsync(value); - } - } - - private void InitializePluginSelection() - { - PluginOptions = [new(null), .. SingerPluginService.Registry.Snapshot.Settings.Values - .OrderBy(item => item.Descriptor.DisplayName, StringComparer.CurrentCulture).Select(item => new SettingsPluginOption(item))]; - selectedPlugin = PluginOptions[0]; - _disposables.Add(this.WhenAnyValue(item => item.SelectedCategory).Subscribe(_ => this.RaisePropertyChanged(nameof(IsPluginTab)))); - } - - /// 等待已排队的实时保存后切换实例,不询问保存或放弃。 - private async Task SelectPluginAsync(SettingsPluginOption option) - { - if (!CanSelectPlugin || disposed) - { - RestorePluginSelection(); - return; - } - switchingPlugin = true; - this.RaisePropertyChanged(nameof(CanSelectPlugin)); - selectedPlugin = option; - this.RaisePropertyChanged(nameof(SelectedPlugin)); - try - { - if (PluginSettings != null) await PluginSettings.FlushAsync(); - if (disposed) return; - DisposePluginSelection(); - PluginSettings = option.Registration is { } registration ? new(registration) : null; - this.RaisePropertyChanged(nameof(HasSelectedPlugin)); - if (PluginSettings != null) - { - PluginSettings.PropertyChanged += OnPluginSettingsChanged; - await PluginSettings.InitializeAsync(); - } - } - finally - { - switchingPlugin = false; - this.RaisePropertyChanged(nameof(CanSelectPlugin)); - } - } - - private void OnPluginSettingsChanged(object? sender, PropertyChangedEventArgs args) - { - if (args.PropertyName is nameof(PluginSettingsViewModel.IsBusy) or nameof(PluginSettingsViewModel.IsSaving)) this.RaisePropertyChanged(nameof(CanSelectPlugin)); - } - - /// 操作期间拒绝选择变更,保持下拉框与实际插件一致。 - private void RestorePluginSelection() => Dispatcher.UIThread.Post(() => - { - if (!disposed) this.RaisePropertyChanged(nameof(SelectedPlugin)); - }); - - public override void OnBackRequested() => _ = LeaveSettingsAsync(); - - private async Task LeaveSettingsAsync() - { - if (leavingSettings || switchingPlugin || disposed) return; - leavingSettings = true; - try - { - if (PluginSettings?.IsBusy == true) { ToastService.Enqueue(L.S("PluginSettings.Busy")); return; } - if (PluginSettings != null) await PluginSettings.FlushAsync(); - if (disposed) return; - Navigator.NavigateBack(this); - } - finally { leavingSettings = false; } - } - - private void DisposePluginSelection() - { - if (PluginSettings == null) return; - PluginSettings.PropertyChanged -= OnPluginSettingsChanged; - PluginSettings.Dispose(); - } -} diff --git a/OpenUtauMobile/ViewModels/SettingsViewModel.cs b/OpenUtauMobile/ViewModels/SettingsViewModel.cs index 11ded081..8262f1fb 100644 --- a/OpenUtauMobile/ViewModels/SettingsViewModel.cs +++ b/OpenUtauMobile/ViewModels/SettingsViewModel.cs @@ -35,7 +35,6 @@ public enum SettingsCategory RenderAndPerformance, FileAndStorage, AppearanceAndLanguage, - Plugins } /// @@ -660,8 +659,7 @@ public partial class SettingsViewModel : NavigateViewModelBase, IDisposable public SettingsViewModel(MainViewModel navigator) : base(navigator) { - BackCommand = ReactiveCommand.CreateFromTask(LeaveSettingsAsync); - InitializePluginSelection(); + BackCommand = ReactiveCommand.Create(() => Navigator.NavigateBack(this)); ToggleNavCommand = ReactiveCommand.Create(OnToggleNav); SelectCategoryCommand = ReactiveCommand.Create(OnSelectCategory); } @@ -1662,7 +1660,6 @@ private void OnToggleNav() private void OnSelectCategory(SettingsCategory category) { SelectedCategory = category; - this.RaisePropertyChanged(nameof(IsPluginTab)); if (ArePreferencesInitialized && category == SettingsCategory.FileAndStorage) { _ = RefreshCacheSizeAsync(); @@ -1671,7 +1668,6 @@ private void OnSelectCategory(SettingsCategory category) public void Dispose() { - DisposePluginSelection(); disposed = true; ++_cacheSizeRefreshVersion; _disposables.Dispose(); diff --git a/OpenUtauMobile/ViewModels/TrackSettingsPopupViewModel.cs b/OpenUtauMobile/ViewModels/TrackSettingsPopupViewModel.cs index 8d070f29..1337528c 100644 --- a/OpenUtauMobile/ViewModels/TrackSettingsPopupViewModel.cs +++ b/OpenUtauMobile/ViewModels/TrackSettingsPopupViewModel.cs @@ -38,7 +38,7 @@ public sealed class TrackSettingsPopupViewModel : PopupViewModelBase, IDisposabl private readonly URenderSettings originalRenderSettings; private readonly string? originalExpressionGraph; private readonly USinger? originalSinger; - private readonly Phonemizer originalPhonemizer; + private readonly Phonemizer? originalPhonemizer; private readonly UExpressionDescriptor[] originalTrackExpressions; private Phonemizer draftPhonemizer; private URenderSettings draftRenderSettings; @@ -46,11 +46,11 @@ public sealed class TrackSettingsPopupViewModel : PopupViewModelBase, IDisposabl private bool classicDraftInitialized; [Reactive] public USinger? DraftSinger { get; set; } - [Reactive] public string DraftSingerName { get; set; } = string.Empty; - [Reactive] public string DraftPhonemizerName { get; set; } = string.Empty; - [Reactive] public string DraftRenderer { get; set; } = string.Empty; - [Reactive] public string DraftResampler { get; set; } = string.Empty; - [Reactive] public string DraftWavtool { get; set; } = string.Empty; + [Reactive] public string DraftSingerName { get; set; } + [Reactive] public string DraftPhonemizerName { get; set; } + [Reactive] public string DraftRenderer { get; set; } + [Reactive] public string DraftResampler { get; set; } + [Reactive] public string DraftWavtool { get; set; } [Reactive] public string Error { get; set; } = string.Empty; [Reactive] public Vector ScrollOffset { get; set; } [Reactive] public bool IsRendererEnabled { get; set; } @@ -76,11 +76,11 @@ public sealed class TrackSettingsPopupViewModel : PopupViewModelBase, IDisposabl public UProject Project => project; public UTrack Track => track; - public Type OriginalPhonemizerType => originalPhonemizer.GetType(); + public Type? OriginalPhonemizerType => originalPhonemizer?.GetType(); public string DraftPhonemizerIdentifier => draftPhonemizer.Name; public IReadOnlyList DraftTrackExpressions { get; private set; } public bool IsStale => !ReferenceEquals(DocManager.Inst.Project, project) || !project.tracks.Contains(track) || - !ReferenceEquals(track.Singer, originalSinger) || track.Phonemizer?.GetType() != originalPhonemizer.GetType() || + !ReferenceEquals(track.Singer, originalSinger) || track.Phonemizer?.GetType() != originalPhonemizer?.GetType() || !SameRenderSettings(track.RendererSettings, originalRenderSettings) || track.ExpressionGraph != originalExpressionGraph || !SameExpressions(track.TrackExpressions, originalTrackExpressions); diff --git a/OpenUtauMobile/Views/PluginManagerView.axaml b/OpenUtauMobile/Views/PluginManagerView.axaml index ffdfd98d..b4ac7236 100644 --- a/OpenUtauMobile/Views/PluginManagerView.axaml +++ b/OpenUtauMobile/Views/PluginManagerView.axaml @@ -34,9 +34,9 @@ - + - + - - - @@ -402,7 +345,7 @@ Opacity="0.10" Background="{DynamicResource Sem.Color.OnSurfaceVariant}" /> - - - - - - - - - - - - - - - - - - - - - - - + diff --git a/docs/PLUGIN_WEB_SETTINGS.md b/docs/PLUGIN_WEB_SETTINGS.md new file mode 100644 index 00000000..ca61ff91 --- /dev/null +++ b/docs/PLUGIN_WEB_SETTINGS.md @@ -0,0 +1,49 @@ +# 插件 Web 设置(契约 v2) + +插件管理卡片上的齿轮进入独立 WebView 页面。宿主使用 `Avalonia.Controls.WebView` 的系统适配器:Windows WebView2、Apple WKWebView、Linux WebKit。宿主不携带 Chromium/CEF;系统缺少对应运行库或加载失败时保留右上角的系统浏览器入口。 + +## 动态声明 + +在 `ISingerPlugin` 上实现两个方法: + +```csharp +public ValueTask GetWebSettingsAsync( + PluginWebSettingsContext context, CancellationToken cancellationToken) +{ + // 返回 null 时不显示设置齿轮。查询不得启动 HTTP 服务或弹出页面。 + return ValueTask.FromResult( + new PluginWebSettingsDescriptor("账户与设置")); +} + +public async ValueTask OpenWebSettingsAsync( + PluginWebSettingsContext context, CancellationToken cancellationToken) +{ + // 插件自行提供 HTTP/HTTPS 页面,返回拥有服务生命周期的会话对象。 + return await CreateSessionAsync(context.Storage.DataDirectory, cancellationToken); +} +``` + +宿主在进入插件管理页或点击右上角刷新按钮时查询当前声明,没有定时轮询。点击齿轮时再次查询,创建页面会话之前也会确认能力仍可用。查询应快速完成并响应取消;查询失败或超时隐藏对应齿轮,不影响其他插件。 + +`GetWebSettingsAsync` 的默认实现返回 null,因此没有 Web 设置的插件不需要实现任何额外方法。尚未激活、登记失败和待删除的插件不会显示齿轮;安装插件后仍按既有流程重启激活。 + +## 会话与存储 + +- `IPluginWebSettingsSession.Address` 是绝对 HTTP/HTTPS 地址;可以是插件创建的本地服务,也可以是远端设置页。地址在每次打开时生成,不缓存登记时的 URL。 +- `DisposeAsync` 负责关闭本地监听、轮询和临时资源。取消令牌在离开页面时取消;不要把监听器生命周期交给浏览器标签页。 +- `ReloadResourcesOnClose` 默认 true,释放会话后由宿主刷新歌手发现;不需要刷新时返回 false。 +- 右上角按钮使用系统浏览器打开会话地址。此时内嵌页面仍拥有会话;返回管理页会结束会话,本地网页在外部浏览器中也随之失效。 +- `context.Storage.DataDirectory` 是插件独占的稳定目录,沿用 `DataPath/PluginData/<插件 ID 的 SHA256>` 映射。`ResourceDirectory` 是其中的 `Resources` 子目录。 +- 插件自行管理配置格式、凭据保护、读写并发和版本迁移;发现和安装上下文通过 `Storage` 提供相同目录。 + +宿主不解释网页的表单或账户协议,不通过 JavaScript 接收账户 token,也不提供可执行宿主命令的脚本桥。运行平台的文件和网络限制仍然适用。 + +## v1 迁移 + +本次为破坏性契约升级,`SingerPluginContract.Version` 为 2,插件需重新编译。 + +移除 `RegisterSettings`、`IPluginSettingsHandler`、`IPluginSettingsReader`、字段式设置描述、宿主自动保存与配置迁移回调。安装向导自己的字段描述和值类型仍保留,不属于设置契约。 + +发现和安装代码把原 `context.Settings` 改为 `context.Storage`,自行从插件目录读取配置。旧 `settings.json` 不由宿主删除或自动重写;需要延续数据时由插件自己的迁移逻辑处理。 + +用户界面入口统一在“插件管理”,通用“设置”页面不再包含插件设置分类。 From 7983bc35f3e334de57ebf4df0b33431f436edd5c Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Wed, 4 Nov 2026 20:55:04 +0800 Subject: [PATCH 17/45] =?UTF-8?q?chore:=20=E4=BF=AE=E6=94=B9=E6=8F=92?= =?UTF-8?q?=E4=BB=B6=E6=95=B0=E6=8D=AE=E7=9B=AE=E5=BD=95=E5=90=8D=E7=A7=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Discovery/SingerDiscovery.cs | 12 +++++-- .../Installation/InstallServices.cs | 6 +++- .../PluginContracts.cs | 17 ++++++++++ .../PluginNotifications.cs | 15 +++++++++ OpenUtauMobile.Plugin.Abstractions/README.md | 15 ++++++++- .../Settings/PluginWebSettings.cs | 6 +++- OpenUtauMobile/Assets/Lang/Strings.en.resx | 2 ++ .../Assets/Lang/Strings.zh-Hans.resx | 2 ++ .../SingerPlugins/PluginWebSettingsService.cs | 11 ++++--- .../SingerPlugins/SingerPluginRegistration.cs | 6 +--- .../SingerPlugins/SingerPluginRuntime.cs | 32 +++++++++++++++++-- docs/PLUGIN_WEB_SETTINGS.md | 2 +- 12 files changed, 108 insertions(+), 18 deletions(-) create mode 100644 OpenUtauMobile.Plugin.Abstractions/PluginNotifications.cs diff --git a/OpenUtauMobile.Plugin.Abstractions/Discovery/SingerDiscovery.cs b/OpenUtauMobile.Plugin.Abstractions/Discovery/SingerDiscovery.cs index 45622314..e4ff313a 100644 --- a/OpenUtauMobile.Plugin.Abstractions/Discovery/SingerDiscovery.cs +++ b/OpenUtauMobile.Plugin.Abstractions/Discovery/SingerDiscovery.cs @@ -39,10 +39,18 @@ public sealed record SingerDiscoveryContext( ImmutableArray Roots, CultureInfo Culture, PluginStorageContext Storage, - IPluginLog Log); + IPluginLog Log) + { + /// 当前插件的用户通知入口。 + public IPluginNotifications Notifications => (IPluginNotifications)Log; + } /// 执行时重新读取根目录权限,不能沿用扫描时已过期的删除授权。 - public sealed record SingerDeletionContext(ImmutableArray Roots, IPluginLog Log); + public sealed record SingerDeletionContext(ImmutableArray Roots, IPluginLog Log) + { + /// 当前插件的用户通知入口。 + public IPluginNotifications Notifications => (IPluginNotifications)Log; + } /// 提供歌手发现和可选删除能力,不直接修改宿主歌手字典。 public interface ISingerProvider diff --git a/OpenUtauMobile.Plugin.Abstractions/Installation/InstallServices.cs b/OpenUtauMobile.Plugin.Abstractions/Installation/InstallServices.cs index 745536f0..93c79638 100644 --- a/OpenUtauMobile.Plugin.Abstractions/Installation/InstallServices.cs +++ b/OpenUtauMobile.Plugin.Abstractions/Installation/InstallServices.cs @@ -71,5 +71,9 @@ public sealed record SingerInstallContext(Guid SessionId, CultureInfo Culture, I IInstallWorkspace Workspace, ImmutableArray SingerRoots, ImmutableArray InstallTargets, string DefaultTargetId, IInstalledSingerLookup InstalledSingers, IInstallFileOperations Files, - PluginStorageContext Storage, IPluginLog Log); + PluginStorageContext Storage, IPluginLog Log) + { + /// 当前插件的用户通知入口。 + public IPluginNotifications Notifications => (IPluginNotifications)Log; + } } diff --git a/OpenUtauMobile.Plugin.Abstractions/PluginContracts.cs b/OpenUtauMobile.Plugin.Abstractions/PluginContracts.cs index 6746abde..10e4d218 100644 --- a/OpenUtauMobile.Plugin.Abstractions/PluginContracts.cs +++ b/OpenUtauMobile.Plugin.Abstractions/PluginContracts.cs @@ -9,6 +9,23 @@ public static class SingerPluginContract public const int Version = 2; /// 外部类型数值的起点;数值只用于桥接,不作为位标志。 public const int ExternalTypeMinimum = 0x10000000; + + /// 校验可直接作为跨平台单级目录名的插件 ID;能力 ID 另按命名空间规则校验。 + public static void ValidatePluginId(string id) + { + ArgumentException.ThrowIfNullOrEmpty(id); + if (id.Length > 160 || !char.IsAsciiLetterLower(id[0]) || id.EndsWith('.') + || id.StartsWith("opum.", StringComparison.Ordinal) + || id.Any(character => !char.IsAsciiLetterLower(character) && !char.IsAsciiDigit(character) + && character is not '.' and not '-' and not '_')) + throw new ArgumentException("插件 ID 须以小写字母开头,仅含小写字母、数字、点、下划线和短横线,不能以点结尾或使用 opum. 前缀。", nameof(id)); + + string stem = id.Split('.')[0]; + if (stem is "con" or "prn" or "aux" or "nul" + || (stem.Length == 4 && stem[3] is >= '1' and <= '9' + && (stem.StartsWith("com", StringComparison.Ordinal) || stem.StartsWith("lpt", StringComparison.Ordinal)))) + throw new ArgumentException("插件 ID 不能使用系统保留的设备名称。", nameof(id)); + } } /// 在程序集上声明歌手插件入口;宿主先检查版本,再创建入口实例。 diff --git a/OpenUtauMobile.Plugin.Abstractions/PluginNotifications.cs b/OpenUtauMobile.Plugin.Abstractions/PluginNotifications.cs new file mode 100644 index 00000000..46506864 --- /dev/null +++ b/OpenUtauMobile.Plugin.Abstractions/PluginNotifications.cs @@ -0,0 +1,15 @@ +namespace OpenUtauMobile.Plugin.Abstractions +{ + /// 需要用户关注的插件警告;文本由插件本地化,代码在插件内保持稳定。 + public sealed record PluginWarning(string Code, string Message, string? Details = null); + + /// 宿主提供的用户通知入口,与仅写日志的 IPluginLog 分开。 + public interface IPluginNotifications + { + /// 发布或更新同代码警告;宿主自动按当前插件隔离身份并调度到界面线程。 + void PublishWarning(PluginWarning warning); + + /// 问题恢复后清除当前插件的指定警告,不影响其他插件或宿主通知。 + void ClearWarning(string code); + } +} diff --git a/OpenUtauMobile.Plugin.Abstractions/README.md b/OpenUtauMobile.Plugin.Abstractions/README.md index c372e9fd..0c741b8f 100644 --- a/OpenUtauMobile.Plugin.Abstractions/README.md +++ b/OpenUtauMobile.Plugin.Abstractions/README.md @@ -4,10 +4,23 @@ 使用 `[assembly: SingerPlugin(typeof(PluginEntry))]` 声明实现 `ISingerPlugin` 的公开无参入口。在 `Register` 内同步登记类型、发现提供方和安装器,不执行扫描或安装。设置通过运行时 WebUI 会话提供,详见 [Web 设置契约](../docs/PLUGIN_WEB_SETTINGS.md)。 -- 插件 ID 使用小写字母开头,允许数字、点、下划线和短横线;`opum.` 为保留前缀。能力 ID 使用 `:<名称>`。 +- 插件 ID 使用小写字母开头,最长 160 个字符,仅允许小写字母、数字、点、下划线和短横线,不能以点结尾或使用系统设备保留名;`opum.` 为保留前缀。`SingerPluginContract.ValidatePluginId` 保证它能直接作为跨平台单级目录名。能力 ID 使用 `:<名称>`。 +- 数据目录为 `DataPath/PluginData/`,不迁移或回退读取旧哈希目录。 - 类型桥接值固定在 `0x10000000` 至 `int.MaxValue` 内,宿主检查冲突。 - 可用类型的 renderer 工厂须与入口同程序集;类型值、renderer 集合和默认值须与 Core 一致。不可用类型填写原因,renderer 集合与默认值留空。 - 安装器声明文件后缀,由用户先选安装器再选包;后缀允许重叠。 - 插件安装使用独立的声明式页面;内置安装由宿主实现。 - `PrepareAsync` 同时接收末步字段与目标;输入变化后须重新准备,计划只能提交一次。 - 可选集合的默认值按空集合处理。登记失败不发布本批能力;替换插件需要重启。 + +发现、删除、安装和 Web 设置上下文通过 `Notifications` 提供用户警告: + +```csharp +context.Notifications.PublishWarning(new("catalog.fetch-failed", "获取歌手列表失败。", "请检查网络或打开插件设置重新认证。")); +// 成功恢复后清除同代码警告。 +context.Notifications.ClearWarning("catalog.fetch-failed"); +``` + +同插件同代码更新原警告,不重复堆积;宿主自动限定插件归属,允许后台线程调用。Message/Details 是插件本地化后的纯文本,不能包含凭据或认证 URL。`Log` 继续只负责诊断日志,发现结果的 Diagnostics 不会自动转成用户警告。 + +`Notifications` 使用宿主既有服务的通知接口,操作上下文的构造参数与 v2 契约版本保持不变。 diff --git a/OpenUtauMobile.Plugin.Abstractions/Settings/PluginWebSettings.cs b/OpenUtauMobile.Plugin.Abstractions/Settings/PluginWebSettings.cs index a064aa41..7f70f38b 100644 --- a/OpenUtauMobile.Plugin.Abstractions/Settings/PluginWebSettings.cs +++ b/OpenUtauMobile.Plugin.Abstractions/Settings/PluginWebSettings.cs @@ -8,7 +8,11 @@ public sealed record PluginStorageContext(string DataDirectory) } /// 每次查询和打开设置时提供的宿主上下文。 - public sealed record PluginWebSettingsContext(PluginStorageContext Storage, IPluginLog Log); + public sealed record PluginWebSettingsContext(PluginStorageContext Storage, IPluginLog Log) + { + /// 宿主服务同时实现日志与通知接口,保持既有构造参数不变。 + public IPluginNotifications Notifications => (IPluginNotifications)Log; + } /// 当前可用的 Web 设置声明;查询返回 null 表示此刻没有设置入口。 public sealed record PluginWebSettingsDescriptor(string Title); diff --git a/OpenUtauMobile/Assets/Lang/Strings.en.resx b/OpenUtauMobile/Assets/Lang/Strings.en.resx index 1dbb8d34..41841fe4 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.en.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.en.resx @@ -2632,4 +2632,6 @@ Applying replaces the source of this input. Could not open plugin settings. Could not open the system browser. The system WebView could not load this page. Use the top-right button to open it in your browser. + {0}: {1} + {2} diff --git a/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx b/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx index e2b3aacf..d993ebba 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx @@ -2632,4 +2632,6 @@ 无法打开插件设置。 无法打开系统浏览器。 系统 WebView 无法加载页面,可使用右上角按钮在系统浏览器打开。 + {0}:{1} + {2} diff --git a/OpenUtauMobile/Services/SingerPlugins/PluginWebSettingsService.cs b/OpenUtauMobile/Services/SingerPlugins/PluginWebSettingsService.cs index 45a10e63..c46c5d61 100644 --- a/OpenUtauMobile/Services/SingerPlugins/PluginWebSettingsService.cs +++ b/OpenUtauMobile/Services/SingerPlugins/PluginWebSettingsService.cs @@ -1,8 +1,6 @@ using System; using System.IO; using System.Linq; -using System.Security.Cryptography; -using System.Text; using System.Threading; using System.Threading.Tasks; using OpenUtau.Core; @@ -13,9 +11,12 @@ namespace OpenUtauMobile.Services.SingerPlugins; /// 按插件隔离存储;只在用户打开页面时创建插件网页会话。 public static class PluginWebSettingsService { - /// 保持已有插件目录映射,不读取或改写旧设置文件。 - public static PluginStorageContext Storage(string pluginId) => new(Path.Combine(PathManager.Inst.DataPath, - "PluginData", Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(pluginId))).ToLowerInvariant())); + /// 插件 ID 直接作为独占目录名,不迁移或读取旧哈希目录。 + public static PluginStorageContext Storage(string pluginId) + { + SingerPluginContract.ValidatePluginId(pluginId); + return new(Path.Combine(PathManager.Inst.DataPath, "PluginData", pluginId)); + } /// 映射已成功登记的插件,不加载未激活的 DLL。 public static RegisteredSingerPlugin? FindPlugin(string relativePath) diff --git a/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistration.cs b/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistration.cs index 8e320e58..16b00296 100644 --- a/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistration.cs +++ b/OpenUtauMobile/Services/SingerPlugins/SingerPluginRegistration.cs @@ -26,12 +26,8 @@ internal sealed class SingerPluginRegistration : ISingerPluginRegistrar internal SingerPluginRegistration(SingerPluginDescriptor plugin, Assembly assembly) { - RequireId(plugin.Id); + SingerPluginContract.ValidatePluginId(plugin.Id); RequireText(plugin.DisplayName, "插件名称"); - if (plugin.Id.Contains(':') || plugin.Id.StartsWith("opum.", StringComparison.Ordinal)) - { - throw new InvalidOperationException("插件 ID 不能包含冒号或使用宿主保留前缀 opum.。"); - } this.plugin = plugin; this.assembly = assembly; } diff --git a/OpenUtauMobile/Services/SingerPlugins/SingerPluginRuntime.cs b/OpenUtauMobile/Services/SingerPlugins/SingerPluginRuntime.cs index 4abfb7e1..dd4c6683 100644 --- a/OpenUtauMobile/Services/SingerPlugins/SingerPluginRuntime.cs +++ b/OpenUtauMobile/Services/SingerPlugins/SingerPluginRuntime.cs @@ -2,6 +2,7 @@ using System.Collections.Immutable; using System.IO; using System.Linq; +using Avalonia.Threading; using OpenUtau.Core; using OpenUtauMobile.Plugin.Abstractions; using Serilog; @@ -21,8 +22,8 @@ internal static ImmutableArray Roots() => PathManager.Inst.SingersPa internal static PluginStorageContext Storage(string pluginId) => PluginWebSettingsService.Storage(pluginId); - /// 将契约诊断写入宿主日志。 - internal sealed class PluginLog(string pluginId) : IPluginLog + /// 复用已绑定插件身份的宿主服务,分别实现日志和用户通知接口。 + internal sealed class PluginLog(string pluginId) : IPluginLog, IPluginNotifications { public void Write(PluginDiagnostic diagnostic, Exception? exception = null) { @@ -35,6 +36,33 @@ public void Write(PluginDiagnostic diagnostic, Exception? exception = null) Log.Write(level, exception, "Plugin {PluginId}: {Code}: {Message} ({Location})", pluginId, diagnostic.Code, diagnostic.Message, diagnostic.Location); } + + /// 同插件同代码更新原警告,后台调用经界面队列发布。 + public void PublishWarning(PluginWarning warning) + { + ArgumentNullException.ThrowIfNull(warning); + ArgumentException.ThrowIfNullOrWhiteSpace(warning.Code); + ArgumentException.ThrowIfNullOrWhiteSpace(warning.Message); + Write(new(warning.Code, warning.Message, PluginDiagnosticSeverity.Warning)); + Dispatcher.UIThread.Post(() => + { + string name = SingerPluginService.Registry.Snapshot.Plugins.TryGetValue(pluginId, out SingerPluginDescriptor? plugin) + ? plugin.DisplayName : pluginId; + DocManager.Inst.ExecuteCmd(new WarningNotification(Key(warning.Code), "Warning.Plugin.Title", + string.IsNullOrWhiteSpace(warning.Details) ? null : "Warning.Plugin.Detail", + name, warning.Message, warning.Details ?? string.Empty)); + }); + } + + /// 问题恢复后清除当前插件的指定警告,不能清除其他插件通知。 + public void ClearWarning(string code) + { + ArgumentException.ThrowIfNullOrWhiteSpace(code); + Dispatcher.UIThread.Post(() => DocManager.Inst.ExecuteCmd(new ClearWarningsNotification(Key(code)))); + } + + /// 插件 ID 不含冒号,固定前缀确保调用方不能跨插件清除通知。 + private string Key(string code) => $"plugin:{pluginId}:{code}"; } } } diff --git a/docs/PLUGIN_WEB_SETTINGS.md b/docs/PLUGIN_WEB_SETTINGS.md index ca61ff91..189bac63 100644 --- a/docs/PLUGIN_WEB_SETTINGS.md +++ b/docs/PLUGIN_WEB_SETTINGS.md @@ -33,7 +33,7 @@ public async ValueTask OpenWebSettingsAsync( - `DisposeAsync` 负责关闭本地监听、轮询和临时资源。取消令牌在离开页面时取消;不要把监听器生命周期交给浏览器标签页。 - `ReloadResourcesOnClose` 默认 true,释放会话后由宿主刷新歌手发现;不需要刷新时返回 false。 - 右上角按钮使用系统浏览器打开会话地址。此时内嵌页面仍拥有会话;返回管理页会结束会话,本地网页在外部浏览器中也随之失效。 -- `context.Storage.DataDirectory` 是插件独占的稳定目录,沿用 `DataPath/PluginData/<插件 ID 的 SHA256>` 映射。`ResourceDirectory` 是其中的 `Resources` 子目录。 +- `context.Storage.DataDirectory` 是插件独占的稳定目录,直接使用 `DataPath/PluginData/`;契约校验插件 ID 为合法的跨平台单级目录名。不迁移或读取旧哈希目录。`ResourceDirectory` 是其中的 `Resources` 子目录。 - 插件自行管理配置格式、凭据保护、读写并发和版本迁移;发现和安装上下文通过 `Storage` 提供相同目录。 宿主不解释网页的表单或账户协议,不通过 JavaScript 接收账户 token,也不提供可执行宿主命令的脚本桥。运行平台的文件和网络限制仍然适用。 From b02cbd9487cc7b56409d0a68ed43ac7606063572 Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Thu, 5 Nov 2026 00:17:11 +0800 Subject: [PATCH 18/45] =?UTF-8?q?fix:=20=E5=90=AF=E7=94=A8android=E6=9C=AC?= =?UTF-8?q?=E5=9C=B0http?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- OpenUtauMobile.Android/Properties/AndroidManifest.xml | 1 + .../Resources/xml/network_security_config.xml | 7 +++++++ OpenUtauMobile/ViewModels/ErrorDialogViewModel.cs | 6 +++--- 3 files changed, 11 insertions(+), 3 deletions(-) create mode 100644 OpenUtauMobile.Android/Resources/xml/network_security_config.xml diff --git a/OpenUtauMobile.Android/Properties/AndroidManifest.xml b/OpenUtauMobile.Android/Properties/AndroidManifest.xml index 6dafecd0..1ded9638 100644 --- a/OpenUtauMobile.Android/Properties/AndroidManifest.xml +++ b/OpenUtauMobile.Android/Properties/AndroidManifest.xml @@ -10,6 +10,7 @@ diff --git a/OpenUtauMobile.Android/Resources/xml/network_security_config.xml b/OpenUtauMobile.Android/Resources/xml/network_security_config.xml new file mode 100644 index 00000000..7036ef61 --- /dev/null +++ b/OpenUtauMobile.Android/Resources/xml/network_security_config.xml @@ -0,0 +1,7 @@ + + + + localhost + 127.0.0.1 + + diff --git a/OpenUtauMobile/ViewModels/ErrorDialogViewModel.cs b/OpenUtauMobile/ViewModels/ErrorDialogViewModel.cs index 0acacbbb..35172720 100644 --- a/OpenUtauMobile/ViewModels/ErrorDialogViewModel.cs +++ b/OpenUtauMobile/ViewModels/ErrorDialogViewModel.cs @@ -47,14 +47,14 @@ public ErrorDialogViewModel(ErrorMessageNotification notification) Message = HasMissingPackage ? string.Format(L.S("ErrorDialog.MissingPackage"), string.Join(", ", packages)) : string.IsNullOrWhiteSpace(mce.Message) ? mce.SubstanceException.Message : mce.Message; - Detail = mce.SubstanceException.ToString(); + Detail = mce.ShowStackTrace ? mce.SubstanceException.ToString() : string.Empty; } else if (notification.e != null) { Message = string.IsNullOrWhiteSpace(notification.message) - ? notification.e.Message + ? error!.Message : notification.message; - Detail = notification.e.ToString(); + Detail = error!.ToString(); } else { From 24b0f5a6cbd8e4280807bb8f733a23363acd7ac1 Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Thu, 5 Nov 2026 14:52:55 +0800 Subject: [PATCH 19/45] =?UTF-8?q?fix:=20Android=E5=B9=B3=E5=8F=B0=E5=8F=91?= =?UTF-8?q?=E5=B8=83=E8=A3=81=E5=89=AA=E4=BF=9D=E7=95=99=E5=9F=BA=E7=A1=80?= =?UTF-8?q?=E6=A1=86=E6=9E=B6=E7=A8=8B=E5=BA=8F=E9=9B=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../OpenUtauMobile.Android.csproj | 12 ++++++++++ .../SingerPlugins/PluginWebSettingsService.cs | 23 +++++++++++++++---- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/OpenUtauMobile.Android/OpenUtauMobile.Android.csproj b/OpenUtauMobile.Android/OpenUtauMobile.Android.csproj index 5b59a136..2178899a 100644 --- a/OpenUtauMobile.Android/OpenUtauMobile.Android.csproj +++ b/OpenUtauMobile.Android/OpenUtauMobile.Android.csproj @@ -13,6 +13,8 @@ 2G true true + + false @@ -49,5 +51,15 @@ Bind="false"/> + + + + + + + + diff --git a/OpenUtauMobile/Services/SingerPlugins/PluginWebSettingsService.cs b/OpenUtauMobile/Services/SingerPlugins/PluginWebSettingsService.cs index c46c5d61..d5383b49 100644 --- a/OpenUtauMobile/Services/SingerPlugins/PluginWebSettingsService.cs +++ b/OpenUtauMobile/Services/SingerPlugins/PluginWebSettingsService.cs @@ -1,10 +1,13 @@ using System; using System.IO; using System.Linq; +using System.Reflection.Metadata; +using System.Reflection.PortableExecutable; using System.Threading; using System.Threading.Tasks; using OpenUtau.Core; using OpenUtauMobile.Plugin.Abstractions; +using Serilog; namespace OpenUtauMobile.Services.SingerPlugins; @@ -18,13 +21,25 @@ public static PluginStorageContext Storage(string pluginId) return new(Path.Combine(PathManager.Inst.DataPath, "PluginData", pluginId)); } - /// 映射已成功登记的插件,不加载未激活的 DLL。 + /// 按模块标识映射已登记的插件,支持移动端映射路径及内存加载,不加载未激活的 DLL。 public static RegisteredSingerPlugin? FindPlugin(string relativePath) { string path = Path.GetFullPath(Path.Combine(PathManager.Inst.PluginsPath, relativePath)); - StringComparison comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; - return SingerPluginService.Registry.Snapshot.Instances.Values.FirstOrDefault(plugin => - !plugin.Assembly.IsDynamic && string.Equals(Path.GetFullPath(plugin.Assembly.Location), path, comparison)); + try + { + using FileStream stream = File.OpenRead(path); + using PEReader pe = new(stream); + if (!pe.HasMetadata) return null; + MetadataReader metadata = pe.GetMetadataReader(); + Guid moduleId = metadata.GetGuid(metadata.GetModuleDefinition().Mvid); + return SingerPluginService.Registry.Snapshot.Instances.Values.FirstOrDefault(plugin => + !plugin.Assembly.IsDynamic && plugin.Assembly.ManifestModule.ModuleVersionId == moduleId); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or BadImageFormatException) + { + Log.Debug(exception, "Failed to identify loaded plugin {Plugin}", relativePath); + return null; + } } private static PluginWebSettingsContext Context(string pluginId) => new(Storage(pluginId), new SingerPluginRuntime.PluginLog(pluginId)); From 6205a93fd3e2a5cc7068b79d621fb50f0df1f55a Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:59:06 +0800 Subject: [PATCH 20/45] =?UTF-8?q?performance:=20=E5=B0=86=E4=B8=80?= =?UTF-8?q?=E4=BA=9B=E6=93=8D=E4=BD=9C=E5=90=8E=E5=8F=B0=E5=BC=82=E6=AD=A5?= =?UTF-8?q?=E6=89=A7=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- OpenUtauMobile/Controls/AsyncAvatarImage.cs | 88 +++++++++ OpenUtauMobile/Controls/FilePickerPopup.axaml | 2 +- .../Controls/ProjectTemplatesPopup.axaml | 7 +- OpenUtauMobile/Controls/SingerList.axaml | 12 +- OpenUtauMobile/Services/BitmapLoader.cs | 31 ++++ .../Services/DocumentValidationScheduler.cs | 99 ++++++++++ .../Installation/SingerInstallController.cs | 4 + .../Services/Tracks/TrackImportService.cs | 4 +- .../Services/Tracks/TrackImportSource.cs | 8 +- OpenUtauMobile/Tools/Converters.cs | 36 +--- OpenUtauMobile/ViewModels/EditorViewModel.cs | 12 +- .../ViewModels/FilePickerBaseViewModel.cs | 171 +++++++++++------- OpenUtauMobile/ViewModels/FilePickerEntry.cs | 2 + .../ViewModels/FilePickerPopupViewModel.cs | 4 +- .../ViewModels/FileSavePickerViewModel.cs | 34 +++- .../ViewModels/FolderPickerViewModel.cs | 8 +- OpenUtauMobile/ViewModels/HomeViewModel.cs | 13 +- .../ViewModels/ImportTracksViewModel.cs | 3 +- .../ViewModels/MultiFilePickerViewModel.cs | 2 +- .../ViewModels/PluginSingerSetupViewModel.cs | 51 ++++-- .../ViewModels/ProjectTemplatesViewModel.cs | 59 +++++- .../ViewModels/TrackHeaderViewModel.cs | 50 +++-- OpenUtauMobile/Views/MainView.axaml.cs | 11 +- 23 files changed, 533 insertions(+), 178 deletions(-) create mode 100644 OpenUtauMobile/Controls/AsyncAvatarImage.cs create mode 100644 OpenUtauMobile/Services/BitmapLoader.cs create mode 100644 OpenUtauMobile/Services/DocumentValidationScheduler.cs diff --git a/OpenUtauMobile/Controls/AsyncAvatarImage.cs b/OpenUtauMobile/Controls/AsyncAvatarImage.cs new file mode 100644 index 00000000..058c0ebc --- /dev/null +++ b/OpenUtauMobile/Controls/AsyncAvatarImage.cs @@ -0,0 +1,88 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Media.Imaging; +using OpenUtauMobile.Services; + +namespace OpenUtauMobile.Controls; + +/// 后台解码歌手头像,控件只在 UI 线程接收和释放当前图片。 +public sealed class AsyncAvatarImage : Image +{ + public static readonly StyledProperty DataProperty = + AvaloniaProperty.Register(nameof(Data)); + + private CancellationTokenSource? _loading; + private Bitmap? _bitmap; + private bool _attached; + + /// 已经预读到内存的只读头像数据,不触发歌手实例的文件加载。 + public byte[]? Data + { + get => GetValue(DataProperty); + set => SetValue(DataProperty, value); + } + + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) + { + base.OnPropertyChanged(change); + if (change.Property == DataProperty && _attached) RefreshImage(); + } + + protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) + { + base.OnAttachedToVisualTree(e); + _attached = true; + RefreshImage(); + } + + protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e) + { + _attached = false; + ClearImage(); + base.OnDetachedFromVisualTree(e); + } + + /// 替换头像或卸载时取消旧请求,图片解绑后再释放。 + private void ClearImage() + { + _loading?.Cancel(); + _loading = null; + Source = null; + _bitmap?.Dispose(); + _bitmap = null; + } + + /// 只有已挂载的控件才请求解码,等待期间保留宿主的文字头像。 + private void RefreshImage() + { + ClearImage(); + if (Data is { Length: > 0 } data) _ = LoadAsync(data); + } + + /// 完成后检查请求身份,切换和卸载后返回的图片立即释放。 + private async Task LoadAsync(byte[] data) + { + using CancellationTokenSource loading = new(); + _loading = loading; + try + { + Bitmap bitmap = await BitmapLoader.DecodeAsync(data, loading.Token); + if (!_attached || loading.IsCancellationRequested || !ReferenceEquals(_loading, loading)) + { + bitmap.Dispose(); + return; + } + _bitmap = bitmap; + Source = bitmap; + } + catch (OperationCanceledException) when (loading.IsCancellationRequested) { } + catch (Exception) { /* 无效图片继续使用宿主的文字头像。 */ } + finally + { + if (ReferenceEquals(_loading, loading)) _loading = null; + } + } +} diff --git a/OpenUtauMobile/Controls/FilePickerPopup.axaml b/OpenUtauMobile/Controls/FilePickerPopup.axaml index 427782c1..9b259494 100644 --- a/OpenUtauMobile/Controls/FilePickerPopup.axaml +++ b/OpenUtauMobile/Controls/FilePickerPopup.axaml @@ -214,7 +214,7 @@ FontSize="14" TextTrimming="CharacterEllipsis" /> diff --git a/OpenUtauMobile/Controls/ProjectTemplatesPopup.axaml b/OpenUtauMobile/Controls/ProjectTemplatesPopup.axaml index b564e53b..4d4e7696 100644 --- a/OpenUtauMobile/Controls/ProjectTemplatesPopup.axaml +++ b/OpenUtauMobile/Controls/ProjectTemplatesPopup.axaml @@ -1,6 +1,5 @@ - - + + + + diff --git a/OpenUtauMobile/Controls/SingerList.axaml b/OpenUtauMobile/Controls/SingerList.axaml index ded0f34d..ec9218fe 100644 --- a/OpenUtauMobile/Controls/SingerList.axaml +++ b/OpenUtauMobile/Controls/SingerList.axaml @@ -15,7 +15,6 @@ - @@ -66,13 +65,10 @@ Foreground="{Binding SingerType, Converter={StaticResource SingerTypeToColor}}" /> - - - - - + + + + diff --git a/OpenUtauMobile/Services/BitmapLoader.cs b/OpenUtauMobile/Services/BitmapLoader.cs new file mode 100644 index 00000000..5b3b16ba --- /dev/null +++ b/OpenUtauMobile/Services/BitmapLoader.cs @@ -0,0 +1,31 @@ +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Avalonia.Media.Imaging; + +namespace OpenUtauMobile.Services; + +/// 在后台解码独立图片数据,限制并行数以控制移动设备的内存峰值。 +internal static class BitmapLoader +{ + private static readonly SemaphoreSlim DecodeSlots = new(2, 2); + + /// 字节数据在解码期间保持只读;调用方拥有返回图片并负责释放晚到结果。 + public static async Task DecodeAsync(byte[] data, CancellationToken cancellationToken = default) + { + await DecodeSlots.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + return await Task.Run(() => + { + cancellationToken.ThrowIfCancellationRequested(); + using MemoryStream stream = new(data); + return new Bitmap(stream); + }, cancellationToken).ConfigureAwait(false); + } + finally + { + DecodeSlots.Release(); + } + } +} diff --git a/OpenUtauMobile/Services/DocumentValidationScheduler.cs b/OpenUtauMobile/Services/DocumentValidationScheduler.cs new file mode 100644 index 00000000..9d56bacc --- /dev/null +++ b/OpenUtauMobile/Services/DocumentValidationScheduler.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using Avalonia.Controls; +using Avalonia.Threading; +using OpenUtau.Core; + +namespace OpenUtauMobile.Services; + +/// 把文档校验合并到下一动画帧,并在停止出帧或宿主卸载时完成待处理校验。 +internal sealed class DocumentValidationScheduler : IDisposable +{ + private readonly TopLevel _topLevel; + private readonly Action _requestFrame; + private readonly HashSet _pendingActions = []; + private readonly DispatcherTimer _fallbackTimer; + private int _generation; + private bool _isDisposed; + + /// 在 UI 线程为当前主视图接入 Core 已有的帧调度接口。 + public DocumentValidationScheduler(TopLevel topLevel) + { + Dispatcher.UIThread.VerifyAccess(); + _topLevel = topLevel; + _requestFrame = RequestFrame; + // 窗口隐藏或 Android 暂停出帧时也不能无限推迟校验;仅有待处理工作时启动。 + _fallbackTimer = new DispatcherTimer(DispatcherPriority.Background) + { + Interval = TimeSpan.FromMilliseconds(100) + }; + _fallbackTimer.Tick += OnFallbackTick; + DocManager.Inst.RequestFrame = _requestFrame; + } + + /// 合并同一帧内的重复冲刷请求,实际校验始终保留在 UI 线程。 + private void RequestFrame(Action action) + { + Dispatcher.UIThread.VerifyAccess(); + if (_isDisposed) + { + action(); + return; + } + + _pendingActions.Add(action); + if (_fallbackTimer.IsEnabled) + { + return; + } + + int generation = ++_generation; + _fallbackTimer.Start(); + _topLevel.RequestAnimationFrame(_ => + { + // 旧宿主、超时兜底以及上一次冲刷遗留的帧回调不能提前执行新一批校验。 + if (!_isDisposed && generation == _generation) + { + Flush(); + } + }); + } + + /// 没有动画帧到来时,在下一次可执行的 UI 调度中完成校验。 + private void OnFallbackTick(object? sender, EventArgs e) + { + Flush(); + } + + /// 先清理本批调度状态,再执行回调,允许校验过程中产生下一批请求。 + private void Flush() + { + _fallbackTimer.Stop(); + _generation++; + Action[] actions = [.. _pendingActions]; + _pendingActions.Clear(); + foreach (Action action in actions) + { + action(); + } + } + + /// 卸载宿主时撤销接线并立即冲刷,避免遗留回调或丢失待校验状态。 + public void Dispose() + { + Dispatcher.UIThread.VerifyAccess(); + if (_isDisposed) + { + return; + } + + _isDisposed = true; + if (DocManager.Inst.RequestFrame == _requestFrame) + { + DocManager.Inst.RequestFrame = null; + } + + _fallbackTimer.Tick -= OnFallbackTick; + Flush(); + } +} diff --git a/OpenUtauMobile/Services/SingerPlugins/Installation/SingerInstallController.cs b/OpenUtauMobile/Services/SingerPlugins/Installation/SingerInstallController.cs index 6e54b4d7..9b20217e 100644 --- a/OpenUtauMobile/Services/SingerPlugins/Installation/SingerInstallController.cs +++ b/OpenUtauMobile/Services/SingerPlugins/Installation/SingerInstallController.cs @@ -35,6 +35,10 @@ public sealed class SingerInstallController : IAsyncDisposable /// 预览资源只能从本会话缓存读取。 public string PreviewPath(string relativePath) => context.Workspace.GetPath(relativePath); + /// 在已有会话串行器内后台预读图片,清理缓存前完成文件访问。 + public Task ReadPreviewAsync(string relativePath) => RunAsync(token => + File.ReadAllBytesAsync(PreviewPath(relativePath), token)); + public SingerInstallController(RegisteredSingerInstaller installer, string sourcePath) { this.installer = installer; diff --git a/OpenUtauMobile/Services/Tracks/TrackImportService.cs b/OpenUtauMobile/Services/Tracks/TrackImportService.cs index ab9b3004..62bb4027 100644 --- a/OpenUtauMobile/Services/Tracks/TrackImportService.cs +++ b/OpenUtauMobile/Services/Tracks/TrackImportService.cs @@ -30,12 +30,14 @@ public static IReadOnlyList ReadFiles(IEnumerable pat throw new InvalidDataException("Invalid source track index."); } // 来源读取在后台执行,等音频加载终止后再展示确认页,避免遗漏晚到的解码失败。 + List missingAudio = []; foreach (UWavePart part in project.parts.OfType()) { try { part.Peaks?.GetAwaiter().GetResult(); } catch (Exception) { /* 片段保留;确认页根据 Peaks 终态显示不可读提示。 */ } + if (!File.Exists(part.FilePath)) missingAudio.Add(part); } - sources.Add(new TrackImportSource(path, project)); + sources.Add(new TrackImportSource(path, project, missingAudio: missingAudio)); } catch (Exception exception) { diff --git a/OpenUtauMobile/Services/Tracks/TrackImportSource.cs b/OpenUtauMobile/Services/Tracks/TrackImportSource.cs index 72c3134f..fc4ebae2 100644 --- a/OpenUtauMobile/Services/Tracks/TrackImportSource.cs +++ b/OpenUtauMobile/Services/Tracks/TrackImportSource.cs @@ -9,17 +9,23 @@ namespace OpenUtauMobile.Services.Tracks; /// 一次读取的来源工程及其诊断;不持有当前编辑工程。 public sealed class TrackImportSource { + private readonly HashSet missingAudio; public string Path { get; } public string Name => System.IO.Path.GetFileName(Path); public UProject? Project { get; } public Exception? Error { get; } - public TrackImportSource(string path, UProject? project, Exception? error = null) + public TrackImportSource(string path, UProject? project, Exception? error = null, + IEnumerable? missingAudio = null) { Path = path; Project = project; Error = error; + this.missingAudio = [.. missingAudio ?? []]; } + + /// 使用来源读取阶段的文件状态,确认行构造时不再访问磁盘。 + public bool IsAudioMissing(UWavePart part) => missingAudio.Contains(part); } /// 确认后的轨道选择,保存来源索引,避免轨道重编号影响选择。 diff --git a/OpenUtauMobile/Tools/Converters.cs b/OpenUtauMobile/Tools/Converters.cs index 569df686..68923789 100644 --- a/OpenUtauMobile/Tools/Converters.cs +++ b/OpenUtauMobile/Tools/Converters.cs @@ -6,7 +6,6 @@ using Avalonia; using Avalonia.Controls; using Avalonia.Data.Converters; -using Avalonia.Media.Imaging; using OpenUtau.Core.Ustx; using OpenUtauMobile.Themes.OpenUtauMobile.Runtime; using OpenUtauMobile.Themes.OpenUtauMobile.Runtime.Resources; @@ -111,35 +110,6 @@ public object ConvertBack(object? value, Type targetType, object? parameter, Cul => AvaloniaProperty.UnsetValue; } -/// -/// byte[] => Bitmap (avatar image) -/// -public class AvatarDataToBitmapConverter : IValueConverter -{ - public static readonly AvatarDataToBitmapConverter Instance = new(); - - public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) - { - if (value is byte[] { Length: > 0 } data) - { - try - { - using MemoryStream ms = new MemoryStream(data); - return new Bitmap(ms); - } - catch - { - return null; - } - } - - return null; - } - - public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) - => AvaloniaProperty.UnsetValue; -} - /// /// Returns true when the value is non-null — used to toggle avatar image visibility. /// @@ -216,8 +186,7 @@ public object ConvertBack(object? value, Type targetType, object? parameter, Cul } /// -/// FileSystemInfo => human-readable file size string (e.g. "1.2 MB"). -/// Returns empty string for directories. +/// 预读的文件字节数转为可读大小;转换期间不访问磁盘。 /// public class FileSizeConverter : IValueConverter { @@ -225,8 +194,7 @@ public class FileSizeConverter : IValueConverter public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) { - if (value is not FileInfo fi) return string.Empty; - long bytes = fi.Length; + if (value is not long bytes) return string.Empty; return bytes switch { < 1024 => $"{bytes} B", diff --git a/OpenUtauMobile/ViewModels/EditorViewModel.cs b/OpenUtauMobile/ViewModels/EditorViewModel.cs index 22c6a8be..747884e6 100644 --- a/OpenUtauMobile/ViewModels/EditorViewModel.cs +++ b/OpenUtauMobile/ViewModels/EditorViewModel.cs @@ -1760,8 +1760,8 @@ private async Task ExecuteAudioExportAsync(ExportAudioRequest request) case ExportAudioMode.Mixdown: await PlaybackManager.Inst.RenderMixdown(DocManager.Inst.Project, request.ExportPath); await ServiceHub.FlushFileSystemAsync(); - success = File.Exists(request.ExportPath) && - File.GetLastWriteTimeUtc(request.ExportPath) >= startedAt.AddSeconds(-1); + success = await Task.Run(() => File.Exists(request.ExportPath) && + File.GetLastWriteTimeUtc(request.ExportPath) >= startedAt.AddSeconds(-1)); ToastService.Enqueue(L.S(success ? "ExportAudioPopup.Toast.Success.Mixdown" : "ExportAudioPopup.Toast.Failed")); @@ -1772,10 +1772,10 @@ private async Task ExecuteAudioExportAsync(ExportAudioRequest request) await ServiceHub.FlushFileSystemAsync(); string? trackDir = Path.GetDirectoryName(request.ExportPath); string trackBase = Path.GetFileNameWithoutExtension(request.ExportPath); - success = !string.IsNullOrWhiteSpace(trackDir) && + success = await Task.Run(() => !string.IsNullOrWhiteSpace(trackDir) && Directory.Exists(trackDir) && - Directory.GetFiles(trackDir, $"{trackBase}_*.wav") - .Any(file => File.GetLastWriteTimeUtc(file) >= startedAt.AddSeconds(-1)); + Directory.EnumerateFiles(trackDir, $"{trackBase}_*.wav") + .Any(file => File.GetLastWriteTimeUtc(file) >= startedAt.AddSeconds(-1))); ToastService.Enqueue(L.S(success ? "ExportAudioPopup.Toast.Success.Tracks" : "ExportAudioPopup.Toast.Failed")); @@ -2517,4 +2517,4 @@ public void Dispose() StopCommand.Dispose(); // 释放停止命令 GC.SuppressFinalize(this); // 告知 GC 无需调用终结器 } -} \ No newline at end of file +} diff --git a/OpenUtauMobile/ViewModels/FilePickerBaseViewModel.cs b/OpenUtauMobile/ViewModels/FilePickerBaseViewModel.cs index cbc3ee16..c3e6555c 100644 --- a/OpenUtauMobile/ViewModels/FilePickerBaseViewModel.cs +++ b/OpenUtauMobile/ViewModels/FilePickerBaseViewModel.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Globalization; using System.IO; using System.Linq; using System.Reactive; @@ -42,6 +43,10 @@ public abstract class FilePickerBaseViewModel : PopupViewModelBase [Reactive] public bool IsLoading { get; set; } + /// 后台检查确认当前目录存在,供选择和保存命令使用。 + [Reactive] + public bool IsDirectoryAvailable { get; private set; } + /// 是否显示空状态面板(无内容或异常时) [Reactive] public bool ShowEmptyState { get; set; } @@ -71,6 +76,12 @@ public abstract class FilePickerBaseViewModel : PopupViewModelBase protected readonly string[] Filters; private CancellationTokenSource _cts = new(); + private Dictionary _fileSizes = []; + private bool _initialPathPending = true; + private bool _publishingPath; + + /// 选择器关闭后不再接收晚到的磁盘查询结果。 + protected bool IsClosed { get; private set; } /// /// 仅供设计器使用 @@ -80,29 +91,24 @@ protected FilePickerBaseViewModel() : this("文件浏览器", []) { } protected FilePickerBaseViewModel(string title, string[] filters, string initialPath = "") { Title = title; - Filters = filters; + Filters = [.. filters]; AllItems.CollectionChanged += (_, _) => { Entries.Clear(); foreach (FileSystemInfo item in AllItems) { - Entries.Add(CreateEntry(item)); + FilePickerEntry entry = CreateEntry(item); + entry.Size = _fileSizes.TryGetValue(item, out long size) ? size : null; + Entries.Add(entry); } }; - if (FilePickerWorkspace.IsSandboxed) - initialPath = FilePickerWorkspace.NormalizeDirectory(initialPath); - if (!Directory.Exists(initialPath)) - initialPath = string.Empty; - if (!string.IsNullOrEmpty(initialPath)) CurrentPath = initialPath; else - CurrentPath = FilePickerWorkspace.IsSandboxed ? FilePickerWorkspace.Root : OperatingSystem.IsAndroid() - ? "/sdcard" - : Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + CurrentPath = DefaultDirectory; - // 构造时先置为加载中,等 View 附加到视觉树后再真正开始 I/O + // 构造时立即显示加载状态,目录 I/O 由下方异步请求在后台执行。 IsLoading = true; this.WhenAnyValue(x => x.IsLoading) @@ -112,76 +118,54 @@ protected FilePickerBaseViewModel(string title, string[] filters, string initial }); this.WhenAnyValue(x => x.CurrentPath) - .Subscribe(_ => RefreshItemsAsync().ConfigureAwait(false)); + .Subscribe(path => + { + if (!_publishingPath) _ = RefreshItemsAsync(); + }); SelectItemCommand = ReactiveCommand.Create(SelectItem); GoUpCommand = ReactiveCommand.Create(GoUp); CloseCommand = ReactiveCommand.Create(RequestBack); } + /// 在后台完成路径检查、枚举和文件元数据读取,UI 仅发布当前请求。 public async Task RefreshItemsAsync() { + if (IsClosed) return; // 先取消旧目录请求,路径无效时也不能让旧列表重新出现。 CancellationTokenSource previous = _cts; _cts = new CancellationTokenSource(); CancellationToken token = _cts.Token; + string requestedPath = CurrentPath; + bool initialPath = _initialPathPending; + _initialPathPending = false; + bool showFiles = ShowFiles; + IsLoading = true; + IsDirectoryAvailable = false; + IsAccessDenied = false; await previous.CancelAsync(); previous.Dispose(); if (token.IsCancellationRequested) return; - if (FilePickerWorkspace.IsSandboxed) - { - string allowedPath = FilePickerWorkspace.NormalizeDirectory(CurrentPath); - if (allowedPath != CurrentPath) - { - CurrentPath = allowedPath; - return; - } - } - if (!Directory.Exists(CurrentPath)) - { - AllItems.Clear(); - IsLoading = false; - return; - } - - IsLoading = true; - IsAccessDenied = false; - try { - DirectoryInfo currentDir = new(CurrentPath); - - List items = await Task.Run(() => - { - token.ThrowIfCancellationRequested(); - IEnumerable dirs = currentDir.GetDirectories() - .LocalizedOrderBy(d => d.Name); - IEnumerable result = dirs; - if (ShowFiles) - { - IEnumerable files = currentDir.GetFiles() - .Where(f => MatchesFilter(f.Name)) - .LocalizedOrderBy(f => f.Name); - result = result.Concat(files); - } - - return result.ToList(); - }, token); - - if (token.IsCancellationRequested) return; - - AllItems.Load(items); - - if (items.Count == 0) + // 后台排序使用本次请求的文化快照,不读取随后可能变化的全局偏好。 + string sortingOrder = Preferences.Default.SortingOrder + ?? LocalizationManager.ResolveLanguagePreference(Preferences.Default.Language); + LocalizedComparer comparer = new(CultureInfo.GetCultureInfo(sortingOrder)); + DirectorySnapshot snapshot = await Task.Run( + () => ReadDirectory(requestedPath, initialPath, showFiles, comparer, token), token); + if (token.IsCancellationRequested || IsClosed) return; + _publishingPath = true; + try { CurrentPath = snapshot.Path; } + finally { _publishingPath = false; } + IsDirectoryAvailable = snapshot.Exists; + _fileSizes = snapshot.Sizes; + AllItems.Load(snapshot.Items); + + if (snapshot.Items.Length == 0) { - bool hasAnyContent = await Task.Run(() => - currentDir.GetFiles().Length > 0 || currentDir.GetDirectories().Length > 0, - token); - - if (token.IsCancellationRequested) return; - - EmptyStateMessage = hasAnyContent + EmptyStateMessage = snapshot.HasAnyContent ? L.S("FilePicker.NoMatch") : L.S("FilePicker.Empty"); ShowEmptyState = true; @@ -197,7 +181,7 @@ public async Task RefreshItemsAsync() } catch (UnauthorizedAccessException) { - if (token.IsCancellationRequested) return; + if (token.IsCancellationRequested || IsClosed) return; AllItems.Clear(); EmptyStateMessage = L.S("FilePicker.AccessDenied"); IsAccessDenied = true; @@ -206,7 +190,7 @@ public async Task RefreshItemsAsync() } catch (Exception ex) { - if (token.IsCancellationRequested) return; + if (token.IsCancellationRequested || IsClosed) return; AllItems.Clear(); EmptyStateMessage = L.S("FilePicker.AccessDenied"); IsAccessDenied = true; @@ -215,11 +199,68 @@ public async Task RefreshItemsAsync() } finally { - if (!token.IsCancellationRequested) + if (!token.IsCancellationRequested && !IsClosed) IsLoading = false; } } + /// 后台读取目录快照,避免行绑定再次访问文件系统。 + private DirectorySnapshot ReadDirectory(string path, bool initialPath, bool showFiles, + IComparer comparer, CancellationToken token) + { + token.ThrowIfCancellationRequested(); + if (FilePickerWorkspace.IsSandboxed) path = FilePickerWorkspace.NormalizeDirectory(path); + if (initialPath && !Directory.Exists(path)) path = DefaultDirectory; + bool exists = Directory.Exists(path); + if (!exists) return new(path, false, [], [], false); + + DirectoryInfo directory = new(path); + List directories = []; + foreach (DirectoryInfo child in directory.EnumerateDirectories()) + { + token.ThrowIfCancellationRequested(); + directories.Add(child); + } + List files = []; + Dictionary sizes = []; + bool hasAnyContent = directories.Count > 0; + foreach (FileInfo file in directory.EnumerateFiles()) + { + token.ThrowIfCancellationRequested(); + hasAnyContent = true; + if (!showFiles) break; + if (!MatchesFilter(file.Name)) continue; + files.Add(file); + try { sizes[file] = file.Length; } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + } + token.ThrowIfCancellationRequested(); + return new(path, true, + [.. directories.OrderBy(item => item.Name, comparer), .. files.OrderBy(item => item.Name, comparer)], + sizes, hasAnyContent); + } + + /// 默认浏览目录仅做路径计算,不在 UI 检查磁盘。 + private static string DefaultDirectory => FilePickerWorkspace.IsSandboxed ? FilePickerWorkspace.Root + : OperatingSystem.IsAndroid() ? "/sdcard" + : Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + + /// 目录内容及预读的文件大小,交给 UI 时不再依赖文件句柄。 + private sealed record DirectorySnapshot(string Path, bool Exists, FileSystemInfo[] Items, + Dictionary Sizes, bool HasAnyContent); + + /// 关闭选择器并停止发布正在读取的目录结果。 + protected void ClosePicker(object? result) + { + if (IsClosed) return; + IsClosed = true; + _cts.Cancel(); + RaiseClose(result); + } + + public override void RequestBack() => ClosePicker(null); + /// /// 子类可重写此属性以控制列表中是否显示文件。 /// 文件夹模式设为 false,仅显示子目录。 diff --git a/OpenUtauMobile/ViewModels/FilePickerEntry.cs b/OpenUtauMobile/ViewModels/FilePickerEntry.cs index ecda508e..7e5f7ddb 100644 --- a/OpenUtauMobile/ViewModels/FilePickerEntry.cs +++ b/OpenUtauMobile/ViewModels/FilePickerEntry.cs @@ -12,6 +12,8 @@ public sealed class FilePickerEntry : ReactiveObject public FileSystemInfo Item { get; } public string Name => Item.Name; + /// 目录读取阶段预取的大小;文件消失或无法读取时为空。 + public long? Size { get; internal set; } public bool CanSelect => Item is FileInfo && selectionChanged != null; public bool IsSelected diff --git a/OpenUtauMobile/ViewModels/FilePickerPopupViewModel.cs b/OpenUtauMobile/ViewModels/FilePickerPopupViewModel.cs index bf4a449c..858c75ff 100644 --- a/OpenUtauMobile/ViewModels/FilePickerPopupViewModel.cs +++ b/OpenUtauMobile/ViewModels/FilePickerPopupViewModel.cs @@ -21,6 +21,6 @@ protected override void SelectItem(FileSystemInfo item) if (item is DirectoryInfo dir) CurrentPath = dir.FullName; else if (item is FileInfo file) - RaiseClose(file.FullName); + ClosePicker(file.FullName); } -} \ No newline at end of file +} diff --git a/OpenUtauMobile/ViewModels/FileSavePickerViewModel.cs b/OpenUtauMobile/ViewModels/FileSavePickerViewModel.cs index e075fe5f..5379b2b3 100644 --- a/OpenUtauMobile/ViewModels/FileSavePickerViewModel.cs +++ b/OpenUtauMobile/ViewModels/FileSavePickerViewModel.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Reactive; +using System.Threading.Tasks; using OpenUtauMobile.Helpers; using ReactiveUI; using ReactiveUI.Fody.Helpers; @@ -14,6 +15,7 @@ namespace OpenUtauMobile.ViewModels; /// public class FileSavePickerViewModel : FilePickerBaseViewModel { + private int _previewVersion; public override FilePickerMode Mode => FilePickerMode.SaveFile; /// 用户输入的文件名(不含后缀)。 @@ -49,11 +51,11 @@ public FileSavePickerViewModel( // 实时更新预览路径 this.WhenAnyValue(x => x.CurrentPath, x => x.FileName) - .Subscribe(_ => UpdatePreviewPath()); + .Subscribe(change => { _ = UpdatePreviewPathAsync(); }); - IObservable canSave = this.WhenAnyValue(x => x.FileName, x => x.CurrentPath, - (name, path) => IsValidFileName(name) && Directory.Exists(path)); - SaveCommand = ReactiveCommand.Create(Save, canSave); + IObservable canSave = this.WhenAnyValue(x => x.FileName, x => x.IsDirectoryAvailable, x => x.IsLoading, + (name, available, loading) => IsValidFileName(name) && available && !loading); + SaveCommand = ReactiveCommand.CreateFromTask(SaveAsync, canSave); } protected override void SelectItem(FileSystemInfo item) @@ -65,8 +67,10 @@ protected override void SelectItem(FileSystemInfo item) FileName = Path.GetFileNameWithoutExtension(file.Name); } - private void UpdatePreviewPath() + /// 路径预览立即更新,磁盘存在性检查防抖后在后台执行。 + private async Task UpdatePreviewPathAsync() { + int version = ++_previewVersion; if (!IsValidFileName(FileName)) { PreviewFullPath = string.Empty; @@ -79,7 +83,13 @@ private void UpdatePreviewPath() ? FileName : FileName + Extension; PreviewFullPath = Path.Combine(CurrentPath, nameWithExt); - if (File.Exists(PreviewFullPath)) + string previewPath = PreviewFullPath; + IsShowingWarningMessage = false; + await Task.Delay(150); + if (IsClosed || version != _previewVersion) return; + bool exists = await Task.Run(() => File.Exists(previewPath)); + if (IsClosed || version != _previewVersion) return; + if (exists) { WarningMessage = L.S("FilePicker.OverwriteWarning"); IsShowingWarningMessage = true; @@ -90,10 +100,16 @@ private void UpdatePreviewPath() } } - private void Save() + /// 最终确认目录仍存在,等待期间路径变化或关闭则放弃本次提交。 + private async Task SaveAsync() { - if (!IsValidFileName(FileName) || !Directory.Exists(CurrentPath)) return; - RaiseClose(PreviewFullPath); + if (!IsValidFileName(FileName) || IsClosed) return; + string directory = CurrentPath; + string previewPath = PreviewFullPath; + int version = _previewVersion; + bool exists = await Task.Run(() => Directory.Exists(directory)); + if (!exists || IsClosed || version != _previewVersion) return; + ClosePicker(previewPath); } private static bool IsValidFileName(string name) => diff --git a/OpenUtauMobile/ViewModels/FolderPickerViewModel.cs b/OpenUtauMobile/ViewModels/FolderPickerViewModel.cs index 96a3710e..92676ce4 100644 --- a/OpenUtauMobile/ViewModels/FolderPickerViewModel.cs +++ b/OpenUtauMobile/ViewModels/FolderPickerViewModel.cs @@ -21,7 +21,9 @@ public class FolderPickerViewModel : FilePickerBaseViewModel public FolderPickerViewModel(string title, string initialPath = "") : base(title, filters: [], initialPath) { - SelectCurrentFolderCommand = ReactiveCommand.Create(SelectCurrentFolder); + SelectCurrentFolderCommand = ReactiveCommand.Create(SelectCurrentFolder, + this.WhenAnyValue(model => model.IsDirectoryAvailable, model => model.IsLoading, + (available, loading) => available && !loading)); } protected override void SelectItem(FileSystemInfo item) @@ -32,5 +34,5 @@ protected override void SelectItem(FileSystemInfo item) } private void SelectCurrentFolder() - => RaiseClose(CurrentPath); -} \ No newline at end of file + => ClosePicker(CurrentPath); +} diff --git a/OpenUtauMobile/ViewModels/HomeViewModel.cs b/OpenUtauMobile/ViewModels/HomeViewModel.cs index b83228f0..c5d07e34 100644 --- a/OpenUtauMobile/ViewModels/HomeViewModel.cs +++ b/OpenUtauMobile/ViewModels/HomeViewModel.cs @@ -68,7 +68,7 @@ public class HomeViewModel : NavigateViewModelBase public HomeViewModel(MainViewModel navigator) : base(navigator) { - NewCommand = ReactiveCommand.Create(New); + NewCommand = ReactiveCommand.CreateFromTask(NewAsync); OpenCommand = ReactiveCommand.Create(Open); SingersCommand = ReactiveCommand.Create(Singers); OptionsCommand = ReactiveCommand.Create(Options); @@ -106,10 +106,13 @@ private void RemoveRecent(string path) RecentProjects.Remove(path); } - private void New() + /// 后台检查默认模板,页面已离开时不再触发导航。 + private async Task NewAsync() { string defaultTemplate = Path.Combine(PathManager.Inst.TemplatesPath, "default.ustx"); - Navigator.Navigate(File.Exists(defaultTemplate) + bool exists = await Task.Run(() => File.Exists(defaultTemplate)); + if (Navigator.CurrentViewModel != this) return; + Navigator.Navigate(exists ? new EditorViewModel(Navigator, new ProjectOpenOptions(defaultTemplate, ProjectOpenKind.Template)) : new EditorViewModel(Navigator)); @@ -188,7 +191,9 @@ private async Task Initialize() RecoveryBannerDismissed = false; string recPath = Preferences.Default.RecoveryPath; - if (!string.IsNullOrWhiteSpace(recPath) && File.Exists(recPath)) + bool recoveryExists = !string.IsNullOrWhiteSpace(recPath) && await Task.Run(() => File.Exists(recPath)); + if (Navigator.CurrentViewModel != this) return; + if (recoveryExists) { RecoveryPath = recPath; HasRecovery = true; diff --git a/OpenUtauMobile/ViewModels/ImportTracksViewModel.cs b/OpenUtauMobile/ViewModels/ImportTracksViewModel.cs index 94763d0e..9039cb1f 100644 --- a/OpenUtauMobile/ViewModels/ImportTracksViewModel.cs +++ b/OpenUtauMobile/ViewModels/ImportTracksViewModel.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.IO; using System.Linq; using System.Reactive; using OpenUtau.Core.Ustx; @@ -176,7 +175,7 @@ public ImportTrackViewModel(TrackImportSelection selection, Action changed) } foreach (UWavePart part in parts.OfType()) { - if (!File.Exists(part.FilePath)) + if (selection.Source.IsAudioMissing(part)) warnings.Add(string.Format(L.S("ImportTracks.MissingAudio"), part.FilePath)); else if (part.Peaks is { IsCompleted: true } peaks && (!peaks.IsCompletedSuccessfully || peaks.Result == null && part.Samples == null)) diff --git a/OpenUtauMobile/ViewModels/MultiFilePickerViewModel.cs b/OpenUtauMobile/ViewModels/MultiFilePickerViewModel.cs index 2497d1c3..26a77828 100644 --- a/OpenUtauMobile/ViewModels/MultiFilePickerViewModel.cs +++ b/OpenUtauMobile/ViewModels/MultiFilePickerViewModel.cs @@ -21,7 +21,7 @@ public sealed class MultiFilePickerViewModel : FilePickerBaseViewModel public MultiFilePickerViewModel(string title, string[] filters) : base(title, filters) { - ConfirmCommand = ReactiveCommand.Create(() => RaiseClose(selected.ToArray()), + ConfirmCommand = ReactiveCommand.Create(() => ClosePicker((string[])[.. selected]), this.WhenAnyValue(model => model.CanConfirm)); } diff --git a/OpenUtauMobile/ViewModels/PluginSingerSetupViewModel.cs b/OpenUtauMobile/ViewModels/PluginSingerSetupViewModel.cs index 6b020b2a..e0b5c1a2 100644 --- a/OpenUtauMobile/ViewModels/PluginSingerSetupViewModel.cs +++ b/OpenUtauMobile/ViewModels/PluginSingerSetupViewModel.cs @@ -1,13 +1,13 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using System.IO; using System.Linq; using System.Reactive; using System.Threading.Tasks; using Avalonia.Media.Imaging; using OpenUtauMobile.Helpers; using OpenUtauMobile.Plugin.Abstractions; +using OpenUtauMobile.Services; using OpenUtauMobile.Services.SingerPlugins; using OpenUtauMobile.Services.SingerPlugins.Installation; using ReactiveUI; @@ -66,9 +66,9 @@ public PluginSingerSetupViewModel(MainViewModel navigator, RegisteredSingerInsta IsProgressIndeterminate = item.Total is not > 0; ProgressPercent = item.Total is > 0 ? Math.Clamp(item.Completed * 100d / item.Total.Value, 0, 100) : 0; }); - NextCommand = ReactiveCommand.CreateFromTask(() => RunAsync(async () => Apply(await controller.NextAsync(Submission(), progress))), + NextCommand = ReactiveCommand.CreateFromTask(() => RunAsync(async () => await ApplyAsync(await controller.NextAsync(Submission(), progress))), this.WhenAnyValue(item => item.CanNext, item => item.IsBusy, item => item.IsClosing, (ready, busy, closing) => ready && !busy && !closing)); - BackCommand = ReactiveCommand.CreateFromTask(() => RunAsync(async () => Apply(await controller.BackAsync())), + BackCommand = ReactiveCommand.CreateFromTask(() => RunAsync(async () => await ApplyAsync(await controller.BackAsync())), this.WhenAnyValue(item => item.CanBack, item => item.IsBusy, item => item.IsClosing, (ready, busy, closing) => ready && !busy && !closing)); InstallCommand = ReactiveCommand.CreateFromTask(() => RunAsync(InstallAsync), this.WhenAnyValue(item => item.CanInstall, item => item.IsBusy, item => item.IsClosing, @@ -81,23 +81,39 @@ public override void OnNavigatedTo() { if (initialized) return; initialized = true; - _ = RunAsync(async () => Apply(await controller.AnalyzeAsync(progress))); + _ = RunAsync(async () => await ApplyAsync(await controller.AnalyzeAsync(progress))); } private InstallSubmission Submission() => new(controller.View!.CurrentStepId, controller.View.Revision, Fields.Where(item => item.Descriptor.IsVisible && item.Descriptor.IsEnabled) .ToImmutableDictionary(item => item.Descriptor.Id, item => item.Read(), StringComparer.Ordinal)); - private void Apply(InstallView view) + /// 预览先独立读取与解码,完成后才在当前页面发布控件数据。 + private async Task ApplyAsync(InstallView view) { ClearContent(); InstallStep step = view.Steps.Single(item => item.Id == view.CurrentStepId); + List previews = []; + try + { + foreach (InstallContent item in step.Content.IsDefault ? ImmutableArray.Empty : step.Content) + { + previews.Add(await InstallPreviewViewModel.CreateAsync( + item.Title == step.Title ? item with { Title = "" } : item, controller)); + if (IsClosing) return; + } + if (IsClosing) return; + Previews = [.. previews]; + previews.Clear(); + } + finally + { + foreach (InstallPreviewViewModel preview in previews) preview.Dispose(); + } Title = step.Title; StepText = string.Format(L.S("SingerSetup.StepFormat"), view.Steps.IndexOf(step) + 1, view.Steps.Length); Fields = [.. (step.Fields.IsDefault ? ImmutableArray.Empty : step.Fields) .Select(item => new PluginFieldViewModel(item, Invalidate))]; - Previews = [.. (step.Content.IsDefault ? ImmutableArray.Empty : step.Content) - .Select(item => new InstallPreviewViewModel(item.Title == step.Title ? item with { Title = "" } : item, controller))]; foreach (PluginDiagnostic diagnostic in view.Diagnostics.IsDefault ? [] : view.Diagnostics) Fields.FirstOrDefault(item => item.Descriptor.Id == diagnostic.FieldId)?.SetError(diagnostic.Message); Error = string.Join("\n", view.Diagnostics.IsDefault ? [] : view.Diagnostics.Select(item => item.Message)); @@ -203,17 +219,24 @@ public sealed class InstallPreviewViewModel : IDisposable public bool HasImage => Image != null; public bool HasText => !string.IsNullOrEmpty(Text); public bool HasTitle => !string.IsNullOrWhiteSpace(Title); - public InstallPreviewViewModel(InstallContent content, SingerInstallController controller) + private InstallPreviewViewModel(string title, string text, Bitmap? image = null) + { + Title = title; + Text = text; + Image = image; + } + + /// 后台读取和解码预览,返回后由页面接管图片的释放责任。 + public static async Task CreateAsync(InstallContent content, SingerInstallController controller) { - Title = content.Title; - Text = content.Kind == InstallContentKind.Image ? "" : content.Value; - if (content.Kind != InstallContentKind.Image) return; + if (content.Kind != InstallContentKind.Image) return new(content.Title, content.Value); try { - using MemoryStream bytes = new(File.ReadAllBytes(controller.PreviewPath(content.Value))); - Image = new Bitmap(bytes); + byte[] bytes = await controller.ReadPreviewAsync(content.Value); + return new(content.Title, "", await BitmapLoader.DecodeAsync(bytes)); } - catch (Exception exception) { Text = exception.Message; } + catch (OperationCanceledException) { throw; } + catch (Exception exception) { return new(content.Title, exception.Message); } } public void Dispose() => Image?.Dispose(); } diff --git a/OpenUtauMobile/ViewModels/ProjectTemplatesViewModel.cs b/OpenUtauMobile/ViewModels/ProjectTemplatesViewModel.cs index 8d770937..96e1b5dd 100644 --- a/OpenUtauMobile/ViewModels/ProjectTemplatesViewModel.cs +++ b/OpenUtauMobile/ViewModels/ProjectTemplatesViewModel.cs @@ -2,9 +2,11 @@ using System.Collections.ObjectModel; using System.IO; using System.Reactive; +using System.Threading.Tasks; using OpenUtau.Core; using OpenUtauMobile.Services.Dialogs; using ReactiveUI; +using ReactiveUI.Fody.Helpers; namespace OpenUtauMobile.ViewModels { @@ -13,8 +15,18 @@ public sealed record ProjectTemplateItem(string Path) public string Name => System.IO.Path.GetFileNameWithoutExtension(Path); } + /// 异步读取模板列表,关闭后不发布迟到的目录结果。 public sealed class ProjectTemplatesViewModel : PopupViewModelBase { + private bool closed; + /// 模板目录正在后台读取。 + [Reactive] public bool IsLoading { get; private set; } = true; + /// 加载结束后才显示空列表提示。 + [Reactive] public bool ShowEmpty { get; private set; } + /// 目录读取失败时显示错误,空列表仍复用动态本地化资源。 + [Reactive] public bool HasLoadError { get; private set; } + /// 目录读取失败的具体说明。 + [Reactive] public string LoadError { get; private set; } = string.Empty; public ObservableCollection Items { get; } = []; public ReactiveCommand OpenCommand { get; } public ReactiveCommand DeleteCommand { get; } @@ -22,27 +34,58 @@ public sealed class ProjectTemplatesViewModel : PopupViewModelBase public ProjectTemplatesViewModel() { - Directory.CreateDirectory(PathManager.Inst.TemplatesPath); - foreach (string path in Directory.GetFiles(PathManager.Inst.TemplatesPath, "*.ustx")) - { - Items.Add(new(path)); - } - OpenCommand = ReactiveCommand.Create(item => RaiseClose(item.Path)); + OpenCommand = ReactiveCommand.Create(item => Close(item.Path)); DeleteCommand = ReactiveCommand.Create(item => { try { File.Delete(item.Path); Items.Remove(item); + ShowEmpty = Items.Count == 0; } catch (Exception exception) { ErrorDialogService.Show(new ErrorDialogViewModel(new ErrorMessageNotification(exception))); } }); - CancelCommand = ReactiveCommand.Create(() => RaiseClose(null)); + CancelCommand = ReactiveCommand.Create(RequestBack); + _ = LoadAsync(); + } + + /// 浏览模板只读目录,不因空目录创建产生额外磁盘写入。 + private async Task LoadAsync() + { + string directory = PathManager.Inst.TemplatesPath; + try + { + string[] paths = await Task.Run(() => Directory.Exists(directory) + ? Directory.GetFiles(directory, "*.ustx") : []); + if (closed) return; + foreach (string path in paths) Items.Add(new(path)); + } + catch (Exception exception) + { + if (closed) return; + LoadError = exception.Message; + HasLoadError = true; + } + finally + { + if (!closed) + { + IsLoading = false; + ShowEmpty = Items.Count == 0 && !HasLoadError; + } + } + } + + /// 用户关闭弹窗后,读取可以结束但不再更新弹窗。 + private void Close(string? path) + { + closed = true; + RaiseClose(path); } - public override void RequestBack() => RaiseClose(null); + public override void RequestBack() => Close(null); } } diff --git a/OpenUtauMobile/ViewModels/TrackHeaderViewModel.cs b/OpenUtauMobile/ViewModels/TrackHeaderViewModel.cs index 43d83679..2708ab05 100644 --- a/OpenUtauMobile/ViewModels/TrackHeaderViewModel.cs +++ b/OpenUtauMobile/ViewModels/TrackHeaderViewModel.cs @@ -1,10 +1,9 @@ using System; -using System.Diagnostics; -using System.IO; using System.Linq; using System.Reactive; using System.Reactive.Disposables; using System.Reactive.Linq; +using System.Threading; using System.Threading.Tasks; using Avalonia.Controls; using Avalonia.Media; @@ -15,6 +14,7 @@ using OpenUtau.Core.Render; using OpenUtau.Core.Ustx; using OpenUtau.Core.Util; +using OpenUtauMobile.Services; using OpenUtauMobile.Services.Tracks; using OpenUtauMobile.Themes.OpenUtauMobile.Runtime; using OpenUtauMobile.Themes.OpenUtauMobile.Runtime.Generation; @@ -35,6 +35,8 @@ public class TrackHeaderViewModel : ViewModelBase, IDisposable private bool _isRefreshing; private byte[]? _avatarData; private bool _avatarInitialized; + private CancellationTokenSource? _avatarLoading; + private bool _disposed; [Reactive] public string TrackName { get; set; } = string.Empty; [Reactive] public bool Muted { get; set; } @@ -382,34 +384,48 @@ private async Task ChangeColor() Refresh(); } + /// 只在头像数据变化时请求后台解码,避免刷新轨道头时阻塞 UI。 private void RefreshAvatar() { + if (_disposed) return; byte[]? avatarData = _track.Singer?.AvatarData; if (_avatarInitialized && ReferenceEquals(_avatarData, avatarData)) return; _avatarInitialized = true; _avatarData = avatarData; - SingerIcon?.Dispose(); + _avatarLoading?.Cancel(); + _avatarLoading = null; + Bitmap? previous = SingerIcon; SingerIcon = null; - if (avatarData == null) - { - SingerIcon = null; - HasSingerAvatar = false; - return; - } + previous?.Dispose(); + HasSingerAvatar = false; + if (avatarData is { Length: > 0 }) _ = LoadAvatarAsync(avatarData); + } + /// 过时或已释放轨道头的解码结果不再进入绑定,并立即释放。 + private async Task LoadAvatarAsync(byte[] avatarData) + { + using CancellationTokenSource loading = new(); + _avatarLoading = loading; try { - using MemoryStream stream = new(avatarData); - SingerIcon = new Bitmap(stream); + Bitmap bitmap = await BitmapLoader.DecodeAsync(avatarData, loading.Token); + if (_disposed || loading.IsCancellationRequested || !ReferenceEquals(_avatarLoading, loading)) + { + bitmap.Dispose(); + return; + } + SingerIcon = bitmap; HasSingerAvatar = true; } + catch (OperationCanceledException) when (loading.IsCancellationRequested) { } catch (Exception e) { - SingerIcon = null; - HasSingerAvatar = false; - Debug.WriteLine(e); Log.Error(e, "Failed to decode avatar."); } + finally + { + if (ReferenceEquals(_avatarLoading, loading)) _avatarLoading = null; + } } /// @@ -440,9 +456,13 @@ public void Refresh() public void Dispose() { + _disposed = true; + _avatarLoading?.Cancel(); + _avatarLoading = null; _disposable.Dispose(); - SingerIcon?.Dispose(); + Bitmap? previous = SingerIcon; SingerIcon = null; + previous?.Dispose(); _avatarData = null; GC.SuppressFinalize(this); } diff --git a/OpenUtauMobile/Views/MainView.axaml.cs b/OpenUtauMobile/Views/MainView.axaml.cs index 1a64197c..26269097 100644 --- a/OpenUtauMobile/Views/MainView.axaml.cs +++ b/OpenUtauMobile/Views/MainView.axaml.cs @@ -11,6 +11,8 @@ namespace OpenUtauMobile.Views; public partial class MainView : UserControl { + private DocumentValidationScheduler? _validationScheduler; + public MainView() { InitializeComponent(); @@ -39,6 +41,11 @@ protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) WarningOverlay.SetPresentationReady(PageHost.Content is ViewModelBase and not SplashScreenViewModel); // Android 的 Material You 色值在 TopLevel 建立后才可由平台设置读取。 App.RefreshSystemThemeColor(); + if (TopLevel.GetTopLevel(this) is { } validationHost) + { + _validationScheduler = new DocumentValidationScheduler(validationHost); + } + TopLevel? topLevel = AppService.GetTopLevel(); topLevel?.BackRequested += OnBackRequested; ToastService.Register(ToastOverlay.ConsumeAsync); @@ -55,6 +62,8 @@ protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e) { + _validationScheduler?.Dispose(); + _validationScheduler = null; base.OnDetachedFromVisualTree(e); TopLevel? topLevel = AppService.GetTopLevel(); topLevel?.BackRequested -= OnBackRequested; @@ -96,4 +105,4 @@ private void OnBackRequested(object? sender, RoutedEventArgs e) vm.OnBackRequested(); e.Handled = true; } -} \ No newline at end of file +} From 8860fa0851616ae543e0d4d40b2f658493f9c889 Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:16:12 +0800 Subject: [PATCH 21/45] =?UTF-8?q?performance:=20=E5=B0=86=E4=BF=9D?= =?UTF-8?q?=E5=AD=98=E5=BC=82=E6=AD=A5=E6=89=A7=E8=A1=8C=E6=8F=90=E5=8D=87?= =?UTF-8?q?UX=EF=BC=8C=E9=81=BF=E5=85=8DANR=E5=B9=B6=E7=A1=AE=E4=BF=9D?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E7=9A=84=E5=8E=9F=E5=AD=90=E6=80=A7=E6=AD=A3?= =?UTF-8?q?=E7=A1=AE=E6=80=A7=E5=AE=89=E5=85=A8=E6=80=A7(core)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- OpenUtau.Core/DocManager.cs | 52 ++++++ OpenUtau.Core/Util/Preferences.cs | 7 + OpenUtauMobile.Android/MainActivity.cs | 21 ++- OpenUtauMobile/App.axaml.cs | 4 +- OpenUtauMobile/Assets/Lang/Strings.en.resx | 8 + OpenUtauMobile/Assets/Lang/Strings.ja.resx | 8 + OpenUtauMobile/Assets/Lang/Strings.ru.resx | 8 + OpenUtauMobile/Assets/Lang/Strings.uk.resx | 8 + .../Assets/Lang/Strings.zh-Hans.resx | 8 + OpenUtauMobile/Services/AppService.cs | 21 ++- .../Services/Dialogs/LoadingPopupService.cs | 2 + .../Editor/EditorInputController.Keyboard.cs | 2 +- .../Services/Projects/AtomicFileWriter.cs | 43 +++++ .../Services/Projects/PreferencesWriter.cs | 146 ++++++++++++++++ .../Projects/ProjectSaveCoordinator.cs | 160 ++++++++++++++++++ .../Services/Projects/ProjectSaveSnapshot.cs | 136 +++++++++++++++ .../ViewModels/EditorViewModel.Input.cs | 51 ++++-- OpenUtauMobile/ViewModels/EditorViewModel.cs | 103 +++++------ OpenUtauMobile/ViewModels/HomeViewModel.cs | 1 + OpenUtauMobile/Views/EditorView.axaml | 1 + OpenUtauMobile/Views/MainWindow.axaml.cs | 6 + 21 files changed, 714 insertions(+), 82 deletions(-) create mode 100644 OpenUtauMobile/Services/Projects/AtomicFileWriter.cs create mode 100644 OpenUtauMobile/Services/Projects/PreferencesWriter.cs create mode 100644 OpenUtauMobile/Services/Projects/ProjectSaveCoordinator.cs create mode 100644 OpenUtauMobile/Services/Projects/ProjectSaveSnapshot.cs diff --git a/OpenUtau.Core/DocManager.cs b/OpenUtau.Core/DocManager.cs index b4d84344..5fb93a0d 100644 --- a/OpenUtau.Core/DocManager.cs +++ b/OpenUtau.Core/DocManager.cs @@ -195,8 +195,59 @@ private void SearchPluginInternal(string path, List result) { ValidateOptions? pendingValidate; UCommandGroup? savedPoint = null; UCommandGroup? autosavedPoint = null; + private object saveSession = new object(); public bool Recovered { get; set; } = false; // Flag to not overwrite backup file + /// 由宿主持有的保存检查点;不暴露或复制撤销队列。 + public sealed class SaveCheckpoint { + internal readonly UProject Project; + internal readonly object Session; + internal readonly UCommandGroup? Point; + + internal SaveCheckpoint(UProject project, object session, UCommandGroup? point) { + Project = project; + Session = session; + Point = point; + } + } + + /// 在 UI 线程捕获已结束编辑事务的保存检查点。 + public SaveCheckpoint CaptureSaveCheckpoint() { + ThreadGuard.AssertUi(); + return HasOpenUndoGroup ? throw new InvalidOperationException("Cannot capture a save checkpoint inside an undo group.") : new SaveCheckpoint(Project, saveSession, undoQueue.LastOrDefault()); + } + + /// 核查工程引用及装载会话,拒绝旧保存任务提交至新文档。 + public bool IsSaveCheckpointCurrent(SaveCheckpoint checkpoint) { + ThreadGuard.AssertUi(); + return ReferenceEquals(Project, checkpoint.Project) && ReferenceEquals(saveSession, checkpoint.Session); + } + + /// 仅按持久化编辑检查点判断是否需要自动保存,不受渲染通知影响。 + public bool NeedsAutoSave(SaveCheckpoint checkpoint) { + ThreadGuard.AssertUi(); + return IsSaveCheckpointCurrent(checkpoint) && !ReferenceEquals(checkpoint.Point, autosavedPoint); + } + + /// 宿主确认写盘及平台同步成功后提交捕获点;此方法不执行文件读写。 + public bool CompleteSave(SaveCheckpoint checkpoint, string path, bool autoSave) { + ThreadGuard.AssertUi(); + if (!IsSaveCheckpointCurrent(checkpoint)) { + return false; + } + if (autoSave) { + autosavedPoint = checkpoint.Point; + } else { + Project.FilePath = path; + Project.Saved = true; + savedPoint = checkpoint.Point; + autosavedPoint = checkpoint.Point; + Recovered = false; + Publish(new SaveProjectNotification(path)); + } + return true; + } + public bool ChangesSaved { get { return (Project.Saved || (Project.tracks.Count <= 1 && Project.parts.Count == 0)) && @@ -302,6 +353,7 @@ ProgressBarNotification or WaveformReadyNotification or Format.Ustx.Save(saveProjectNotif.Path, Project); } } else if (cmd is LoadProjectNotification notification) { + saveSession = new object(); undoQueue.Clear(); redoQueue.Clear(); undoGroup = null; diff --git a/OpenUtau.Core/Util/Preferences.cs b/OpenUtau.Core/Util/Preferences.cs index f5caea38..901dbea5 100644 --- a/OpenUtau.Core/Util/Preferences.cs +++ b/OpenUtau.Core/Util/Preferences.cs @@ -14,12 +14,19 @@ namespace OpenUtau.Core.Util { public static class Preferences { public static SerializablePreferences Default { get; private set; } + /// 可选宿主保存入口;由宿主捕获独立数据、合并请求并安排后台持久化。 + public static Action? SaveOverride { get; set; } + static Preferences() { Load(); } public static void Save() { try { + if (SaveOverride != null) { + SaveOverride(); + return; + } File.WriteAllText(PathManager.Inst.PrefsFilePath, Json.Serialize(Default, Json.WriteIndentedOptions), Encoding.UTF8); diff --git a/OpenUtauMobile.Android/MainActivity.cs b/OpenUtauMobile.Android/MainActivity.cs index 1b592407..559468a6 100644 --- a/OpenUtauMobile.Android/MainActivity.cs +++ b/OpenUtauMobile.Android/MainActivity.cs @@ -23,7 +23,6 @@ using OpenUtauMobile.Android.Services.Platform; using OpenUtauMobile.Android.Services.Performance; using OpenUtauMobile.Android.Services.Storage; -using Serilog; using Environment = System.Environment; using Log = Serilog.Log; using Path = System.IO.Path; @@ -124,6 +123,24 @@ protected override void OnDestroy() base.OnDestroy(); } + + /// 离开前请求刷新合并的偏好,避免以同步磁盘等待阻塞 Android 生命周期。 + protected override void OnPause() + { + base.OnPause(); + _ = FlushPreferencesAsync(); + } + + /// 异步刷新结束后记录异常,不在生命周期回调中等待磁盘。 + private static async Task FlushPreferencesAsync() + { + try + { + await Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(async () => + await OpenUtauMobile.Services.Projects.PreferencesWriter.Inst.FlushAsync()); + } + catch (Exception error) { Log.Error(error, "暂停时刷新偏好失败"); } + } /// /// 自动恢复沉浸模式 /// @@ -248,7 +265,7 @@ internal static void InitPathManager() /// private static void InitLogging() { - OpenUtauMobile.Services.AppLogging.Initialize(PathManager.Inst.LogFilePath); + AppLogging.Initialize(PathManager.Inst.LogFilePath); Log.Information("==========开始记录日志=========="); } diff --git a/OpenUtauMobile/App.axaml.cs b/OpenUtauMobile/App.axaml.cs index a7052fdf..57e0d6bd 100644 --- a/OpenUtauMobile/App.axaml.cs +++ b/OpenUtauMobile/App.axaml.cs @@ -7,6 +7,7 @@ using OpenUtau.Core.Util; using OpenUtauMobile.Helpers; using OpenUtauMobile.Services; +using OpenUtauMobile.Services.Projects; using OpenUtauMobile.Themes.OpenUtauMobile.Runtime; using OpenUtauMobile.Themes.OpenUtauMobile.Runtime.Platform; using OpenUtauMobile.ViewModels; @@ -25,6 +26,7 @@ public override void Initialize() public override void OnFrameworkInitializationCompleted() { + PreferencesWriter.Inst.Install(); // Load language preference before constructing any UI/view-models. LocalizationManager.LoadLanguage(Preferences.Default.Language); @@ -100,4 +102,4 @@ internal static void RefreshSystemThemeColor() "Dark" => ThemeVariant.Dark, _ => ThemeVariant.Default, }; -} \ No newline at end of file +} diff --git a/OpenUtauMobile/Assets/Lang/Strings.en.resx b/OpenUtauMobile/Assets/Lang/Strings.en.resx index 41841fe4..c3293669 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.en.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.en.resx @@ -2634,4 +2634,12 @@ Applying replaces the source of this input. The system WebView could not load this page. Use the top-right button to open it in your browser. {0}: {1} {2} + Capturing project snapshot… + Waiting for the current save… + Preparing project data… + Serializing project… + Writing project file… + Replacing project file… + Synchronizing storage… + Confirming saved version… diff --git a/OpenUtauMobile/Assets/Lang/Strings.ja.resx b/OpenUtauMobile/Assets/Lang/Strings.ja.resx index 2aea4a9e..47ab611c 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.ja.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.ja.resx @@ -2628,4 +2628,12 @@ Applying replaces the source of this input. プラグイン設定を開けませんでした。 システムブラウザーを開けませんでした。 システム WebView で読み込めません。右上のボタンからブラウザーで開いてください。 + プロジェクトのスナップショットを取得中… + 現在の保存処理を待機中… + プロジェクトデータを準備中… + プロジェクトをシリアライズ中… + プロジェクトファイルを書き込み中… + プロジェクトファイルを置換中… + ストレージを同期中… + 保存したバージョンを確認中… diff --git a/OpenUtauMobile/Assets/Lang/Strings.ru.resx b/OpenUtauMobile/Assets/Lang/Strings.ru.resx index 785fbee3..fc229937 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.ru.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.ru.resx @@ -2587,4 +2587,12 @@ Applying replaces the source of this input. Не удалось открыть настройки плагина. Не удалось открыть системный браузер. Системный WebView не смог загрузить страницу. Откройте её в браузере кнопкой справа вверху. + Создание снимка проекта… + Ожидание текущего сохранения… + Подготовка данных проекта… + Сериализация проекта… + Запись файла проекта… + Замена файла проекта… + Синхронизация хранилища… + Подтверждение сохранённой версии… diff --git a/OpenUtauMobile/Assets/Lang/Strings.uk.resx b/OpenUtauMobile/Assets/Lang/Strings.uk.resx index c08f3538..a2295475 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.uk.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.uk.resx @@ -2587,4 +2587,12 @@ Applying replaces the source of this input. Не вдалося відкрити налаштування плагіна. Не вдалося відкрити системний браузер. Системний WebView не завантажив сторінку. Відкрийте її у браузері кнопкою праворуч угорі. + Створення знімка проєкту… + Очікування поточного збереження… + Підготовка даних проєкту… + Серіалізація проєкту… + Запис файлу проєкту… + Заміна файлу проєкту… + Синхронізація сховища… + Підтвердження збереженої версії… diff --git a/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx b/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx index d993ebba..74d68ef7 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx @@ -2634,4 +2634,12 @@ 系统 WebView 无法加载页面,可使用右上角按钮在系统浏览器打开。 {0}:{1} {2} + 正在捕获工程快照… + 正在等待当前保存完成… + 正在整理工程数据… + 正在序列化工程… + 正在写入工程文件… + 正在替换工程文件… + 正在同步存储… + 正在确认已保存版本… diff --git a/OpenUtauMobile/Services/AppService.cs b/OpenUtauMobile/Services/AppService.cs index 3c67e88f..3a092f73 100644 --- a/OpenUtauMobile/Services/AppService.cs +++ b/OpenUtauMobile/Services/AppService.cs @@ -1,5 +1,9 @@ using System; +using System.Threading.Tasks; using Avalonia.Controls; +using OpenUtauMobile.Services.Projects; +using Serilog; +using OpenUtau.Core; namespace OpenUtauMobile.Services; @@ -39,11 +43,11 @@ public static bool ExitApplication() desktopLifetime.Shutdown(); return true; case Avalonia.Controls.ApplicationLifetimes.IActivityApplicationLifetime: - Environment.Exit(0); + _ = FlushAndExitAsync(); return true; case Avalonia.Controls.ApplicationLifetimes.ISingleViewApplicationLifetime when !OperatingSystem.IsBrowser(): - Environment.Exit(0); + _ = FlushAndExitAsync(); return true; case Avalonia.Controls.ApplicationLifetimes.ISingleViewApplicationLifetime: return false; // 在浏览器环境中,无法直接退出应用 @@ -51,4 +55,15 @@ public static bool ExitApplication() return false; } } -} \ No newline at end of file + + /// 退出前异步刷新合并的偏好请求,主线程继续处理平台输入。 + private static async Task FlushAndExitAsync() + { + var project = DocManager.Inst.Project; + var revision = DocManager.Inst.Revision; + try { await PreferencesWriter.Inst.FlushAsync(); } + catch (Exception error) { Log.Error(error, "退出时刷新偏好失败"); } + if (!ReferenceEquals(project, DocManager.Inst.Project) || revision != DocManager.Inst.Revision) return; + Environment.Exit(0); + } +} diff --git a/OpenUtauMobile/Services/Dialogs/LoadingPopupService.cs b/OpenUtauMobile/Services/Dialogs/LoadingPopupService.cs index 2da3b5b8..bdd209bd 100644 --- a/OpenUtauMobile/Services/Dialogs/LoadingPopupService.cs +++ b/OpenUtauMobile/Services/Dialogs/LoadingPopupService.cs @@ -88,6 +88,8 @@ await Dispatcher.UIThread.InvokeAsync( try { + if (popupTask.IsCompleted) + throw new InvalidOperationException("Loading dialog closed before the operation started."); await operation(viewModel); } finally diff --git a/OpenUtauMobile/Services/Editor/EditorInputController.Keyboard.cs b/OpenUtauMobile/Services/Editor/EditorInputController.Keyboard.cs index 49fd1dc8..a8c57351 100644 --- a/OpenUtauMobile/Services/Editor/EditorInputController.Keyboard.cs +++ b/OpenUtauMobile/Services/Editor/EditorInputController.Keyboard.cs @@ -29,7 +29,7 @@ public enum EditArea { Tracks, PianoRoll, Mixer } private bool IsEditorInputActive => _inputRoot != null && TopLevel.GetTopLevel(_owner) == _inputRoot && _owner.IsEffectivelyVisible && _owner.IsEffectivelyEnabled && !IsModalOpen && !HasInputPopup && - _owner.DataContext is EditorViewModel { IsLoadingProject: false }; + _owner.DataContext is EditorViewModel { IsLoadingProject: false, IsSavingProject: false }; private static bool IsWithin(Visual? source, Visual parent) => source != null && source.GetSelfAndVisualAncestors().Contains(parent); diff --git a/OpenUtauMobile/Services/Projects/AtomicFileWriter.cs b/OpenUtauMobile/Services/Projects/AtomicFileWriter.cs new file mode 100644 index 00000000..ea4dea15 --- /dev/null +++ b/OpenUtauMobile/Services/Projects/AtomicFileWriter.cs @@ -0,0 +1,43 @@ +using System; +using System.IO; +using System.Text; +using Serilog; + +namespace OpenUtauMobile.Services.Projects; + +/// 将独立数据写入同目录暂存文件,再替换目标;失败时保留旧目标。 +internal static class AtomicFileWriter +{ + /// 仅供后台调用;显式刷新编码器及文件后才执行替换。 + public static long Write(string path, Action serialize, Action? replacing = null) + { + string fullPath = Path.GetFullPath(path); + string directory = Path.GetDirectoryName(fullPath)!; + Directory.CreateDirectory(directory); + string staging = Path.Combine(directory, $".{Path.GetFileName(path)}.{Guid.NewGuid():N}.tmp"); + try + { + long length; + using (FileStream stream = new(staging, FileMode.CreateNew, FileAccess.Write, FileShare.None, 65536)) + { + using (StreamWriter writer = new(stream, Encoding.UTF8, 65536, leaveOpen: true)) + { + serialize(writer); + writer.Flush(); + } + // 一次最终持久化刷新,不对每个缓冲块同步闪存。 + if (OperatingSystem.IsBrowser()) stream.Flush(); + else stream.Flush(flushToDisk: true); + length = stream.Length; + } + replacing?.Invoke(); + File.Move(staging, fullPath, overwrite: true); + return length; + } + finally + { + try { if (File.Exists(staging)) File.Delete(staging); } + catch (Exception error) { Log.Warning(error, "无法清理保存暂存文件 {Path}", staging); } + } + } +} diff --git a/OpenUtauMobile/Services/Projects/PreferencesWriter.cs b/OpenUtauMobile/Services/Projects/PreferencesWriter.cs new file mode 100644 index 00000000..18109329 --- /dev/null +++ b/OpenUtauMobile/Services/Projects/PreferencesWriter.cs @@ -0,0 +1,146 @@ +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Threading.Tasks; +using Avalonia.Threading; +using OpenUtau.Core; +using OpenUtau.Core.Util; +using Serilog; + +namespace OpenUtauMobile.Services.Projects; + +/// 宿主偏好单写入器;UI 只复制内存,后台合并并原子写入,关键事务可等待持久化。 +public sealed class PreferencesWriter +{ + /// 应用进程唯一的偏好写入器,平台生命周期通过此实例请求刷新。 + public static PreferencesWriter Inst { get; } = new(); + private static readonly ConcurrentDictionary Members = new(); + private readonly List<(long Version, TaskCompletionSource Completion)> _waiters = []; + private PendingSave? _pending; + private Task? _pump; + private long _version; + private long _completedVersion; + private string? _lastWrittenJson; + private string? _lastWrittenPath; + + /// 在应用启动时注册;未注册宿主的上游程序仍使用原同步实现。 + public void Install() => Preferences.SaveOverride = RequestSave; + + /// 统一将请求派发到 UI,避免后台枚举可变偏好集合。 + private void RequestSave() + { + if (!Dispatcher.UIThread.CheckAccess()) + { + Dispatcher.UIThread.Post(RequestSave); + return; + } + var snapshot = (Preferences.SerializablePreferences)CopyValue(Preferences.Default)!; + _pending = new(++_version, snapshot, PathManager.Inst.PrefsFilePath); + _pump ??= PumpAsync(); + } + + /// 关键事务直接请求并等待持久化,捕获失败也向调用者传播。 + public Task SaveAsync() + { + Dispatcher.UIThread.VerifyAccess(); + RequestSave(); + return FlushAsync(); + } + + /// 等待调用时已请求的偏好版本持久化;失败向调用者传播,下一请求可重试。 + public Task FlushAsync() + { + Dispatcher.UIThread.VerifyAccess(); + if (_completedVersion == _version) return Task.CompletedTask; + TaskCompletionSource completion = new(TaskCreationOptions.RunContinuationsAsynchronously); + _waiters.Add((_version, completion)); + _pump ??= PumpAsync(); + return completion.Task; + } + + /// 偏好数据仅含公开 DTO 字段/可写属性;复制集合及嵌套 DTO,不序列化活动对象。 + private static object? CopyValue(object? value) + { + if (value == null || value is string || value.GetType().IsValueType) return value; + Type type = value.GetType(); + if (value is Array array) + { + Array copy = Array.CreateInstance(type.GetElementType()!, array.Length); + for (int i = 0; i < array.Length; i++) copy.SetValue(CopyValue(array.GetValue(i)), i); + return copy; + } + if (value is IDictionary dictionary) + { + IDictionary copy = (IDictionary)Activator.CreateInstance(type)!; + foreach (DictionaryEntry entry in dictionary) copy.Add(entry.Key, CopyValue(entry.Value)); + return copy; + } + if (value is IList list) + { + IList copy = (IList)Activator.CreateInstance(type)!; + foreach (object? item in list) copy.Add(CopyValue(item)); + return copy; + } + object result = Activator.CreateInstance(type)!; + var members = Members.GetOrAdd(type, current => ( + [.. current.GetFields(BindingFlags.Instance | BindingFlags.Public).Where(field => !field.IsInitOnly)], + [.. current.GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(property => property.CanRead && property.SetMethod?.IsPublic == true && property.GetIndexParameters().Length == 0)])); + foreach (FieldInfo field in members.Fields) field.SetValue(result, CopyValue(field.GetValue(value))); + foreach (PropertyInfo property in members.Properties) property.SetValue(result, CopyValue(property.GetValue(value))); + return result; + } + + /// 每批只保留最新偏好快照,避免连续操作反复写入闪存。 + private async Task PumpAsync() + { + await Task.Delay(200); + try + { + while (_pending is { } pending) + { + _pending = null; + try + { + await Task.Run(() => + { + string json = Json.Serialize(pending.Snapshot, Json.WriteIndentedOptions); + // 自动保存通常只重复同一个恢复路径;数据未变时不再写偏好文件。 + if (json == _lastWrittenJson && pending.Path == _lastWrittenPath && File.Exists(pending.Path)) return; + AtomicFileWriter.Write(pending.Path, writer => writer.Write(json)); + _lastWrittenJson = json; + _lastWrittenPath = pending.Path; + }); + _completedVersion = pending.Version; + FinishWaiters(pending.Version, null); + } + catch (Exception error) + { + _pending ??= pending; + Log.Error(error, "偏好后台保存失败"); + FinishWaiters(long.MaxValue, error); + break; + } + } + } + finally { _pump = null; } + } + + /// 完成已落盘版本的等待者;失败保留最新待写快照供后续重试。 + private void FinishWaiters(long version, Exception? error) + { + for (int i = _waiters.Count - 1; i >= 0; i--) + { + if (_waiters[i].Version > version) continue; + TaskCompletionSource completion = _waiters[i].Completion; + _waiters.RemoveAt(i); + if (error == null) completion.TrySetResult(); + else completion.TrySetException(error); + } + } + + private sealed record PendingSave(long Version, Preferences.SerializablePreferences Snapshot, string Path); +} diff --git a/OpenUtauMobile/Services/Projects/ProjectSaveCoordinator.cs b/OpenUtauMobile/Services/Projects/ProjectSaveCoordinator.cs new file mode 100644 index 00000000..2c2c6bc2 --- /dev/null +++ b/OpenUtauMobile/Services/Projects/ProjectSaveCoordinator.cs @@ -0,0 +1,160 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Avalonia.Threading; +using OpenUtau.Core; +using OpenUtau.Core.Ustx; +using OpenUtau.Core.Util; +using Serilog; + +namespace OpenUtauMobile.Services.Projects; + +/// 保存阶段由功能调用方本地化,后台不读取 UI 资源。 +internal enum ProjectSaveStage { Capturing, Waiting, Preparing, Serializing, Writing, Replacing, Synchronizing, Confirming } + +/// 手动、模板及自动保存共用的单写入队列;活动工程只在 UI 捕获和确认阶段访问。 +internal sealed class ProjectSaveCoordinator +{ + // 保存独占实例在后台首次创建,避免默认序列化器的锁阻塞 UI 上的表达式图指纹计算。 + private static readonly Lazy SaveSerializer = new(() => new Yaml()); + /// 所有保存入口共用进程内唯一的工程写入队列。 + public static ProjectSaveCoordinator Inst { get; } = new(); + private readonly SemaphoreSlim _writer = new(1, 1); + private bool _autoSaveRunning; + private int _manualRequests; + private string _backupPath = string.Empty; + private long _recoveryGeneration; + + /// 用户明确丢弃恢复时使在途自动任务失去发布恢复提示的资格。 + public void DismissRecovery() + { + Dispatcher.UIThread.VerifyAccess(); + _recoveryGeneration++; + } + + /// 调用方在模态窗口内等待整个事务;模板保存不会更改活动工程保存点。 + public async Task SaveManualAsync(DocManager.SaveCheckpoint owner, string path, bool template, + IProgress? progress = null) + { + Dispatcher.UIThread.VerifyAccess(); + _manualRequests++; + try { return await SaveAsync(owner, path, template, autoSave: false, progress); } + finally { _manualRequests--; } + } + + /// 无编辑、开放撤销组、有手动请求或已有自动任务时跳过,不积压快照。 + public async Task AutoSaveAsync(DocManager.SaveCheckpoint owner) + { + Dispatcher.UIThread.VerifyAccess(); + DocManager doc = DocManager.Inst; + if (_autoSaveRunning || _manualRequests != 0 || !doc.IsSaveCheckpointCurrent(owner) || doc.HasOpenUndoGroup) + return false; + DocManager.SaveCheckpoint point = doc.CaptureSaveCheckpoint(); + if (!doc.NeedsAutoSave(point)) return false; + if (string.IsNullOrEmpty(_backupPath)) + { + // DocManager 只拥有一个活动工程,队列统一替换同一个恢复文件,避免重开工程积累备份。 + _backupPath = Path.Combine(PathManager.Inst.BackupsPath, "Mobile-autosave.ustx"); + } + _autoSaveRunning = true; + try { return await SaveAsync(owner, _backupPath, template: false, autoSave: true, progress: null); } + catch (Exception error) + { + // 不推进检查点,下一次定时请求仍能重试;不弹模态打断编辑。 + Log.Error(error, "自动保存失败"); + return false; + } + finally { _autoSaveRunning = false; } + } + + /// 捕获开始时版本,后台准备及写入,最后按文档会话确认结果。 + private async Task SaveAsync(DocManager.SaveCheckpoint owner, string path, bool template, bool autoSave, + IProgress? progress) + { + DocManager doc = DocManager.Inst; + if (!doc.IsSaveCheckpointCurrent(owner) || doc.HasOpenUndoGroup || string.IsNullOrWhiteSpace(path)) return false; + progress?.Report(ProjectSaveStage.Capturing); + string previousRecovery = Preferences.Default.RecoveryPath; + long recoveryGeneration = _recoveryGeneration; + DocManager.SaveCheckpoint point = doc.CaptureSaveCheckpoint(); + Stopwatch total = Stopwatch.StartNew(); + UProject snapshot = ProjectSaveSnapshot.Capture(doc.Project, template); + Log.Information("保存阶段 {Stage}:{Milliseconds:F2} ms,Auto={Auto},Template={Template}", + "Capture", total.Elapsed.TotalMilliseconds, autoSave, template); + + progress?.Report(ProjectSaveStage.Waiting); + Stopwatch phase = Stopwatch.StartNew(); + await _writer.WaitAsync(); + try + { + LogPhase("Wait", phase); + // 排队期间已经换工程的任务无需再消耗磁盘;已开始的写盘始终使用捕获路径。 + if (!doc.IsSaveCheckpointCurrent(point)) return false; + await Task.Run(() => WriteSnapshot(snapshot, path, progress)); + progress?.Report(ProjectSaveStage.Synchronizing); + phase.Restart(); + await ServiceHub.FlushFileSystemAsync(); + LogPhase("SyncProject", phase); + if (!doc.IsSaveCheckpointCurrent(point)) return false; + if (template) return true; + + progress?.Report(ProjectSaveStage.Confirming); + if (autoSave) + { + // 用户丢弃恢复或其他事务已经发布恢复路径时,旧任务不得恢复该提示。 + if (_recoveryGeneration != recoveryGeneration || Preferences.Default.RecoveryPath != previousRecovery) return false; + Preferences.Default.RecoveryPath = path; + } + else + { + Preferences.Default.RecoveryPath = string.Empty; + Preferences.Default.LastSaveProjectDirectory = Path.GetDirectoryName(path) ?? string.Empty; + // 已知目标刚刚成功写入,最近记录不再逐个同步查盘。 + var recent = Preferences.Default.RecentFiles; + recent.RemoveAll(file => string.IsNullOrEmpty(file) || file == path || + file.StartsWith(PathManager.Inst.TemplatesPath + Path.DirectorySeparatorChar, StringComparison.Ordinal)); + recent.Insert(0, path); + if (recent.Count > 16) recent.RemoveRange(16, recent.Count - 16); + } + await PreferencesWriter.Inst.SaveAsync(); + LogPhase("Preferences", phase); + await ServiceHub.FlushFileSystemAsync(); + LogPhase("SyncPreferences", phase); + if (autoSave && (_recoveryGeneration != recoveryGeneration || Preferences.Default.RecoveryPath != path)) return false; + bool committed = doc.CompleteSave(point, path, autoSave); + Log.Information("保存完成:{Milliseconds:F2} ms,Auto={Auto},Committed={Committed}", + total.Elapsed.TotalMilliseconds, autoSave, committed); + return committed; + } + finally { _writer.Release(); } + } + + /// 只访问独立快照;分开记录 CPU 序列化、文件写入和替换阶段。 + private static void WriteSnapshot(UProject snapshot, string path, IProgress? progress) + { + Stopwatch phase = Stopwatch.StartNew(); + progress?.Report(ProjectSaveStage.Preparing); + ProjectSaveSnapshot.Prepare(snapshot, path); + LogPhase("Prepare", phase); + progress?.Report(ProjectSaveStage.Serializing); + string yaml = SaveSerializer.Value.Serialize(snapshot); + LogPhase("Serialize", phase); + progress?.Report(ProjectSaveStage.Writing); + long bytes = AtomicFileWriter.Write(path, writer => writer.Write(yaml), () => + { + LogPhase("Write", phase); + progress?.Report(ProjectSaveStage.Replacing); + }); + LogPhase("Replace", phase); + Log.Information("工程写入 {Bytes} bytes:{Path}", bytes, path); + } + + /// 记录阶段耗时并开始下一阶段计时。 + private static void LogPhase(string stage, Stopwatch watch) + { + Log.Information("保存阶段 {Stage}:{Milliseconds:F2} ms", stage, watch.Elapsed.TotalMilliseconds); + watch.Restart(); + } +} diff --git a/OpenUtauMobile/Services/Projects/ProjectSaveSnapshot.cs b/OpenUtauMobile/Services/Projects/ProjectSaveSnapshot.cs new file mode 100644 index 00000000..f15955e5 --- /dev/null +++ b/OpenUtauMobile/Services/Projects/ProjectSaveSnapshot.cs @@ -0,0 +1,136 @@ +using System; +using System.Linq; +using Avalonia.Threading; +using OpenUtau.Core.Format; +using OpenUtau.Core.Ustx; + +namespace OpenUtauMobile.Services.Projects; + +/// 仅包含 USTX 持久化数据的独立副本,不持有活动歌手、音素器或渲染数据。 +internal static class ProjectSaveSnapshot +{ + /// 在一个 UI 调度回合捕获一致版本;返回后后台只能访问该副本。 + public static UProject Capture(UProject source, bool template) + { + Dispatcher.UIThread.VerifyAccess(); + UProject copy = new() + { + ustxVersion = Ustx.kUstxVersion, + expressionGraphs = source.expressionGraphs == null ? null : [.. source.expressionGraphs.Select(graph => graph.Clone())], + defaultExpressionGraphs = source.defaultExpressionGraphs == null ? null : new(source.defaultExpressionGraphs), + }; + foreach (var pair in source.expressions) copy.expressions.Add(pair.Key, CopyExpression(pair.Value)); + // 保留现有模板语义:表达式和表达式图沿用,内容、轨道和时序使用新工程默认值。 + if (template) + { + copy.tracks = [.. copy.tracks.Select(CopyTrack)]; + return copy; + } + + copy.name = source.name; + copy.comment = source.comment; + copy.outputDir = source.outputDir; + copy.cacheDir = source.cacheDir; +#pragma warning disable CS0618 + copy.bpm = source.bpm; + copy.beatPerBar = source.beatPerBar; + copy.beatUnit = source.beatUnit; +#pragma warning restore CS0618 + copy.expSelectors = [.. source.expSelectors]; + copy.expPrimary = source.expPrimary; + copy.expSecondary = source.expSecondary; + copy.key = source.key; + copy.timeSignatures = [.. source.timeSignatures.Select(value => new UTimeSignature(value.barPosition, value.beatPerBar, value.beatUnit))]; + copy.tempos = [.. source.tempos.Select(value => new UTempo(value.position, value.bpm))]; + copy.tracks = [.. source.tracks.Select(CopyTrack)]; + copy.parts = [.. source.parts.Select(CopyPart)]; + return copy; + } + + /// 复制表达式的原始字段,保留自定义默认值的空值语义。 + private static UExpressionDescriptor CopyExpression(UExpressionDescriptor source) => new() + { + name = source.name, abbr = source.abbr, type = source.type, + min = source.min, max = source.max, defaultValue = source.defaultValue, + _customDefaultValue = source._customDefaultValue, + isFlag = source.isFlag, flag = source.flag, + options = source.options == null ? null! : [.. source.options], + skipOutputIfDefault = source.skipOutputIfDefault, + }; + + /// 捕获 BeforeSave 所需的运行时标识,后台不再接触歌手实例。 + private static UTrack CopyTrack(UTrack source) => new() + { + singer = source.Singer?.Id!, + phonemizer = source.Phonemizer.GetType().FullName!, + RendererSettings = new URenderSettings + { + renderer = source.RendererSettings.renderer, + resampler = source.RendererSettings.resampler, + wavtool = source.RendererSettings.wavtool, + }, + TrackName = source.TrackName, TrackColor = source.TrackColor, + Mute = source.Mute, Solo = source.Solo, + MixFx = source.MixFx?.Clone()!, Volume = source.Volume, Pan = source.Pan, + TrackExpressions = [.. source.TrackExpressions.Select(CopyExpression)], + ExpressionGraph = source.ExpressionGraph, + VoiceColorNames = source.Singer is { Found: true } && source.VoiceColorExp?.options is { Length: > 0 } colors + ? [.. colors] : [string.Empty], + }; + + /// 复制片段持久化字段,音频片段只记录引用,不读取或加载波形。 + private static UPart CopyPart(UPart source) + { + UPart copy = source switch + { + UVoicePart voice => new UVoicePart + { + duration = voice.duration, + notes = [.. voice.notes.Select(CopyNote)], + curves = [.. voice.curves.Select(curve => new UCurve(curve.abbr) { xs = [.. curve.xs], ys = [.. curve.ys] })], + maskedCurves = [.. voice.maskedCurves.Select(curve => curve.Clone())], + }, + UWavePart wave => new UWavePart + { + FilePath = wave.FilePath, relativePath = wave.relativePath, + fileDurationMs = wave.fileDurationMs, skip = wave.skip, trim = wave.trim, + fadein = wave.fadein, fadeout = wave.fadeout, + }, + _ => throw new NotSupportedException($"Unsupported project part: {source.GetType().Name}"), + }; + copy.name = source.name; + copy.comment = source.comment; + copy.trackNo = source.trackNo; + copy.position = source.position; + return copy; + } + + /// 音符表达式只保留值,避免 Clone 引用活动表达式描述符。 + private static UNote CopyNote(UNote source) => new() + { + position = source.position, duration = source.duration, tone = source.tone, + lyric = source.lyric, pitch = source.pitch.Clone(), vibrato = source.vibrato.Clone(), + tuning = source.tuning, PhonemizerOverride = source.PhonemizerOverride, + phonemeExpressions = [.. source.phonemeExpressions.Select(value => new UExpression + { + abbr = value.abbr, index = value.index, value = value.value, + })], + phonemeOverrides = [.. source.phonemeOverrides.Select(value => value.Clone())], + }; + + /// 在后台执行原 BeforeSave 的纯数据归一化,不调用具有运行时副作用的保存入口。 + public static void Prepare(UProject copy, string path) + { + copy.FilePath = path; + foreach (UPart part in copy.parts) + { + if (part is UWavePart wave) + wave.relativePath = System.IO.Path.GetRelativePath(System.IO.Path.GetDirectoryName(path)!, wave.FilePath); + else if (part is UVoicePart voice) + foreach (UNote note in voice.notes) + note.phonemeExpressions = [.. note.phonemeExpressions.OrderBy(value => value.index).ThenBy(value => value.abbr)]; + } + copy.voiceParts = [.. copy.parts.OfType().OrderBy(part => part.trackNo).ThenBy(part => part.position)]; + copy.waveParts = [.. copy.parts.OfType().OrderBy(part => part.trackNo).ThenBy(part => part.position)]; + } +} diff --git a/OpenUtauMobile/ViewModels/EditorViewModel.Input.cs b/OpenUtauMobile/ViewModels/EditorViewModel.Input.cs index 480eb815..f37a9af3 100644 --- a/OpenUtauMobile/ViewModels/EditorViewModel.Input.cs +++ b/OpenUtauMobile/ViewModels/EditorViewModel.Input.cs @@ -5,6 +5,7 @@ using OpenUtauMobile.Helpers; using OpenUtauMobile.Services; using OpenUtauMobile.Services.Dialogs; +using OpenUtauMobile.Services.Projects; using Serilog; namespace OpenUtauMobile.ViewModels; @@ -15,7 +16,7 @@ namespace OpenUtauMobile.ViewModels; public partial class EditorViewModel { private bool _viewportInputActive; - private bool _saveInProgress; + private Task? _manualSaveTask; public bool CanNavigateViewport => _inputState is TrackInputState.Idle or TrackInputState.Panning; public bool SupportsVerticalZoom => false; @@ -47,25 +48,53 @@ public void ZoomViewport(double scaleX, double scaleY, Point anchor) public void EndViewportInput(bool hadZoomInput, bool interrupted) => _viewportInputActive = false; - public async Task SaveFromInputAsync(bool saveAs) + /// 重复请求等待同一保存事务,失败不会放行保存并退出。 + public Task SaveFromInputAsync(bool saveAs) => + RunManualSaveAsync(() => saveAs ? RequestSaveAs() : SaveCore()); + + /// 核查编辑器所拥有的文档会话,避免文件选择后保存了另一个工程。 + private bool OwnsSaveDocument() => !_disposed && _projectLoaded && _saveOwner != null && + DocManager.Inst.IsSaveCheckpointCurrent(_saveOwner); + + /// 所有手动保存入口复用同一个在途任务,包括模板保存和另存为选择器。 + private Task RunManualSaveAsync(Func> operation) => + _manualSaveTask ??= ExecuteManualSaveAsync(operation); + + /// 统一处理失败通知和任务收尾,不改写可能已切换的工程状态。 + private async Task ExecuteManualSaveAsync(Func> operation) { - if (_saveInProgress) return false; - _saveInProgress = true; + // 先返回任务,保证同步取消/失败也会清理已登记的在途任务。 + await Task.Yield(); try { - bool saved = saveAs ? await RequestSaveAs() : await SaveCore(); - if (!saved) return false; - await ServiceHub.FlushFileSystemAsync(); - if (OperatingSystem.IsBrowser()) ToastService.Enqueue(L.S("Editor.Saved")); - return true; + return await operation(); } catch (Exception exception) { Log.Error(exception, "保存工程失败"); - if (OperatingSystem.IsBrowser()) DocManager.Inst.Project.Saved = false; DocManager.Inst.ExecuteCmd(new ErrorMessageNotification(exception)); return false; } - finally { _saveInProgress = false; } + finally { _manualSaveTask = null; } + } + + /// 复用现有模态加载窗口显示阶段,整个手动保存期间禁用编辑器输入。 + private async Task SaveWithProgressAsync(string path, bool template) + { + if (!OwnsSaveDocument()) return false; + bool saved = false; + IsSavingProject = true; + try + { + await LoadingPopupService.RunAsync(L.S("ProjectSave.Capturing"), async loading => + { + Progress progress = new(stage => loading.SetIndeterminate(L.S($"ProjectSave.{stage}"))); + if (OwnsSaveDocument()) + saved = await ProjectSaveCoordinator.Inst.SaveManualAsync(_saveOwner!, path, template, progress); + }); + if (saved && OwnsSaveDocument()) ToastService.Enqueue(L.S("Editor.Saved")); + return saved && OwnsSaveDocument(); + } + finally { IsSavingProject = false; } } } diff --git a/OpenUtauMobile/ViewModels/EditorViewModel.cs b/OpenUtauMobile/ViewModels/EditorViewModel.cs index 747884e6..3331b991 100644 --- a/OpenUtauMobile/ViewModels/EditorViewModel.cs +++ b/OpenUtauMobile/ViewModels/EditorViewModel.cs @@ -21,6 +21,7 @@ using OpenUtauMobile.Services; using OpenUtauMobile.Services.Dialogs; using OpenUtauMobile.Services.Editor; +using OpenUtauMobile.Services.Projects; using OpenUtauMobile.Services.Tracks; using OpenUtauMobile.Storage; using OpenUtauMobile.Themes.OpenUtauMobile.Runtime.Generation; @@ -64,6 +65,7 @@ public partial class EditorViewModel : NavigateViewModelBase, ICmdSubscriber, ID private readonly ProjectOpenOptions _projectOpenOptions; private bool _loadStarted; private bool _projectLoaded; + private DocManager.SaveCheckpoint? _saveOwner; private PreparedProject? _preparedProject; private bool _disposed; private readonly TaskCompletionSource _projectLoadCompletion = @@ -72,6 +74,10 @@ public partial class EditorViewModel : NavigateViewModelBase, ICmdSubscriber, ID [Reactive] public bool IsLoadingProject { get; private set; } = true; + /// 手动保存期间限制工程交互,进度由主窗口的模态弹窗显示。 + [Reactive] + public bool IsSavingProject { get; private set; } + #region 响应式命令 /// @@ -444,7 +450,7 @@ internal EditorViewModel(MainViewModel navigator, ProjectOpenOptions? projectOpe { Interval = TimeSpan.FromSeconds(Math.Max(Preferences.Default.AutoSaveInterval, 30)) }; - _autoSaveTimer.Tick += (_, _) => AutoSaveProject(); + _autoSaveTimer.Tick += (_, _) => _ = AutoSaveProjectAsync(); } // TrackHeight 变更时,MaxTrackOffset 依赖它,置脏并重新校验。目前设计下轨道高度不变,但预留了修改接口,保持逻辑完整性。 @@ -511,27 +517,10 @@ internal static async Task PrepareProjectAsync(ProjectOpenOptio return new PreparedProject(project, repairedPhonemizers); } - private static void AutoSaveProject() + private async Task AutoSaveProjectAsync() { - UProject project = DocManager.Inst.Project; - string originalProjectPath = project.FilePath; - if (!string.IsNullOrEmpty(originalProjectPath)) - { - DocManager.Inst.AutoSave(); - return; - } - - // 未命名工程需要一个临时序列化基准目录,波形分片才能生成相对路径。 - Directory.CreateDirectory(PathManager.Inst.BackupsPath); - project.FilePath = Path.Combine(PathManager.Inst.BackupsPath, "Untitled.ustx"); - try - { - DocManager.Inst.AutoSave(); - } - finally - { - project.FilePath = originalProjectPath; - } + if (!_disposed && _projectLoaded && !IsSavingProject && _saveOwner is { } owner) + await ProjectSaveCoordinator.Inst.AutoSaveAsync(owner); } /// @@ -555,6 +544,7 @@ private async Task LoadProjectAsync(ProjectOpenOptions openOptions) DocManager.Inst.Recovered = false; DocManager.Inst.ExecuteCmd(new SeekPlayPosTickNotification(0)); _projectLoaded = true; + _saveOwner = DocManager.Inst.CaptureSaveCheckpoint(); loadSucceeded = true; PlaybackTimer.Start(); _autoSaveTimer?.Start(); @@ -701,9 +691,8 @@ await VoiceColorMappingService.ValidateAsync(mappingProject, mappingTrack, RequestInvalidateVisual?.Invoke(); break; case SaveProjectNotification saveProjectNotification: - if (!OperatingSystem.IsBrowser()) ToastService.Enqueue(L.S("Editor.Saved")); ProjectPath = DocManager.Inst.Project.FilePath; - Preferences.AddRecentFileIfEnabled(saveProjectNotification.Path); + this.RaisePropertyChanged(nameof(Saved)); break; } } @@ -832,24 +821,17 @@ public async Task ExecuteEditorActionAsync(EditorMoreAction action) private async Task SaveAsTemplateAsync() { - UProject project = DocManager.Inst.Project; - string? file = await TextInputPopupService.ShowAsync( - L.S("EditorMore.SaveAsTemplate"), string.Empty, - L.S("ProjectTemplates.Name"), "default"); - if (string.IsNullOrEmpty(file) || _disposed || DocManager.Inst.Project != project || - (ServiceHub.UseDesktopFileWorkflows ? Navigator.ActiveEditor != this : Navigator.CurrentViewModel != this)) return; - try - { - file = Path.GetFileNameWithoutExtension(file); - file = Path.Combine(PathManager.Inst.TemplatesPath, $"{file}.ustx"); - Directory.CreateDirectory(PathManager.Inst.TemplatesPath); - Ustx.Save(file, project.CloneAsTemplate()); - await ServiceHub.FlushFileSystemAsync(); - } - catch (Exception exception) + await RunManualSaveAsync(async () => { - ErrorDialogService.Show(new ErrorDialogViewModel(new ErrorMessageNotification(exception))); - } + if (!OwnsSaveDocument()) return false; + string? name = await TextInputPopupService.ShowAsync( + L.S("EditorMore.SaveAsTemplate"), string.Empty, + L.S("ProjectTemplates.Name"), "default"); + if (string.IsNullOrWhiteSpace(name) || !OwnsSaveDocument()) return false; + name = Path.GetFileNameWithoutExtension(name); + if (string.IsNullOrWhiteSpace(name)) return false; + return await SaveWithProgressAsync(Path.Combine(PathManager.Inst.TemplatesPath, $"{name}.ustx"), template: true); + }); } private static async Task ImportAudio() @@ -1665,38 +1647,28 @@ private void Redo() /// /// 实际执行保存 /// - /// 置空表示保存到原位 - private static void SaveAs(string fileName) - { - DocManager.Inst.ExecuteCmd(new SaveProjectNotification(fileName)); - } - /// - /// 判断直接保存还是另存为 - /// private Task Save() => SaveFromInputAsync(false); private async Task SaveCore() { + if (!OwnsSaveDocument()) return false; if (ServiceHub.UseDesktopFileWorkflows ? string.IsNullOrEmpty(DocManager.Inst.Project.FilePath) : !Saved) return await RequestSaveAs(); - SaveAs(string.Empty); - return true; + return await SaveWithProgressAsync(DocManager.Inst.Project.FilePath, template: false); } /// /// 打开弹窗获取保存filename /// /// 是否成功保存 - private static async Task RequestSaveAs() + private async Task RequestSaveAs() { + if (!OwnsSaveDocument()) return false; if (ServiceHub.UseDesktopFileWorkflows || FilePickerWorkspace.IsSandboxed) { string destination = await FilePicker.SaveFileAsync(L.S("FilePicker.SaveProjectAs"), "ustx", string.IsNullOrEmpty(DocManager.Inst.Project.FilePath) ? L.S("FilePicker.DefaultProjectName") : Path.GetFileNameWithoutExtension(DocManager.Inst.Project.FilePath), Preferences.Default.LastSaveProjectDirectory); - if (string.IsNullOrEmpty(destination)) return false; - SaveAs(destination); - Preferences.Default.LastSaveProjectDirectory = Path.GetDirectoryName(destination) ?? string.Empty; - Preferences.Save(); - return true; + if (string.IsNullOrEmpty(destination) || !OwnsSaveDocument()) return false; + return await SaveWithProgressAsync(destination, template: false); } FilePickerPopup view = new(); // TODO: 使用统一文件入口 @@ -1706,14 +1678,11 @@ private static async Task RequestSaveAs() Preferences.Default.LastSaveProjectDirectory, L.S("FilePicker.DefaultProjectName")); string? fileName = await PopupService.Show(view, vm); - if (string.IsNullOrEmpty(fileName)) + if (string.IsNullOrEmpty(fileName) || !OwnsSaveDocument()) { return false; } - SaveAs(fileName); - Preferences.Default.LastSaveProjectDirectory = Path.GetDirectoryName(fileName) ?? Preferences.Default.LastSaveProjectDirectory; - Preferences.Save(); - return true; + return await SaveWithProgressAsync(fileName, template: false); } private static async Task ShowExitEditorConfirmPopupAsync() @@ -2460,22 +2429,28 @@ private async Task OnBackAsync() /// 已保存或用户确认退出时返回 true。 public async Task ConfirmExitAsync() { + if (_manualSaveTask != null && !await _manualSaveTask) return false; // 同步格式读取器会继续运行;离开后丢弃结果,返回操作不等待读取。 if (!_projectLoaded) return true; + if (!OwnsSaveDocument()) return false; if (DocManager.Inst.ChangesSaved) { return true; } + var revision = DocManager.Inst.Revision; byte actionRegister = await ShowExitEditorConfirmPopupAsync(); + if (!OwnsSaveDocument() || revision != DocManager.Inst.Revision) return false; switch ((ExitEditorActionRegister)actionRegister) { case ExitEditorActionRegister.ExitWithoutSave: + ProjectSaveCoordinator.Inst.DismissRecovery(); Preferences.Default.RecoveryPath = string.Empty; - Preferences.Save(); - return true; + await PreferencesWriter.Inst.SaveAsync(); + await ServiceHub.FlushFileSystemAsync(); + return OwnsSaveDocument() && revision == DocManager.Inst.Revision; case ExitEditorActionRegister.SaveAndExit: - return await Save(); + return await Save() && OwnsSaveDocument() && DocManager.Inst.ChangesSaved; case ExitEditorActionRegister.Cancel: default: return false; diff --git a/OpenUtauMobile/ViewModels/HomeViewModel.cs b/OpenUtauMobile/ViewModels/HomeViewModel.cs index c5d07e34..7e1186d0 100644 --- a/OpenUtauMobile/ViewModels/HomeViewModel.cs +++ b/OpenUtauMobile/ViewModels/HomeViewModel.cs @@ -174,6 +174,7 @@ private void OpenRecovery() private void DismissRecovery() { + Services.Projects.ProjectSaveCoordinator.Inst.DismissRecovery(); RecoveryBannerDismissed = true; RecoveryBannerHeight = 0; Preferences.Default.RecoveryPath = string.Empty; diff --git a/OpenUtauMobile/Views/EditorView.axaml b/OpenUtauMobile/Views/EditorView.axaml index 06df63ef..9cb2dd23 100644 --- a/OpenUtauMobile/Views/EditorView.axaml +++ b/OpenUtauMobile/Views/EditorView.axaml @@ -13,6 +13,7 @@ xmlns:foundation="clr-namespace:OpenUtauMobile.Themes.OpenUtauMobile.Tokens.Foundation" xmlns:semantic="clr-namespace:OpenUtauMobile.Themes.OpenUtauMobile.Tokens.Semantic" x:DataType="vm:EditorViewModel" + IsEnabled="{Binding !IsSavingProject}" Background="{DynamicResource Sem.Color.SurfaceContainerLow}"> diff --git a/OpenUtauMobile/Views/MainWindow.axaml.cs b/OpenUtauMobile/Views/MainWindow.axaml.cs index 4925840e..02af9670 100644 --- a/OpenUtauMobile/Views/MainWindow.axaml.cs +++ b/OpenUtauMobile/Views/MainWindow.axaml.cs @@ -1,6 +1,8 @@ using System; using Avalonia.Controls; using OpenUtauMobile.ViewModels; +using OpenUtauMobile.Services.Projects; +using OpenUtau.Core; using Serilog; namespace OpenUtauMobile.Views; @@ -39,11 +41,15 @@ private async void OnClosing(object? sender, WindowClosingEventArgs e) _closeRequestPending = true; try { + var project = DocManager.Inst.Project; + var revision = DocManager.Inst.Revision; if (!await mainViewModel.ConfirmCloseAsync()) { return; } + await PreferencesWriter.Inst.FlushAsync(); + if (!ReferenceEquals(project, DocManager.Inst.Project) || revision != DocManager.Inst.Revision) return; _closeConfirmed = true; Close(); } From 5261d96163226d32ffd5144913804c2d13d5ffb3 Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Fri, 6 Nov 2026 21:12:58 +0800 Subject: [PATCH 22/45] =?UTF-8?q?performance:=20=E5=B0=86=E6=AD=8C?= =?UTF-8?q?=E6=89=8B=E5=88=87=E6=8D=A2=E3=80=81voice=20mapping=E3=80=81?= =?UTF-8?q?=E9=9F=B3=E7=B4=A0=E5=8C=96=E7=AD=89=E5=BC=82=E6=AD=A5=E6=89=A7?= =?UTF-8?q?=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Views/DesktopTrackInspector.cs | 2 +- OpenUtauMobile/Assets/Lang/Strings.en.resx | 5 + OpenUtauMobile/Assets/Lang/Strings.ja.resx | 5 + OpenUtauMobile/Assets/Lang/Strings.ru.resx | 5 + OpenUtauMobile/Assets/Lang/Strings.uk.resx | 5 + .../Assets/Lang/Strings.zh-Hans.resx | 5 + .../Editor/EditorInputController.Keyboard.cs | 2 +- .../Services/Tracks/PhonemizationStatus.cs | 66 ++++++ .../Services/Tracks/TrackHeaderService.cs | 9 +- .../Tracks/TrackPreparationService.cs | 127 +++++++++++ .../Services/Tracks/TrackSettingsService.cs | 53 ++++- .../Tracks/VoiceColorMappingService.cs | 211 +++++++++++++----- OpenUtauMobile/ViewModels/EditorViewModel.cs | 25 +++ .../ViewModels/TrackHeaderViewModel.cs | 94 ++++---- .../ViewModels/TrackSettingsPopupViewModel.cs | 53 ++--- OpenUtauMobile/Views/EditorView.axaml | 7 +- 16 files changed, 530 insertions(+), 144 deletions(-) create mode 100644 OpenUtauMobile/Services/Tracks/PhonemizationStatus.cs create mode 100644 OpenUtauMobile/Services/Tracks/TrackPreparationService.cs diff --git a/OpenUtauMobile.DesktopUI/Views/DesktopTrackInspector.cs b/OpenUtauMobile.DesktopUI/Views/DesktopTrackInspector.cs index 206c13e9..d49541c9 100644 --- a/OpenUtauMobile.DesktopUI/Views/DesktopTrackInspector.cs +++ b/OpenUtauMobile.DesktopUI/Views/DesktopTrackInspector.cs @@ -108,7 +108,7 @@ void CommitName() || originalSettings.renderer != track.RendererSettings.renderer || originalSettings.resampler != track.RendererSettings.resampler || originalSettings.wavtool != track.RendererSettings.wavtool) return; - singerVm.SetSinger(chosen); + await singerVm.SetSingerAsync(chosen); }; ToolTip.SetTip(singer, DesktopUi.Label("TrackSettings.Singer")); body.Children.Add(singer); diff --git a/OpenUtauMobile/Assets/Lang/Strings.en.resx b/OpenUtauMobile/Assets/Lang/Strings.en.resx index c3293669..12bef8cf 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.en.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.en.resx @@ -2642,4 +2642,9 @@ Applying replaces the source of this input. Replacing project file… Synchronizing storage… Confirming saved version… + Loading singer resources… + Preparing phonemizer… + Applying track settings… + Preparing voice color mapping… + Phonemizing: {0} of {1} parts pending · {2}s diff --git a/OpenUtauMobile/Assets/Lang/Strings.ja.resx b/OpenUtauMobile/Assets/Lang/Strings.ja.resx index 47ab611c..b17baafc 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.ja.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.ja.resx @@ -2636,4 +2636,9 @@ Applying replaces the source of this input. プロジェクトファイルを置換中… ストレージを同期中… 保存したバージョンを確認中… + 歌手のリソースを読み込み中… + 音素変換器を準備中… + トラック設定を適用中… + 音色マッピングを準備中… + 音素変換中:残り {0}/{1} パート · {2} 秒経過 diff --git a/OpenUtauMobile/Assets/Lang/Strings.ru.resx b/OpenUtauMobile/Assets/Lang/Strings.ru.resx index fc229937..ddede28f 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.ru.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.ru.resx @@ -2595,4 +2595,9 @@ Applying replaces the source of this input. Замена файла проекта… Синхронизация хранилища… Подтверждение сохранённой версии… + Загрузка ресурсов певца… + Подготовка фонемайзера… + Применение настроек дорожки… + Подготовка сопоставления тембров… + Фонемизация: осталось {0} из {1} партий · {2} с diff --git a/OpenUtauMobile/Assets/Lang/Strings.uk.resx b/OpenUtauMobile/Assets/Lang/Strings.uk.resx index a2295475..7d97a289 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.uk.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.uk.resx @@ -2595,4 +2595,9 @@ Applying replaces the source of this input. Заміна файлу проєкту… Синхронізація сховища… Підтвердження збереженої версії… + Завантаження ресурсів співака… + Підготовка фонемайзера… + Застосування налаштувань доріжки… + Підготовка зіставлення тембрів… + Фонемізація: залишилося {0} з {1} партій · {2} с diff --git a/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx b/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx index 74d68ef7..51764dd6 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx @@ -2642,4 +2642,9 @@ 正在替换工程文件… 正在同步存储… 正在确认已保存版本… + 正在加载歌手资源… + 正在准备音素器… + 正在应用轨道设置… + 正在准备音色映射… + 正在音素化:剩余 {0}/{1} 个片段 · 已等待 {2} 秒 diff --git a/OpenUtauMobile/Services/Editor/EditorInputController.Keyboard.cs b/OpenUtauMobile/Services/Editor/EditorInputController.Keyboard.cs index a8c57351..8fe6b3b2 100644 --- a/OpenUtauMobile/Services/Editor/EditorInputController.Keyboard.cs +++ b/OpenUtauMobile/Services/Editor/EditorInputController.Keyboard.cs @@ -29,7 +29,7 @@ public enum EditArea { Tracks, PianoRoll, Mixer } private bool IsEditorInputActive => _inputRoot != null && TopLevel.GetTopLevel(_owner) == _inputRoot && _owner.IsEffectivelyVisible && _owner.IsEffectivelyEnabled && !IsModalOpen && !HasInputPopup && - _owner.DataContext is EditorViewModel { IsLoadingProject: false, IsSavingProject: false }; + _owner.DataContext is EditorViewModel { IsLoadingProject: false, CanEditProject: true }; private static bool IsWithin(Visual? source, Visual parent) => source != null && source.GetSelfAndVisualAncestors().Contains(parent); diff --git a/OpenUtauMobile/Services/Tracks/PhonemizationStatus.cs b/OpenUtauMobile/Services/Tracks/PhonemizationStatus.cs new file mode 100644 index 00000000..a8c624ed --- /dev/null +++ b/OpenUtauMobile/Services/Tracks/PhonemizationStatus.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using Avalonia.Threading; +using OpenUtau.Core.Ustx; + +namespace OpenUtauMobile.Services.Tracks; + +/// 只在 UI 观察 Core 已有的音素结果版本,不新增后台队列或改变音素器的串行约束。 +internal sealed class PhonemizationStatus : IDisposable +{ + private readonly Func currentProject; + private readonly Action update; + private readonly DispatcherTimer timer; + private readonly HashSet batch = []; + private readonly Stopwatch elapsed = new(); + private UProject? project; + + internal PhonemizationStatus(Func currentProject, Action update) + { + this.currentProject = currentProject; + this.update = update; + timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(200) }; + timer.Tick += OnTick; + timer.Start(); + } + + /// 等待包括排队、模型初始化和远程调用;真实完成以当前片段结果版本为准。 + private void OnTick(object? sender, EventArgs args) + { + UProject? current = currentProject(); + if (!ReferenceEquals(project, current)) + { + project = current; + batch.Clear(); + elapsed.Reset(); + } + if (current == null) + { + update(0, 0, TimeSpan.Zero); + return; + } + UVoicePart[] pending = [.. current.parts.OfType().Where(part => !part.PhonemesUpToDate)]; + if (pending.Length == 0) + { + batch.Clear(); + elapsed.Reset(); + update(0, 0, TimeSpan.Zero); + return; + } + if (!elapsed.IsRunning) elapsed.Restart(); + HashSet currentParts = [.. current.parts]; + batch.RemoveWhere(part => !currentParts.Contains(part)); + batch.UnionWith(pending); + update(pending.Length, batch.Count, elapsed.Elapsed); + } + + /// 编辑器销毁后停止观察,释放片段引用。 + public void Dispose() + { + timer.Stop(); + timer.Tick -= OnTick; + batch.Clear(); + } +} diff --git a/OpenUtauMobile/Services/Tracks/TrackHeaderService.cs b/OpenUtauMobile/Services/Tracks/TrackHeaderService.cs index 9474f94a..37fb5287 100644 --- a/OpenUtauMobile/Services/Tracks/TrackHeaderService.cs +++ b/OpenUtauMobile/Services/Tracks/TrackHeaderService.cs @@ -42,7 +42,14 @@ public static TrackHeaderService Inst try { PhonemizerPickerResult? result = await PhonemizerPickerService.PickAsync(new(CurrentName: currentName, Anchor: anchor)); - return result?.Factory?.Create(); + if (result?.Factory is not { } factory) return null; + Phonemizer? prepared = null; + await TrackPreparationService.Inst.RunAsync(async loading => + { + loading.SetIndeterminate(L.S("TrackPreparation.Phonemizer")); + prepared = await Task.Run(factory.Create); + }); + return prepared; } catch (System.Exception exception) { diff --git a/OpenUtauMobile/Services/Tracks/TrackPreparationService.cs b/OpenUtauMobile/Services/Tracks/TrackPreparationService.cs new file mode 100644 index 00000000..11776e71 --- /dev/null +++ b/OpenUtauMobile/Services/Tracks/TrackPreparationService.cs @@ -0,0 +1,127 @@ +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using Avalonia.Threading; +using OpenUtau.Api; +using OpenUtau.Core; +using OpenUtau.Core.Ustx; +using OpenUtau.Core.Util; +using OpenUtauMobile.Helpers; +using OpenUtauMobile.Services.Dialogs; +using OpenUtauMobile.ViewModels; +using ReactiveUI; +using ReactiveUI.Fody.Helpers; +using Serilog; + +namespace OpenUtauMobile.Services.Tracks; + +/// 先展示模态,再准备独立的歌手资源和音素器;活动轨道只在 UI 提交。 +public sealed class TrackPreparationService : ReactiveObject +{ + private static readonly ConditionalWeakTable SingerLocks = new(); + /// 所有轨道准备共享一个模态事务,避免重复打开同一弹窗宿主。 + public static TrackPreparationService Inst { get; } = new(); + + /// 准备及提交期间禁止编辑,后台音素化不占用此状态。 + [Reactive] public bool IsBusy { get; private set; } + + /// 拒绝重复的准备请求,异常在弹窗关闭和编辑解锁后传递。 + public async Task RunAsync(Func operation) + { + Dispatcher.UIThread.VerifyAccess(); + if (IsBusy || DocManager.Inst.HasOpenUndoGroup) return false; + IsBusy = true; + try + { + await LoadingPopupService.RunAsync(L.S("TrackPreparation.Singer"), operation); + return true; + } + finally { IsBusy = false; } + } + + /// 仅装载歌手资源,不在这里调用音素器 SetSinger;后者始终由原有后台队列串行执行。 + internal static async Task EnsureSingerAsync(USinger? singer) + { + if (singer is not { Found: true }) return; + Stopwatch watch = Stopwatch.StartNew(); + await Task.Run(() => + { + lock (SingerLocks.GetValue(singer, _ => new object())) + { + singer.EnsureLoaded(); + if (!singer.Loaded) throw new InvalidOperationException($"Failed to load singer: {singer.Name}"); + } + }); + Log.Information("轨道准备 Singer:{Milliseconds:F2} ms,{Singer}", watch.Elapsed.TotalMilliseconds, singer.Id); + } + + /// 在 UI 读取偏好;耗时构造仅作用于尚未提交的音素器实例。 + internal static async Task PrepareSingerAsync(USinger singer, LoadingPopupViewModel loading) + { + Preferences.Default.SingerPhonemizers.TryGetValue(singer.Id ?? string.Empty, out string? remembered); + await EnsureSingerAsync(singer); + loading.SetIndeterminate(L.S("TrackPreparation.Phonemizer")); + Stopwatch watch = Stopwatch.StartNew(); + Phonemizer? result = await Task.Run(() => + { + Phonemizer? prepared = TryCreate(remembered) ?? TryCreate(singer.DefaultPhonemizer); + if (singer.Found) + { + string renderer = ExternalSingerPluginService.GetDefaultRenderer(singer); + if (!string.IsNullOrEmpty(renderer)) OpenUtau.Core.Render.Renderers.GetOrCreate(renderer); + } + return prepared; + }); + Log.Information("轨道准备 Phonemizer:{Milliseconds:F2} ms", watch.Elapsed.TotalMilliseconds); + return result; + } + + /// 兼容原有默认音素器回退,但记录构造失败。 + private static Phonemizer? TryCreate(string? identifier) + { + if (string.IsNullOrWhiteSpace(identifier)) return null; + try { return PhonemizerFactory.Get(identifier)?.Create(); } + catch (Exception error) + { + Log.Error(error, "无法准备音素器 {Phonemizer}", identifier); + return null; + } + } +} + +/// 捕获会话和轨道配置,防止等待期间重载同一个工程实例后误提交。 +internal sealed class TrackPreparationOwner +{ + private readonly DocManager.SaveCheckpoint session = DocManager.Inst.CaptureSaveCheckpoint(); + private readonly UProject project; + private readonly UTrack track; + private readonly USinger? singer; + private readonly Phonemizer phonemizer; + private readonly URenderSettings settings; + private readonly string? graph; + + internal TrackPreparationOwner(UProject project, UTrack track) + { + this.project = project; + this.track = track; + singer = track.Singer; + phonemizer = track.Phonemizer; + settings = track.RendererSettings.Clone(); + graph = track.ExpressionGraph; + } + + /// 提交后配置已变化,收尾只检查原文档会话。 + internal bool IsSessionCurrent => DocManager.Inst.IsSaveCheckpointCurrent(session); + + /// 派生音素结果可更新;会话、轨道身份及用户选择的配置必须保持一致。 + internal bool IsCurrent => IsSessionCurrent && + ReferenceEquals(project, DocManager.Inst.Project) && project.tracks.Contains(track) && + ReferenceEquals(singer, track.Singer) && ReferenceEquals(phonemizer, track.Phonemizer) && + settings.renderer == track.RendererSettings.renderer && settings.resampler == track.RendererSettings.resampler && + settings.wavtool == track.RendererSettings.wavtool && graph == track.ExpressionGraph; + + /// 目录扫描替换歌手实例后,旧准备结果不再可用。 + internal static bool IsAvailable(USinger singer) => !singer.Found || + SingerManager.Inst.Singers.TryGetValue(singer.Id, out USinger? registered) && ReferenceEquals(singer, registered); +} diff --git a/OpenUtauMobile/Services/Tracks/TrackSettingsService.cs b/OpenUtauMobile/Services/Tracks/TrackSettingsService.cs index 67a61ae5..36d24bf1 100644 --- a/OpenUtauMobile/Services/Tracks/TrackSettingsService.cs +++ b/OpenUtauMobile/Services/Tracks/TrackSettingsService.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Threading.Tasks; -using Avalonia.Threading; using OpenUtau.Api; using OpenUtau.Core; using OpenUtau.Core.Ustx; @@ -23,7 +23,7 @@ private TrackSettingsService() { } public async Task ShowAsync(UTrack track) { - if (sessionOpen || !DocManager.Inst.Project.tracks.Contains(track)) return; + if (sessionOpen || TrackPreparationService.Inst.IsBusy || DocManager.Inst.HasOpenUndoGroup || !DocManager.Inst.Project.tracks.Contains(track)) return; sessionOpen = true; TrackSettingsPopupViewModel? sessionViewModel = null; try @@ -31,13 +31,29 @@ public async Task ShowAsync(UTrack track) TrackSettingsPopupViewModel viewModel = sessionViewModel = new(DocManager.Inst.Project, track); while (true) { + if (viewModel.IsStale) return; TrackSettingsAction action = await PopupService.Show(new TrackSettingsPopup(), viewModel); switch (action) { case TrackSettingsAction.PickSinger: { USinger? singer = await TrackHeaderService.Inst.PickSingerAsync(viewModel.DraftSinger); - if (singer != null) viewModel.SetSinger(singer); + if (singer != null) + { + try + { + await TrackPreparationService.Inst.RunAsync(async loading => + { + Phonemizer? prepared = await TrackPreparationService.PrepareSingerAsync(singer, loading); + if (!viewModel.IsStale && TrackPreparationOwner.IsAvailable(singer)) viewModel.SetSinger(singer, prepared); + }); + } + catch (Exception exception) + { + Serilog.Log.Error(exception, "Failed to prepare track settings singer"); + viewModel.Error = exception.Message; + } + } break; } case TrackSettingsAction.PickPhonemizer: @@ -48,8 +64,14 @@ public async Task ShowAsync(UTrack track) } case TrackSettingsAction.PickRenderer: { - string? renderer = await TrackHeaderService.Inst.PickRendererNameAsync(viewModel.Renderers.ToArray()); - if (renderer != null) viewModel.SetRenderer(renderer); + string? renderer = await TrackHeaderService.Inst.PickRendererNameAsync([.. viewModel.Renderers]); + if (renderer != null) + await TrackPreparationService.Inst.RunAsync(async loading => + { + loading.SetIndeterminate(L.S("TrackPreparation.Applying")); + await Task.Run(() => OpenUtau.Core.Render.Renderers.GetOrCreate(renderer)); + if (!viewModel.IsStale) viewModel.SetRenderer(renderer); + }); break; } case TrackSettingsAction.EditExpressions: @@ -64,7 +86,21 @@ public async Task ShowAsync(UTrack track) case TrackSettingsAction.Apply: { bool singerChanged = false; - bool applied = await Dispatcher.UIThread.InvokeAsync(() => TryApply(viewModel, out singerChanged)); + bool applied = false; + try + { + await TrackPreparationService.Inst.RunAsync(async loading => + { + await viewModel.PrepareApplyAsync(); + loading.SetIndeterminate(L.S("TrackPreparation.Applying")); + applied = TryApply(viewModel, out singerChanged); + }); + } + catch (Exception exception) + { + Serilog.Log.Error(exception, "Failed to prepare mobile track settings"); + viewModel.Error = exception.Message; + } if (applied) { if (singerChanged) @@ -110,10 +146,12 @@ private static bool TryApply(TrackSettingsPopupViewModel viewModel, out bool sin } if (commands.Count == 0) return true; DocManager manager = DocManager.Inst; + Stopwatch commit = Stopwatch.StartNew(); bool ownsUndoGroup = false; try { - manager.StartUndoGroup("TrackSettings.Apply", deferValidate: true); + // 复用 Mobile 的帧合并校验;避免全量校验在 UI 释放刚换下的歌手,令撤销时再次同步加载。 + manager.StartUndoGroup("TrackSettings.Apply"); ownsUndoGroup = true; foreach (UCommand command in commands) manager.ExecuteCmd(command); // 使用最终轨道设置校验图引用,并与设置修改一起撤销。 @@ -136,6 +174,7 @@ private static bool TryApply(TrackSettingsPopupViewModel viewModel, out bool sin ? L.S("TrackSettings.Error.Apply") : exception.Message; return false; } + Serilog.Log.Information("轨道提交 Settings:{Milliseconds:F2} ms", commit.Elapsed.TotalMilliseconds); try { SavePreferences(viewModel, singerChanged, diff --git a/OpenUtauMobile/Services/Tracks/VoiceColorMappingService.cs b/OpenUtauMobile/Services/Tracks/VoiceColorMappingService.cs index 1f0afbc2..6f2a4d19 100644 --- a/OpenUtauMobile/Services/Tracks/VoiceColorMappingService.cs +++ b/OpenUtauMobile/Services/Tracks/VoiceColorMappingService.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Threading.Tasks; +using Avalonia.Threading; using OpenUtau.Core; using OpenUtau.Core.Format; using OpenUtau.Core.Ustx; @@ -27,28 +29,35 @@ public static class VoiceColorMappingService public static async Task ValidateAsync(UProject project, UTrack? requestedTrack = null, bool validate = true) { DocManager manager = DocManager.Inst; - if (isMapping || !ReferenceEquals(manager.Project, project)) return; + if (isMapping || TrackPreparationService.Inst.IsBusy || !ReferenceEquals(manager.Project, project)) return; if (manager.HasOpenUndoGroup) throw new InvalidOperationException("An edit is still active."); - UTrack[] tracks = requestedTrack == null ? project.tracks.ToArray() : [requestedTrack]; + UTrack[] tracks = requestedTrack == null ? [.. project.tracks] : [requestedTrack]; isMapping = true; - manager.StartUndoGroup("VoiceMapping.Undo"); try { foreach (UTrack track in tracks) { if (!IsCurrent(project, track)) break; - string[] oldColors = track.VoiceColorNames.ToArray(); - string[] newColors = track.VoiceColorExp?.options ?? []; - if (!validate || track.ValidateVoiceColor(out oldColors, out newColors)) + TrackPreparationOwner owner = new(project, track); + if (track.Singer is { Found: true, Loaded: false } singer) + { + await TrackPreparationService.Inst.RunAsync(async _ => await TrackPreparationService.EnsureSingerAsync(singer)); + if (!owner.IsCurrent) return; + track.Validate(new ValidateOptions { SkipTiming = true }, project); + } + string[] oldColors = [.. track.VoiceColorNames]; + string[] newColors = [.. track.VoiceColorExp?.options ?? []]; + // 不调用会提前覆盖 VoiceColorNames 的校验方法,取消映射后保留原音色表。 + if (!validate || oldColors.Length > 1 && newColors.Length > 0 && !oldColors.SequenceEqual(newColors)) { - UVoicePart[] parts = project.parts.OfType() - .Where(part => part.trackNo == track.TrackNo && part.notes.Count > 0).ToArray(); + UVoicePart[] parts = [.. project.parts.OfType() + .Where(part => part.trackNo == track.TrackNo && part.notes.Count > 0)]; if (parts.Length > 0 && newColors.Length > 0) { VoiceColorMappingViewModel model = new(oldColors, newColors, track.TrackName); - if (await PopupService.Show(new VoiceColorMappingPopup(), model) && IsCurrent(project, track)) + if (await PopupService.Show(new VoiceColorMappingPopup(), model) && owner.IsCurrent) { - ApplyVoiceColors(project, track, parts, model); + await ApplyVoiceColorsAsync(project, track, parts, model, owner, newColors); } } else if (!validate) @@ -56,85 +65,165 @@ public static async Task ValidateAsync(UProject project, UTrack? requestedTrack ToastService.Enqueue(L.S("VoiceMapping.NoNotes")); } } - if (IsCurrent(project, track)) await RemapVocalModesAsync(project, track); + if (owner.IsCurrent) await RemapVocalModesAsync(project, track, owner); } } finally { - try - { - if (ReferenceEquals(manager.Project, project) && manager.HasOpenUndoGroup) manager.EndUndoGroup(); - } - finally - { - isMapping = false; - } + isMapping = false; } } private static bool IsCurrent(UProject project, UTrack track) => ReferenceEquals(DocManager.Inst.Project, project) && project.tracks.Contains(track); - private static void ApplyVoiceColors(UProject project, UTrack track, IEnumerable parts, - VoiceColorMappingViewModel model) + /// 在模态下分片捕获音素表达式,后台查表,最后只提交一个可撤销命令。 + private static async Task ApplyVoiceColorsAsync(UProject project, UTrack track, UVoicePart[] parts, + VoiceColorMappingViewModel model, TrackPreparationOwner owner, string[] newColors) { - foreach (UVoicePart part in parts) + Dictionary mappings = model.Mappings.ToDictionary(row => (float)row.OldIndex, row => row.SelectedIndex); + await TrackPreparationService.Inst.RunAsync(async loading => { - foreach (UPhoneme phoneme in part.phonemes) + loading.SetIndeterminate(L.S("TrackPreparation.Mapping")); + List<(UVoicePart Part, UPhoneme Phoneme, float Value)> inputs = []; + int work = 0; + foreach (UVoicePart part in parts) { - float oldValue = phoneme.GetExpression(project, track, Ustx.CLR).Item1; - VoiceColorMappingRow? mapping = model.Mappings.FirstOrDefault(row => row.OldIndex == oldValue); - if (mapping != null && mapping.OldIndex == mapping.SelectedIndex) continue; - float? value = mapping == null || mapping.SelectedIndex == DefaultIndex ? null : mapping.SelectedIndex; - DocManager.Inst.ExecuteCmd(new SetPhonemeExpressionCommand(project, track, part, phoneme, Ustx.CLR, value)); + // 后台响应可能替换派生音素列表,分片前先固定本批引用,不持有活动枚举器跨 await。 + UPhoneme[] phonemes = [.. part.phonemes]; + foreach (UPhoneme phoneme in phonemes) + { + if (!owner.IsCurrent) return; + inputs.Add((part, phoneme, phoneme.GetExpression(project, track, Ustx.CLR).Item1)); + if (++work % 128 == 0) await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Background); + } } - } + (int Index, float? Value)[] results = await Task.Run<(int Index, float? Value)[]>(() => [.. inputs.Select((input, index) => + { + bool found = mappings.TryGetValue(input.Value, out int selected); + return (Index: index, Value: found && selected != DefaultIndex ? (float?)selected : null, + Changed: !found || selected != input.Value); + }).Where(result => result.Changed).Select(result => (result.Index, result.Value))]); + if (!owner.IsCurrent) return; + List commands = []; + foreach ((int index, float? value) in results) + { + (UVoicePart part, UPhoneme phoneme, _) = inputs[index]; + if (!project.parts.Contains(part) || phoneme.Parent == null || !part.notes.Contains(phoneme.Parent)) return; + commands.Add(new SetPhonemeExpressionCommand(project, track, part, phoneme, Ustx.CLR, value)); + if (++work % 128 == 0) await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Background); + } + if (!owner.IsCurrent) return; + string[] previousColors = track.VoiceColorNames; + Commit(new VoiceMappingCommand(project, track, + () => { foreach (SetPhonemeExpressionCommand command in commands) command.Execute(); track.VoiceColorNames = newColors; }, + () => { for (int index = commands.Count - 1; index >= 0; index--) commands[index].Unexecute(); track.VoiceColorNames = previousColors; }, + rephonemize: true)); + }); } - private static async Task RemapVocalModesAsync(UProject project, UTrack track) + private static async Task RemapVocalModesAsync(UProject project, UTrack track, TrackPreparationOwner owner) { if (track.Singer?.SingerType != USingerType.DiffSinger) return; - track.Singer.EnsureLoaded(); if (!track.Singer.Loaded) return; - UVoicePart[] parts = project.parts.OfType().Where(part => part.trackNo == track.TrackNo).ToArray(); - string[] modes = parts.SelectMany(part => part.curves) + UVoicePart[] parts = [.. project.parts.OfType().Where(part => part.trackNo == track.TrackNo)]; + string[] modes = [.. parts.SelectMany(part => part.curves) .Where(curve => curve.descriptor != null && IsImportedVocalModeCurve(curve.abbr)) .Select(curve => curve.descriptor.name).Where(name => !string.IsNullOrWhiteSpace(name)) - .Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); + .Distinct(StringComparer.OrdinalIgnoreCase)]; if (modes.Length == 0) return; - string[] colors = track.Singer.Subbanks.Select(subbank => subbank.Color).ToArray(); + string[] colors = [.. track.Singer.Subbanks.Select(subbank => subbank.Color)]; if (colors.Length == 0) return; - VoiceColorMappingViewModel model = new(new[] { string.Empty }.Concat(modes).ToArray(), colors, track.TrackName, true); - if (!await PopupService.Show(new VoiceColorMappingPopup(), model) || !IsCurrent(project, track)) return; - bool changed = false; - foreach (VoiceColorMappingRow mapping in model.Mappings.Where(row => row.OldIndex > DefaultIndex && row.SelectedIndex > DefaultIndex)) + VoiceColorMappingViewModel model = new([string.Empty, .. modes], colors, track.TrackName, true); + if (!await PopupService.Show(new VoiceColorMappingPopup(), model) || !owner.IsCurrent) return; + await TrackPreparationService.Inst.RunAsync(async loading => { - string sourceName = modes[mapping.OldIndex - 1]; - UExpressionDescriptor? sourceDescriptor = project.expressions.Values.FirstOrDefault(descriptor => - descriptor.name.Equals(sourceName, StringComparison.OrdinalIgnoreCase)); - if (sourceDescriptor == null) continue; - string targetAbbr = VoiceCurvePrefix + mapping.SelectedIndex.ToString(VoiceCurveIndexFormat); - if (!project.expressions.TryGetValue(targetAbbr, out UExpressionDescriptor? targetDescriptor)) + loading.SetIndeterminate(L.S("TrackPreparation.Mapping")); + List descriptors = []; + List<(UVoicePart Part, UCurve Curve)> additions = []; + foreach (VoiceColorMappingRow mapping in model.Mappings.Where(row => row.OldIndex > DefaultIndex && row.SelectedIndex > DefaultIndex)) { - targetDescriptor = new UExpressionDescriptor($"voice color {colors[mapping.SelectedIndex]}", - targetAbbr, DefaultIndex, PercentMaximum, DefaultIndex) { type = UExpressionType.Curve }; - project.RegisterExpression(targetDescriptor); - } - foreach (UVoicePart part in parts) - { - UCurve? source = part.curves.FirstOrDefault(curve => curve.abbr == sourceDescriptor.abbr); - if (source == null || part.curves.Any(curve => curve.abbr == targetAbbr)) continue; - // 与桌面保持一致:复制曲线、归一化数值,不覆盖既有目标曲线。 - part.curves.Add(new UCurve(targetDescriptor) + string sourceName = modes[mapping.OldIndex - 1]; + UExpressionDescriptor? sourceDescriptor = project.expressions.Values.FirstOrDefault(descriptor => + descriptor.name.Equals(sourceName, StringComparison.OrdinalIgnoreCase)); + if (sourceDescriptor == null) continue; + string targetAbbr = VoiceCurvePrefix + mapping.SelectedIndex.ToString(VoiceCurveIndexFormat); + UExpressionDescriptor? targetDescriptor = descriptors.FirstOrDefault(descriptor => descriptor.abbr == targetAbbr); + if (targetDescriptor == null && !project.expressions.TryGetValue(targetAbbr, out targetDescriptor)) + { + targetDescriptor = new UExpressionDescriptor($"voice color {colors[mapping.SelectedIndex]}", + targetAbbr, DefaultIndex, PercentMaximum, DefaultIndex) { type = UExpressionType.Curve }; + descriptors.Add(targetDescriptor); + } + foreach (UVoicePart part in parts) { - xs = source.xs.ToList(), - ys = source.ys.Select(value => Math.Clamp(value <= NormalizedMaximum - ? value * PercentMaximum : value, DefaultIndex, PercentMaximum)).ToList(), - }); - changed = true; + UCurve? source = part.curves.FirstOrDefault(curve => curve.abbr == sourceDescriptor.abbr); + if (source == null || part.curves.Any(curve => curve.abbr == targetAbbr) || + additions.Any(addition => ReferenceEquals(addition.Part, part) && addition.Curve.abbr == targetAbbr)) continue; + // UI 只捕获数值快照,后台复制、归一化,不覆盖既有目标曲线。 + int[] xs = [.. source.xs]; + int[] ys = [.. source.ys]; + UCurve prepared = await Task.Run(() => new UCurve(targetDescriptor) + { + xs = [.. xs], + ys = [.. ys.Select(value => Math.Clamp(value <= NormalizedMaximum + ? value * PercentMaximum : value, DefaultIndex, PercentMaximum))], + }); + if (!owner.IsCurrent || !project.parts.Contains(part)) return; + additions.Add((part, prepared)); + } } + if (!owner.IsCurrent || additions.Count == 0) return; + Commit(new VoiceMappingCommand(project, track, + () => + { + foreach (UExpressionDescriptor descriptor in descriptors) project.RegisterExpression(descriptor); + foreach ((UVoicePart part, UCurve curve) in additions) part.curves.Add(curve); + }, + () => + { + foreach ((UVoicePart part, UCurve curve) in additions) part.curves.Remove(curve); + foreach (UExpressionDescriptor descriptor in descriptors) project.expressions.Remove(descriptor.abbr); + }, rephonemize: false)); + }); + } + + /// 等待弹窗和计算期间没有开放撤销组,提交后只触发一次合并校验。 + private static void Commit(VoiceMappingCommand command) + { + DocManager manager = DocManager.Inst; + if (manager.HasOpenUndoGroup) return; + Stopwatch commit = Stopwatch.StartNew(); + manager.StartUndoGroup("VoiceMapping.Undo"); + try { manager.ExecuteCmd(command); } + catch { manager.RollBackUndoGroup(); throw; } + finally + { + try { if (manager.HasOpenUndoGroup) manager.EndUndoGroup(); } + finally { Serilog.Log.Information("轨道提交 Mapping:{Milliseconds:F2} ms", commit.Elapsed.TotalMilliseconds); } } - if (changed) DocManager.Inst.ExecuteCmd(new ValidateProjectNotification()); + } + + /// 仅在 UI 原子地应用已准备的映射,撤销不重新运行映射计算。 + private sealed class VoiceMappingCommand : TrackCommand + { + private readonly Action apply; + private readonly Action undo; + private readonly bool rephonemize; + + internal VoiceMappingCommand(UProject project, UTrack track, Action apply, Action undo, bool rephonemize) + { + this.project = project; + this.track = track; + this.apply = apply; + this.undo = undo; + this.rephonemize = rephonemize; + } + + public override ValidateOptions ValidateOptions => new() { SkipTiming = true, SkipPhonemizer = !rephonemize }; + public override void Execute() => apply(); + public override void Unexecute() => undo(); + public override string ToString() => "Map track voice colors"; } private static bool IsImportedVocalModeCurve(string abbreviation) diff --git a/OpenUtauMobile/ViewModels/EditorViewModel.cs b/OpenUtauMobile/ViewModels/EditorViewModel.cs index 3331b991..27969402 100644 --- a/OpenUtauMobile/ViewModels/EditorViewModel.cs +++ b/OpenUtauMobile/ViewModels/EditorViewModel.cs @@ -78,6 +78,15 @@ public partial class EditorViewModel : NavigateViewModelBase, ICmdSubscriber, ID [Reactive] public bool IsSavingProject { get; private set; } + /// 资源准备及映射提交期间限制编辑,音素化运行期间仍可编辑。 + [Reactive] public bool IsPreparingTrack { get; private set; } + public bool CanEditProject => !IsSavingProject && !IsPreparingTrack; + + /// 独立于渲染进度显示后台音素化,避免不同任务互相清空状态。 + [Reactive] public bool IsPhonemizing { get; private set; } + [Reactive] public string PhonemizationMessage { get; private set; } = string.Empty; + public string DisplayProgressMessage => IsPhonemizing ? PhonemizationMessage : ProgressMessage; + #region 响应式命令 /// @@ -274,6 +283,20 @@ internal EditorViewModel(MainViewModel navigator, ProjectOpenOptions? projectOpe UndoCommand = ReactiveCommand.Create(Undo); RedoCommand = ReactiveCommand.Create(Redo); SaveCommand = ReactiveCommand.Create(Save); + TrackPreparationService.Inst.WhenAnyValue(service => service.IsBusy) + .Subscribe(busy => IsPreparingTrack = busy).DisposeWith(_disposables); + this.WhenAnyValue(vm => vm.IsSavingProject, vm => vm.IsPreparingTrack) + .Subscribe(_ => this.RaisePropertyChanged(nameof(CanEditProject))).DisposeWith(_disposables); + this.WhenAnyValue(vm => vm.IsPhonemizing, vm => vm.PhonemizationMessage, vm => vm.ProgressMessage) + .Subscribe(_ => this.RaisePropertyChanged(nameof(DisplayProgressMessage))).DisposeWith(_disposables); + new PhonemizationStatus(() => OwnsSaveDocument() ? DocManager.Inst.Project : null, + (pending, total, elapsed) => + { + IsPhonemizing = pending > 0; + PhonemizationMessage = pending > 0 + ? string.Format(L.S("Editor.Phonemizing"), pending, total, (int)elapsed.TotalSeconds) + : string.Empty; + }).DisposeWith(_disposables); InitializeEditorChrome(); // 播放/暂停命令 PlayPauseCommand = ReactiveCommand.Create(() => @@ -2470,6 +2493,8 @@ public void Dispose() ProgressValue = 0; ProgressMessage = string.Empty; PlaybackManager.Inst.StopPlayback(); // 停止回放 + IsPhonemizing = false; + PhonemizationMessage = string.Empty; PlaybackTimer.Stop(); // 停止定时器 _autoSaveTimer?.Stop(); // 停止自动保存定时器 _panMotion.Dispose(); diff --git a/OpenUtauMobile/ViewModels/TrackHeaderViewModel.cs b/OpenUtauMobile/ViewModels/TrackHeaderViewModel.cs index 2708ab05..a6c252c3 100644 --- a/OpenUtauMobile/ViewModels/TrackHeaderViewModel.cs +++ b/OpenUtauMobile/ViewModels/TrackHeaderViewModel.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics; using System.Linq; using System.Reactive; using System.Reactive.Disposables; @@ -15,6 +16,7 @@ using OpenUtau.Core.Ustx; using OpenUtau.Core.Util; using OpenUtauMobile.Services; +using OpenUtauMobile.Services.Dialogs; using OpenUtauMobile.Services.Tracks; using OpenUtauMobile.Themes.OpenUtauMobile.Runtime; using OpenUtauMobile.Themes.OpenUtauMobile.Runtime.Generation; @@ -121,26 +123,51 @@ public TrackHeaderViewModel(UTrack track) private async Task SelectSinger() { + if (DocManager.Inst.HasOpenUndoGroup) return; UProject project = DocManager.Inst.Project; + TrackPreparationOwner pickerOwner = new(project, _track); USinger? originalSinger = _track.Singer; URenderSettings originalSettings = _track.RendererSettings.Clone(); string? originalGraph = _track.ExpressionGraph; USinger? singer = await TrackHeaderService.Inst.PickSingerAsync(originalSinger); - if (singer == null || ReferenceEquals(singer, originalSinger) + if (singer == null || !pickerOwner.IsCurrent || ReferenceEquals(singer, originalSinger) || !ReferenceEquals(project, DocManager.Inst.Project) || !project.tracks.Contains(_track) || !ReferenceEquals(originalSinger, _track.Singer) || originalGraph != _track.ExpressionGraph || originalSettings.renderer != _track.RendererSettings.renderer || originalSettings.resampler != _track.RendererSettings.resampler || originalSettings.wavtool != _track.RendererSettings.wavtool || DocManager.Inst.HasOpenUndoGroup) return; - SetSinger(singer); + await SetSingerAsync(singer); } /// 切换歌手,并在同一撤销事务中校验轨道的表情图。 - public void SetSinger(USinger singer) + public async Task SetSingerAsync(USinger singer) { UProject project = DocManager.Inst.Project; - if (!project.tracks.Contains(_track) || DocManager.Inst.HasOpenUndoGroup || ReferenceEquals(_track.Singer, singer)) return; - ApplySinger(project, singer); + if (_disposed || !project.tracks.Contains(_track) || DocManager.Inst.HasOpenUndoGroup || ReferenceEquals(_track.Singer, singer)) return; + TrackPreparationOwner owner = new(project, _track); + bool applied = false; + try + { + await TrackPreparationService.Inst.RunAsync(async loading => + { + Phonemizer? phonemizer = await TrackPreparationService.PrepareSingerAsync(singer, loading); + string[] supported = await Task.Run(() => ExternalSingerPluginService.GetSupportedRenderers(singer)); + string renderer = supported.Contains(_track.RendererSettings.renderer) + ? _track.RendererSettings.renderer : await Task.Run(() => ExternalSingerPluginService.GetDefaultRenderer(singer)); + // 渲染器首次构造也可能加载资源,在提交前预热缓存。 + await Task.Run(() => OpenUtau.Core.Render.Renderers.GetOrCreate(renderer)); + if (_disposed || !owner.IsCurrent || !TrackPreparationOwner.IsAvailable(singer)) return; + loading.SetIndeterminate(OpenUtauMobile.Helpers.L.S("TrackPreparation.Applying")); + ApplySinger(project, singer, phonemizer, renderer); + applied = true; + }); + } + catch (Exception error) + { + Log.Error(error, "Failed to prepare track singer"); + ErrorDialogService.Show(new ErrorDialogViewModel(new ErrorMessageNotification(error))); + } + if (!applied || !owner.IsSessionCurrent || !project.tracks.Contains(_track) || !ReferenceEquals(_track.Singer, singer)) return; // 保存最近使用的歌手;切换事务已经完成。 if (!string.IsNullOrEmpty(singer.Id) && singer.Found) { @@ -151,11 +178,14 @@ public void SetSinger(USinger singer) } Preferences.Save(); Refresh(); + try { await VoiceColorMappingService.ValidateAsync(project, _track, true); } + catch (Exception error) { Log.Error(error, "Failed to remap track voice colors"); } } /// 统一歌手、音素器、渲染设置和表情图的切换事务。 - private void ApplySinger(UProject project, USinger singer) + private void ApplySinger(UProject project, USinger singer, Phonemizer? phonemizer, string renderer) { + Stopwatch commit = Stopwatch.StartNew(); DocManager.Inst.StartUndoGroup("切换歌手"); try { @@ -163,15 +193,8 @@ private void ApplySinger(UProject project, USinger singer) // 执行切换歌手命令 DocManager.Inst.ExecuteCmd(new TrackChangeSingerCommand(DocManager.Inst.Project, _track, singer)); // 切音素器 - if (!string.IsNullOrEmpty(singer.Id) && - Preferences.Default.SingerPhonemizers.TryGetValue(singer.Id, out string? phonemizerName) && - TryChangePhonemizer(phonemizerName)) - { - } - else if (!string.IsNullOrEmpty(singer.DefaultPhonemizer)) - { - TryChangePhonemizer(singer.DefaultPhonemizer); - } + if (phonemizer != null) + DocManager.Inst.ExecuteCmd(new TrackChangePhonemizerCommand(project, _track, phonemizer)); // 切渲染器 if (!singer.Found) // 默认渲染器 @@ -179,25 +202,35 @@ private void ApplySinger(UProject project, USinger singer) URenderSettings settings = new(); DocManager.Inst.ExecuteCmd(new TrackChangeRenderSettingCommand(DocManager.Inst.Project, _track, settings)); } - else if (!OpenUtauMobile.Services.ExternalSingerPluginService.GetSupportedRenderers(singer).Contains(_track.RendererSettings.renderer)) + else if (renderer != _track.RendererSettings.renderer) { URenderSettings settings = new() { - renderer = OpenUtauMobile.Services.ExternalSingerPluginService.GetDefaultRenderer(singer), // 根据歌手类型 + renderer = renderer, }; DocManager.Inst.ExecuteCmd(new TrackChangeRenderSettingCommand(DocManager.Inst.Project, _track, settings)); } TrackExpressionGraphSelection.Revalidate(project, _track); - DocManager.Inst.ExecuteCmd(new VoiceColorRemappingNotification(_track.TrackNo, true)); } - finally { DocManager.Inst.EndUndoGroup(); } + catch + { + DocManager.Inst.RollBackUndoGroup(); + throw; + } + finally + { + try { if (DocManager.Inst.HasOpenUndoGroup) DocManager.Inst.EndUndoGroup(); } + finally { Log.Information("轨道提交 Singer:{Milliseconds:F2} ms", commit.Elapsed.TotalMilliseconds); } + } } private async Task SelectPhonemizer(Control? anchor) { + if (DocManager.Inst.HasOpenUndoGroup) return; + TrackPreparationOwner owner = new(DocManager.Inst.Project, _track); Phonemizer? phonemizer = await TrackHeaderService.Inst.PickPhonemizerAsync(_track.Phonemizer?.Name, anchor); - if (phonemizer != null) SetPhonemizer(phonemizer); + if (!_disposed && owner.IsCurrent && phonemizer != null) SetPhonemizer(phonemizer); } public void SetPhonemizer(Phonemizer phonemizer) @@ -297,27 +330,6 @@ private void CommitMixParameter(MixCommand command) RefreshMix(); } - private bool TryChangePhonemizer(string phonemizerName) - { - try - { - PhonemizerFactory? factory = PhonemizerFactory.Get(phonemizerName); - Phonemizer? phonemizer = factory?.Create(); - if (phonemizer != null) - { - DocManager.Inst.ExecuteCmd( - new TrackChangePhonemizerCommand(DocManager.Inst.Project, _track, phonemizer)); - return true; - } - } - catch (Exception e) - { - Log.Error(e, $"无法加载音素器 {phonemizerName}"); - } - - return false; - } - private void RemoveTrack() { DocManager.Inst.StartUndoGroup("删除轨道"); diff --git a/OpenUtauMobile/ViewModels/TrackSettingsPopupViewModel.cs b/OpenUtauMobile/ViewModels/TrackSettingsPopupViewModel.cs index 1337528c..5be5a40c 100644 --- a/OpenUtauMobile/ViewModels/TrackSettingsPopupViewModel.cs +++ b/OpenUtauMobile/ViewModels/TrackSettingsPopupViewModel.cs @@ -3,6 +3,7 @@ using System.Collections.ObjectModel; using System.Linq; using System.Reactive; +using System.Threading.Tasks; using Avalonia; using OpenUtau.Api; using OpenUtau.Classic; @@ -11,6 +12,7 @@ using OpenUtau.Core.Ustx; using OpenUtau.Core.Util; using OpenUtauMobile.Helpers; +using OpenUtauMobile.Services.Tracks; using ReactiveUI; using ReactiveUI.Fody.Helpers; using CoreRenderers = OpenUtau.Core.Render.Renderers; @@ -35,13 +37,15 @@ public sealed class TrackSettingsPopupViewModel : PopupViewModelBase, IDisposabl { private readonly UProject project; private readonly UTrack track; + private readonly TrackPreparationOwner owner; private readonly URenderSettings originalRenderSettings; private readonly string? originalExpressionGraph; private readonly USinger? originalSinger; - private readonly Phonemizer? originalPhonemizer; + private readonly Phonemizer originalPhonemizer; private readonly UExpressionDescriptor[] originalTrackExpressions; private Phonemizer draftPhonemizer; private URenderSettings draftRenderSettings; + private URenderSettings? preparedRenderSettings; private bool changingSelection; private bool classicDraftInitialized; @@ -79,7 +83,7 @@ public sealed class TrackSettingsPopupViewModel : PopupViewModelBase, IDisposabl public Type? OriginalPhonemizerType => originalPhonemizer?.GetType(); public string DraftPhonemizerIdentifier => draftPhonemizer.Name; public IReadOnlyList DraftTrackExpressions { get; private set; } - public bool IsStale => !ReferenceEquals(DocManager.Inst.Project, project) || !project.tracks.Contains(track) || + public bool IsStale => !owner.IsCurrent || !ReferenceEquals(track.Singer, originalSinger) || track.Phonemizer?.GetType() != originalPhonemizer?.GetType() || !SameRenderSettings(track.RendererSettings, originalRenderSettings) || track.ExpressionGraph != originalExpressionGraph || !SameExpressions(track.TrackExpressions, originalTrackExpressions); @@ -88,6 +92,7 @@ public TrackSettingsPopupViewModel(UProject project, UTrack track) { this.project = project; this.track = track; + owner = new(project, track); originalSinger = track.Singer; originalPhonemizer = track.Phonemizer!; originalRenderSettings = track.RendererSettings.Clone(); @@ -114,7 +119,8 @@ public TrackSettingsPopupViewModel(UProject project, UTrack track) RebuildRendererChoices(false); } - public void SetSinger(USinger singer) + /// 只更新 UI 草稿,歌手资源和默认音素器须已在后台准备。 + public void SetSinger(USinger singer, Phonemizer? preparedPhonemizer) { if (ReferenceEquals(DraftSinger, singer)) return; changingSelection = true; @@ -135,7 +141,7 @@ public void SetSinger(USinger singer) } else { - SelectSingerPhonemizer(singer); + if (preparedPhonemizer != null) SetPhonemizer(preparedPhonemizer); } UpdateDirtyState(); RebuildRendererChoices(true); @@ -207,8 +213,7 @@ public bool TryPrepareApply(out List commands, out bool singerChanged, return false; } USinger? singer = DraftSinger; - if (singerChanged && singer is { Found: true } && !SingerManager.Inst.Singers.Values.Any(candidate => - ReferenceEquals(candidate, singer) || !string.IsNullOrEmpty(candidate.Id) && candidate.Id == singer.Id)) + if (singerChanged && singer is { Found: true } && !TrackPreparationOwner.IsAvailable(singer)) { error = L.S("TrackSettings.Error.SingerUnavailable"); return false; @@ -242,16 +247,12 @@ public bool TryPrepareApply(out List commands, out bool singerChanged, return false; } - URenderSettings renderSettings = draftRenderSettings.Clone(); + URenderSettings renderSettings = preparedRenderSettings?.Clone() ?? draftRenderSettings.Clone(); if (singer is { Found: true } && IsRenderSettingsDirty) { - try + if (preparedRenderSettings == null) { - renderSettings.Validate(new UTrack { Singer = singer }); - } - catch (Exception exception) - { - error = string.IsNullOrWhiteSpace(exception.Message) ? L.S("TrackSettings.Error.Apply") : exception.Message; + error = L.S("TrackSettings.Error.Busy"); return false; } } @@ -270,24 +271,15 @@ public bool TryPrepareApply(out List commands, out bool singerChanged, return true; } - private void SelectSingerPhonemizer(USinger singer) - { - Phonemizer? selected = null; - if (!string.IsNullOrEmpty(singer.Id) && Preferences.Default.SingerPhonemizers.TryGetValue(singer.Id, out string? remembered)) - selected = CreatePhonemizer(remembered); - selected ??= CreatePhonemizer(singer.DefaultPhonemizer); - if (selected != null) - { - draftPhonemizer = selected; - DraftPhonemizerName = selected.Tag; - } - } - - private static Phonemizer? CreatePhonemizer(string? name) + /// 在模态期间准备独立渲染设置;不把 ViewModel 或活动轨道交给后台。 + public async Task PrepareApplyAsync() { - if (string.IsNullOrWhiteSpace(name)) return null; - try { return PhonemizerFactory.Get(name)?.Create(); } - catch { return null; } + USinger? singer = DraftSinger; + URenderSettings settings = draftRenderSettings.Clone(); + await TrackPreparationService.EnsureSingerAsync(singer); + if (singer is { Found: true }) + await Task.Run(() => settings.Validate(new UTrack { Singer = singer })); + preparedRenderSettings = settings; } private void RebuildRendererChoices(bool chooseCompatibleDefault) @@ -441,6 +433,7 @@ private void RebuildToolChoices(bool resamplerWasChanged) private void UpdateDirtyState() { + preparedRenderSettings = null; IsRenderSettingsDirty = !SameRenderSettings(draftRenderSettings, originalRenderSettings); if (!changingSelection) Error = string.Empty; } diff --git a/OpenUtauMobile/Views/EditorView.axaml b/OpenUtauMobile/Views/EditorView.axaml index 9cb2dd23..7de3e569 100644 --- a/OpenUtauMobile/Views/EditorView.axaml +++ b/OpenUtauMobile/Views/EditorView.axaml @@ -13,7 +13,7 @@ xmlns:foundation="clr-namespace:OpenUtauMobile.Themes.OpenUtauMobile.Tokens.Foundation" xmlns:semantic="clr-namespace:OpenUtauMobile.Themes.OpenUtauMobile.Tokens.Semantic" x:DataType="vm:EditorViewModel" - IsEnabled="{Binding !IsSavingProject}" + IsEnabled="{Binding CanEditProject}" Background="{DynamicResource Sem.Color.SurfaceContainerLow}"> @@ -163,11 +163,14 @@ - + + From 322e2777d4fc0c6723b07bff14c833758f2e47c3 Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Sat, 7 Nov 2026 16:11:26 +0800 Subject: [PATCH 23/45] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8DAndroid=E5=B9=B3?= =?UTF-8?q?=E5=8F=B0=E9=94=99=E8=AF=AF=E7=9A=84=E9=80=80=E5=87=BA=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- OpenUtauMobile.Android/MainActivity.cs | 1 + OpenUtauMobile/Services/AppService.cs | 15 ++++++++++++--- OpenUtauMobile/Services/ServiceHub.cs | 2 ++ 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/OpenUtauMobile.Android/MainActivity.cs b/OpenUtauMobile.Android/MainActivity.cs index 559468a6..32a9a2a9 100644 --- a/OpenUtauMobile.Android/MainActivity.cs +++ b/OpenUtauMobile.Android/MainActivity.cs @@ -83,6 +83,7 @@ internal static AppBuilder ConfigureAppBuilder(AppBuilder builder) ServiceHub.PlatformCrashLogService = crashLogService; _ = crashLogService.CollectPreviousExitAsync(); ServiceHub.InitAudioOutput = InitAudioOutput; // 设置初始化音频输出的委托 + ServiceHub.PlatformExitApplication = () => CurrentActivity?.FinishAffinity(); ServiceHub.ExternalUrlLauncher = new AndroidExternalUrlLauncher(() => CurrentActivity); ServiceHub.ExternalStorageService = new AndroidExternalStorageService(() => CurrentActivity); // 设置外部存储服务 diff --git a/OpenUtauMobile/Services/AppService.cs b/OpenUtauMobile/Services/AppService.cs index 3a092f73..34a9b860 100644 --- a/OpenUtauMobile/Services/AppService.cs +++ b/OpenUtauMobile/Services/AppService.cs @@ -4,6 +4,8 @@ using OpenUtauMobile.Services.Projects; using Serilog; using OpenUtau.Core; +using OpenUtau.Core.Pipeline; +using OpenUtau.Core.Ustx; namespace OpenUtauMobile.Services; @@ -59,11 +61,18 @@ public static bool ExitApplication() /// 退出前异步刷新合并的偏好请求,主线程继续处理平台输入。 private static async Task FlushAndExitAsync() { - var project = DocManager.Inst.Project; - var revision = DocManager.Inst.Revision; + UProject project = DocManager.Inst.Project; + DocRevision revision = DocManager.Inst.Revision; try { await PreferencesWriter.Inst.FlushAsync(); } catch (Exception error) { Log.Error(error, "退出时刷新偏好失败"); } if (!ReferenceEquals(project, DocManager.Inst.Project) || revision != DocManager.Inst.Revision) return; - Environment.Exit(0); + if (ServiceHub.PlatformExitApplication is { } exitApplication) + { + exitApplication(); + } + else if (!OperatingSystem.IsAndroid()) + { + Environment.Exit(0); + } } } diff --git a/OpenUtauMobile/Services/ServiceHub.cs b/OpenUtauMobile/Services/ServiceHub.cs index bb531ce9..14a0397c 100644 --- a/OpenUtauMobile/Services/ServiceHub.cs +++ b/OpenUtauMobile/Services/ServiceHub.cs @@ -17,6 +17,8 @@ namespace OpenUtauMobile.Services; /// public static class ServiceHub { + /// 通过平台生命周期退出应用,避免直接终止进程。 + public static Action? PlatformExitApplication { get; set; } public static Func? DesktopWindowFactory { get; set; } public static IDesktopWindowContext? DesktopWindowContext { get; set; } public static Func? DesktopPopupSizeProvider { get; set; } From ba3027113e68913783bbb27cf57729324576d00f Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Sat, 7 Nov 2026 17:24:54 +0800 Subject: [PATCH 24/45] =?UTF-8?q?performance:=20=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E6=B5=8F=E8=A7=88=E5=99=A8=E9=9F=B3=E9=A2=91=E6=80=A7=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Services/Audio/BrowserAudioBuffer.cs | 81 +++++++++++ .../Services/Audio/BrowserAudioInterop.cs | 24 ++-- .../Services/Audio/BrowserAudioOutput.cs | 131 ++++++------------ .../wwwroot/audio-output-buffer.js | 4 +- .../wwwroot/audio-output-worklet.js | 19 +-- .../wwwroot/audio-output.js | 83 +++++------ 6 files changed, 178 insertions(+), 164 deletions(-) create mode 100644 OpenUtauMobile.Browser/Services/Audio/BrowserAudioBuffer.cs diff --git a/OpenUtauMobile.Browser/Services/Audio/BrowserAudioBuffer.cs b/OpenUtauMobile.Browser/Services/Audio/BrowserAudioBuffer.cs new file mode 100644 index 00000000..aa9bce4f --- /dev/null +++ b/OpenUtauMobile.Browser/Services/Audio/BrowserAudioBuffer.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Concurrent; +using System.Runtime.InteropServices; +using System.Threading; + +namespace OpenUtauMobile.Browser.Services.Audio; + +/// 固定在 WASM 共享内存中的单生产者、单消费者音频队列。 +internal sealed class BrowserAudioBuffer +{ + // 与 audio-output-buffer.js 共用布局;计数均为立体声帧,允许无符号回绕。 + private const int Read = 0, Write = 1, Playing = 2, Ended = 3, Consumed = 4, Running = 5; + private const int HeaderLength = 8; + internal const int Capacity = 4096; + internal const int TargetFrames = 2048; + private static readonly ConcurrentDictionary retained = new(); + private readonly int[] storage = new int[HeaderLength + Capacity * 2]; + private readonly GCHandle pin; + private uint lastConsumed; + private long consumedFrames; + + /// 固定队列地址,内存增长和托管回收均不会移动音频数据。 + internal BrowserAudioBuffer() => pin = GCHandle.Alloc(storage, GCHandleType.Pinned); + + /// 浏览器放弃引用且后台生产结束之后,才允许解除固定。 + ~BrowserAudioBuffer() + { + if (pin.IsAllocated) pin.Free(); + } + + /// 发布给浏览器的队列必须保活,直到音频线程确认已切换。 + internal int Retain(int generation) + { + retained[generation] = this; + return pin.AddrOfPinnedObject().ToInt32(); + } + + /// 音频线程确认旧队列不再使用后,移除浏览器持有的引用。 + internal static void Release(int generation) => retained.TryRemove(generation, out _); + + /// 直接发布播放意图,不依赖主线程及时处理控制消息。 + internal bool IsPlaying + { + get => Volatile.Read(ref storage[Playing]) != 0; + set => Volatile.Write(ref storage[Playing], value ? 1 : 0); + } + + /// 浏览器主线程只在上下文状态变化时更新运行标记。 + internal bool IsRunning => Volatile.Read(ref storage[Running]) != 0; + + /// 设备尚未消费的帧数;写指针只能在样本复制完成后发布。 + internal int QueuedFrames => unchecked((int)((uint)Volatile.Read(ref storage[Write]) - + (uint)Volatile.Read(ref storage[Read]))); + + /// 读取消费时钟并展开回绕;调用者须串行访问。 + internal long ConsumedFrames + { + get + { + uint current = unchecked((uint)Volatile.Read(ref storage[Consumed])); + consumedFrames += unchecked(current - lastConsumed); + lastConsumed = current; + return consumedFrames; + } + } + + /// 生产结束只发布标记,音频线程自行排空剩余样本。 + internal void EndInput() => Volatile.Write(ref storage[Ended], 1); + + /// 向已预留的空位写入交错样本,跨越环尾时分两段复制。 + internal void WriteSamples(ReadOnlySpan samples) + { + uint write = unchecked((uint)Volatile.Read(ref storage[Write])); + int offset = (int)(write % Capacity) * 2; + Span destination = MemoryMarshal.Cast(storage.AsSpan(HeaderLength)); + int first = Math.Min(samples.Length, destination.Length - offset); + samples[..first].CopyTo(destination[offset..]); + samples[first..].CopyTo(destination); + Volatile.Write(ref storage[Write], unchecked((int)(write + (uint)(samples.Length / 2)))); + } +} diff --git a/OpenUtauMobile.Browser/Services/Audio/BrowserAudioInterop.cs b/OpenUtauMobile.Browser/Services/Audio/BrowserAudioInterop.cs index 8d4d7edc..d2f27b9f 100644 --- a/OpenUtauMobile.Browser/Services/Audio/BrowserAudioInterop.cs +++ b/OpenUtauMobile.Browser/Services/Audio/BrowserAudioInterop.cs @@ -48,18 +48,19 @@ internal static List GetCurrentDevices() } } - /// 音频线程通过主线程通知请求下一批样本。 + /// 浏览器已不再读取旧队列,允许回收其固定内存。 [JSExport] - public static async Task RequestData(int generation) + public static Task ReleaseBuffer(int generation) { - await Dispatcher.UIThread.InvokeAsync(() => BrowserAudioOutput.Active?.Pump(generation)); + BrowserAudioBuffer.Release(generation); + return Task.CompletedTask; } /// 将消费时钟与上下文状态同步到托管快照。 [JSExport] - public static async Task UpdateStatus(int generation, double frames, int state, double latency) + public static async Task UpdateStatus(int generation, int state, double latency) { - await Dispatcher.UIThread.InvokeAsync(() => BrowserAudioOutput.Active?.UpdateStatus(generation, frames, state, latency)); + await Dispatcher.UIThread.InvokeAsync(() => BrowserAudioOutput.Active?.UpdateStatus(generation, state, latency)); } /// 异步接收浏览器错误,避免从 JS 主线程同步进入托管运行时。 @@ -105,17 +106,8 @@ await Dispatcher.UIThread.InvokeAsync(() => private static partial bool CanSelectOutput(); [JSImport("setPlayback", ModuleName)] - internal static partial void SetPlayback(int generation, int state); - - [JSImport("writableFrames", ModuleName)] - internal static partial int WritableFrames(int generation); - - [JSImport("writeSamples", ModuleName)] - internal static partial void WriteSamples(int generation, byte[] samples, int count); - - [JSImport("endInput", ModuleName)] - internal static partial void EndInput(int generation); + internal static partial void SetPlayback(int generation, int state, int address); [JSImport("selectOutput", ModuleName)] internal static partial Task SelectOutputAsync(); -} \ No newline at end of file +} diff --git a/OpenUtauMobile.Browser/Services/Audio/BrowserAudioOutput.cs b/OpenUtauMobile.Browser/Services/Audio/BrowserAudioOutput.cs index 9dc4bd03..2de48ce2 100644 --- a/OpenUtauMobile.Browser/Services/Audio/BrowserAudioOutput.cs +++ b/OpenUtauMobile.Browser/Services/Audio/BrowserAudioOutput.cs @@ -1,5 +1,4 @@ using System; -using System.Buffers; using System.Collections.Generic; using System.Threading; using Avalonia.Threading; @@ -11,27 +10,21 @@ namespace OpenUtauMobile.Browser.Services.Audio; -/// 后台生产浮点采样,通过主线程有界搬运到浏览器音频线程。 +/// 后台直接向 WASM 共享队列生产采样,浏览器音频线程独立消费。 internal sealed class BrowserAudioOutput : IAudioOutput, IAudioLatencySource, IDisposable { private const int Channels = 2; private const int BlockSamples = 1024 * Channels; - private const int QueueBlockCount = 2; private static BrowserAudioOutput? active; private static int nextGeneration; private readonly object syncRoot = new(); - private readonly Queue blocks = new(); - private readonly byte[] transferBuffer = new byte[BlockSamples * sizeof(float)]; + private BrowserAudioBuffer buffer = new(); private ISampleProvider? sampleProvider; - private PlaybackState playbackState; private int generation = Interlocked.Increment(ref nextGeneration); private int requestedState; - private int queuedSamples; - private double consumedFrames; private double transportLatency; private bool inputEnded; private bool synchronizationPosted; - private bool pumpPosted; private bool disposed; /// 原生音频线程不会进入托管运行时,由这个后台线程读取采样源。 @@ -63,20 +56,28 @@ public BrowserAudioOutput() /// 读取已同步的传输状态;等待用户激活时保持可继续的暂停状态。 public PlaybackState PlaybackState { - get { lock (syncRoot) return playbackState; } + get + { + lock (syncRoot) + { + if (requestedState == 0 || (inputEnded && buffer.QueuedFrames == 0)) return PlaybackState.Stopped; + return requestedState == 1 && buffer.IsRunning && buffer.IsPlaying + ? PlaybackState.Playing : PlaybackState.Paused; + } + } } /// 路由由浏览器选择器管理,不持久化枚举序号。 public int DeviceNumber => 0; - /// 包括托管队列、音频线程队列及浏览器可报告的设备延迟。 + /// 直接读取共享队列水位,并加上浏览器报告的设备延迟。 public double? OutputLatencyMilliseconds { get { lock (syncRoot) { - return transportLatency + queuedSamples * 1000.0 / Channels / BrowserAudioInterop.SampleRate; + return transportLatency + buffer.QueuedFrames * 1000.0 / BrowserAudioInterop.SampleRate; } } } @@ -119,7 +120,7 @@ public void Play() ObjectDisposedException.ThrowIf(disposed, this); if (sampleProvider == null) return; requestedState = 1; - playbackState = PlaybackState.Paused; + buffer.IsPlaying = true; ScheduleSynchronizationLocked(); Monitor.PulseAll(syncRoot); } @@ -132,7 +133,7 @@ public void Pause() { if (requestedState == 0 || disposed) return; requestedState = 2; - playbackState = PlaybackState.Paused; + buffer.IsPlaying = false; ScheduleSynchronizationLocked(); } } @@ -153,7 +154,7 @@ public long GetPosition() { lock (syncRoot) { - return (long)(consumedFrames * 44100 / BrowserAudioInterop.SampleRate) * sizeof(float); + return (long)(buffer.ConsumedFrames * 44100.0 / BrowserAudioInterop.SampleRate) * sizeof(float); } } @@ -171,16 +172,15 @@ public void Dispose() } } - /// 清空本代输入与队列,调用者须持有状态锁。 + /// 停止旧队列并切换独立内存,避免重置正在消费的读写指针。 private void ResetLocked() { + buffer.IsPlaying = false; + buffer = new BrowserAudioBuffer(); generation = Interlocked.Increment(ref nextGeneration); requestedState = 0; - playbackState = PlaybackState.Stopped; inputEnded = false; - consumedFrames = transportLatency = 0; - queuedSamples = 0; - while (blocks.TryDequeue(out AudioBlock block)) ArrayPool.Shared.Return(block.Samples); + transportLatency = 0; } /// 合并控制请求,主线程始终应用最新的播放意图。 @@ -194,38 +194,46 @@ private void ScheduleSynchronizationLocked() /// 不持有状态锁调用 JS,防止浏览器回调与后台生产相互等待。 private void SynchronizeTransport() { - int version, state; + int version, state, address; lock (syncRoot) { synchronizationPosted = false; version = generation; state = requestedState; + address = disposed ? 0 : buffer.Retain(version); } try { - BrowserAudioInterop.SetPlayback(version, state); - Pump(version); + BrowserAudioInterop.SetPlayback(version, state, address); } catch (Exception exception) { Fail(version, exception, synchronize: false); } if (disposed) Interlocked.CompareExchange(ref active, null, this); } - /// 在后台读取采样源;任何时刻最多保留两块尚未传输的音频。 + /// 后台直接发布样本;满队列时短暂休眠,唤醒不依赖浏览器主线程。 private void ProduceSamples() { + float[] samples = new float[BlockSamples]; while (true) { int version; ISampleProvider provider; + BrowserAudioBuffer target; lock (syncRoot) { - while (!disposed && (requestedState != 1 || inputEnded || blocks.Count >= QueueBlockCount)) + while (!disposed && (requestedState != 1 || inputEnded)) Monitor.Wait(syncRoot); if (disposed) return; + if (buffer.QueuedFrames > BrowserAudioBuffer.TargetFrames - BlockSamples / Channels) + { + // Worklet 不进入托管运行时;有界休眠独立检查它发布的读指针。 + Monitor.Wait(syncRoot, 5); + continue; + } version = generation; provider = sampleProvider!; + target = buffer; } - float[] samples = ArrayPool.Shared.Rent(BlockSamples); try { int count = provider.Read(samples, 0, BlockSamples); @@ -235,72 +243,22 @@ private void ProduceSamples() { if (count > 0) { - blocks.Enqueue(new AudioBlock(samples, count)); - queuedSamples += count; - samples = null!; + target.WriteSamples(samples.AsSpan(0, count)); } - else inputEnded = true; - if (!pumpPosted) + else { - pumpPosted = true; - Dispatcher.UIThread.Post(PumpCurrentGeneration); + inputEnded = true; + target.EndInput(); } } } } catch (Exception exception) { Fail(version, exception); } - finally { if (samples != null) ArrayPool.Shared.Return(samples); } } } - /// 处理生产线程合并投递的数据通知。 - private void PumpCurrentGeneration() - { - int version; - lock (syncRoot) { pumpPosted = false; version = generation; } - Pump(version); - } - - /// 每次仅批量搬运有空位的样本,不在音频回调中等待后台线程。 - internal void Pump(int version) - { - try - { - for (int batch = 0; batch < 4; batch++) - { - int writable = BrowserAudioInterop.WritableFrames(version); - AudioBlock block; - bool ended; - lock (syncRoot) - { - if (disposed || version != generation || requestedState != 1) return; - ended = inputEnded && blocks.Count == 0; - if (!blocks.TryPeek(out block)) - { - if (!ended) return; - } - else - { - if (writable < block.Count / Channels) return; - blocks.Dequeue(); - queuedSamples -= block.Count; - Monitor.PulseAll(syncRoot); - } - } - if (ended) { BrowserAudioInterop.EndInput(version); return; } - try - { - Buffer.BlockCopy(block.Samples, 0, transferBuffer, 0, block.Count * sizeof(float)); - BrowserAudioInterop.WriteSamples(version, transferBuffer, block.Count); - } - finally { ArrayPool.Shared.Return(block.Samples); } - } - } - catch (Exception exception) { Fail(version, exception); } - } - - /// 只接受本代消费时钟,输入结束须等浏览器排空后才进入停止状态。 - internal void UpdateStatus(int version, double frames, int state, double latency) + /// 只接受本代设备状态;采样水位和消费时钟直接读取共享内存。 + internal void UpdateStatus(int version, int state, double latency) { lock (syncRoot) { @@ -311,14 +269,10 @@ internal void UpdateStatus(int version, double frames, int state, double latency sampleProvider = null; return; } - consumedFrames = Math.Max(consumedFrames, frames); transportLatency = latency; - playbackState = requestedState == 0 ? PlaybackState.Stopped - : state == 1 && requestedState == 1 ? PlaybackState.Playing : PlaybackState.Paused; - if (state == 0 && inputEnded && blocks.Count == 0) + if (state == 0 && inputEnded && buffer.QueuedFrames == 0) { requestedState = 0; - playbackState = PlaybackState.Stopped; } } } @@ -336,7 +290,4 @@ private void Fail(int version, Exception exception, bool synchronize = true) Log.Error(exception, "浏览器音频输出失败"); Dispatcher.UIThread.Post(() => BrowserAudioInterop.ReportError(version, exception.Message)); } - - /// 保存池化采样块及其有效交错样本数量。 - private readonly record struct AudioBlock(float[] Samples, int Count); } diff --git a/OpenUtauMobile.Browser/wwwroot/audio-output-buffer.js b/OpenUtauMobile.Browser/wwwroot/audio-output-buffer.js index a3fbd62d..799ca6e6 100644 --- a/OpenUtauMobile.Browser/wwwroot/audio-output-buffer.js +++ b/OpenUtauMobile.Browser/wwwroot/audio-output-buffer.js @@ -1,5 +1,5 @@ -// 两个线程共同使用的队列协议;索引与计数均以立体声帧为单位。 -export const Read = 0, Write = 1, Playing = 2, Ended = 3, Consumed = 4, Requested = 5; +// 与 BrowserAudioBuffer.cs 共用布局;队列位于固定的 WASM 内存,计数单位为立体声帧。 +export const Read = 0, Write = 1, Playing = 2, Ended = 3, Consumed = 4, Running = 5; export const headerLength = 8; export const capacity = 4096; export const targetFrames = 2048; diff --git a/OpenUtauMobile.Browser/wwwroot/audio-output-worklet.js b/OpenUtauMobile.Browser/wwwroot/audio-output-worklet.js index 2f9d5644..a90d4e35 100644 --- a/OpenUtauMobile.Browser/wwwroot/audio-output-worklet.js +++ b/OpenUtauMobile.Browser/wwwroot/audio-output-worklet.js @@ -1,5 +1,5 @@ -// 主线程和音频线程共用的帧队列;每一代播放使用独立内存,避免重置时覆盖旧读指针。 -import { Read, Write, Playing, Ended, Consumed, Requested, headerLength, capacity, targetFrames } from './audio-output-buffer.js'; +// 后台生产者与音频线程直接共用 WASM 帧队列;主线程不参与持续供音。 +import { Read, Write, Playing, Ended, Consumed, headerLength, capacity } from './audio-output-buffer.js'; class OpenUtauAudioProcessor extends AudioWorkletProcessor { constructor() { @@ -9,10 +9,14 @@ class OpenUtauAudioProcessor extends AudioWorkletProcessor { this.framesSinceReport = 0; this.port.onmessage = ({ data }) => { if (data.type === "configure") { + const previousGeneration = this.generation; + const hadBuffer = this.header !== null; this.generation = data.generation; - this.header = new Int32Array(data.buffer, 0, headerLength); - this.samples = new Float32Array(data.buffer, headerLength * 4); + this.header = data.buffer ? new Int32Array(data.buffer, data.address, headerLength) : null; + this.samples = data.buffer ? new Float32Array(data.buffer, data.address + headerLength * 4, capacity * 2) : null; this.framesSinceReport = 0; + // 消息和 process 在同一音频线程串行执行,确认之后不再访问旧地址。 + if (hadBuffer) this.port.postMessage({ type: "released", generation: previousGeneration }); } }; } @@ -34,11 +38,10 @@ class OpenUtauAudioProcessor extends AudioWorkletProcessor { Atomics.store(header, Read, (read + count) | 0); Atomics.add(header, Consumed, count); const remaining = available - count; - if (remaining <= targetFrames / 2 && !Atomics.exchange(header, Requested, 1)) { - this.port.postMessage({ type: "need", generation: this.generation }); - } this.framesSinceReport += output[0].length; - if (remaining === 0 && Atomics.load(header, Ended)) { + // 结束标记可能在本次写指针快照之后发布,须再次确认末块已经消费完。 + if (remaining === 0 && Atomics.load(header, Ended) + && (Atomics.load(header, Write) >>> 0) === ((read + count) >>> 0)) { Atomics.store(header, Playing, 0); this.port.postMessage({ type: "ended", generation: this.generation }); } else if (this.framesSinceReport >= sampleRate / 50) { diff --git a/OpenUtauMobile.Browser/wwwroot/audio-output.js b/OpenUtauMobile.Browser/wwwroot/audio-output.js index e20b5ed7..2f497ccb 100644 --- a/OpenUtauMobile.Browser/wwwroot/audio-output.js +++ b/OpenUtauMobile.Browser/wwwroot/audio-output.js @@ -1,9 +1,9 @@ // 此模块只在浏览器主线程访问 AudioContext,音频线程只消费共享帧队列。 -import { Read, Write, Playing, Ended, Consumed, Requested, headerLength, capacity, targetFrames } from './audio-output-buffer.js'; +import { Read, Write, Playing, Consumed, Running, headerLength } from './audio-output-buffer.js'; const deviceStorageKey = "OpenUtauMobile.AudioOutput.Device"; -let context, node, header, samples; -let generation = -1, intent = 0, consumedBase = 0, lastConsumed = 0; -let onNeedData, onStatus, onError, onDeviceChanged; +let context, node, header, getHeap; +let generation = -1, intent = 0; +let onReleased, onStatus, onError, onDeviceChanged; let selectedId = "", selectedName = "", selectionVersion = 0; let resumePending = null; let failed = false; @@ -11,11 +11,13 @@ let failed = false; export async function initialize(runtime) { const exports = await runtime.getAssemblyExports("OpenUtauMobile.Browser"); const bridge = exports.OpenUtauMobile.Browser.Services.Audio.BrowserAudioInterop; - return initializeTransport(bridge.RequestData, bridge.UpdateStatus, bridge.ReceiveError, bridge.UpdateDevice); + return initializeTransport(bridge.ReleaseBuffer, bridge.UpdateStatus, bridge.ReceiveError, bridge.UpdateDevice, + () => runtime.localHeapViewU8()); } -export async function initializeTransport(needData, status, error, deviceChanged) { - onNeedData = needData; +export async function initializeTransport(released, status, error, deviceChanged, heap) { + onReleased = released; + getHeap = heap; onStatus = status; onError = error; onDeviceChanged = deviceChanged; @@ -35,8 +37,8 @@ export async function initializeTransport(needData, status, error, deviceChanged }); node.connect(context.destination); node.port.onmessage = ({ data }) => { + if (data.type === "released") { notify(onReleased, data.generation); return; } if (data.generation !== generation) return; - if (data.type === "need") notify(onNeedData, generation); if (data.type === "ended") intent = 0; report(); }; @@ -79,56 +81,40 @@ function resume(force = false) { } } -export function setPlayback(nextGeneration, nextIntent) { - if (failed) throw new Error("Reload the page to restart the browser audio processor."); +export function setPlayback(nextGeneration, nextIntent, address) { + if (failed) { + if (address && nextGeneration !== generation) notify(onReleased, nextGeneration); + throw new Error("Reload the page to restart the browser audio processor."); + } if (nextGeneration !== generation) { - if (header) Atomics.store(header, Playing, 0); + // 仅在控制操作时获取当前堆视图;已有固定范围在共享内存增长后仍指向原数据。 + let nextHeader; + try { + const buffer = address ? getHeap().buffer : null; + if (buffer && !(buffer instanceof SharedArrayBuffer)) throw new Error("Browser audio requires shared WASM memory."); + nextHeader = buffer ? new Int32Array(buffer, address >>> 0, headerLength) : null; + node.port.postMessage({ type: "configure", generation: nextGeneration, buffer, address: address >>> 0 }); + } catch (error) { + // 配置尚未送到音频线程,可以立即归还本次提交的固定缓冲。 + if (address) notify(onReleased, nextGeneration); + throw error; + } generation = nextGeneration; - consumedBase = lastConsumed = 0; - const buffer = new SharedArrayBuffer(headerLength * 4 + capacity * 2 * 4); - header = new Int32Array(buffer, 0, headerLength); - samples = new Float32Array(buffer, headerLength * 4); - node.port.postMessage({ type: "configure", generation, buffer }); + header = nextHeader; } intent = nextIntent; - Atomics.store(header, Playing, intent === 1 ? 1 : 0); if (intent === 1) resume(); report(); } -export function writableFrames(expectedGeneration) { - if (!header || expectedGeneration !== generation || intent !== 1) return 0; - const queued = ((Atomics.load(header, Write) >>> 0) - (Atomics.load(header, Read) >>> 0)) >>> 0; - return Math.max(0, targetFrames - queued); -} - -export function writeSamples(expectedGeneration, bytes, count) { - if (expectedGeneration !== generation || intent !== 1) return; - const data = new Float32Array(bytes.buffer, bytes.byteOffset, count); - const write = Atomics.load(header, Write) >>> 0; - for (let frame = 0; frame < count / 2; frame++) { - const offset = ((write + frame) % capacity) * 2; - samples[offset] = data[frame * 2]; - samples[offset + 1] = data[frame * 2 + 1]; - } - Atomics.store(header, Write, (write + count / 2) | 0); - Atomics.store(header, Requested, 0); - report(); -} - -export function endInput(expectedGeneration) { - if (expectedGeneration === generation) Atomics.store(header, Ended, 1); -} - function report() { if (!header || !onStatus) return; + Atomics.store(header, Running, context.state === "running" && !failed ? 1 : 0); const consumed = Atomics.load(header, Consumed) >>> 0; - if (consumed < lastConsumed) consumedBase += 0x100000000; - lastConsumed = consumed; const queued = ((Atomics.load(header, Write) >>> 0) - (Atomics.load(header, Read) >>> 0)) >>> 0; const state = failed ? 3 : intent === 0 ? 0 : intent === 1 && context.state === "running" && (queued > 0 || consumed > 0) ? 1 : 2; - notify(onStatus, generation, consumedBase + consumed, state, latencyMilliseconds()); + notify(onStatus, generation, state, ((context.baseLatency || 0) + (context.outputLatency || 0)) * 1000); } // .NET 多线程模式要求异步导出;通知不阻塞浏览器主线程,也不跨语言同步重入。 @@ -153,13 +139,11 @@ function fail(error) { function visibilityChanged() { if (document.hidden) context?.suspend().catch(fail); else if (intent === 1) { - if (header) Atomics.store(header, Playing, 1); resume(); } } function pageHidden() { - if (header) Atomics.store(header, Playing, 0); context?.suspend().catch(fail); } @@ -228,7 +212,10 @@ export async function dispose() { window.removeEventListener("pagehide", pageHidden); window.removeEventListener("pageshow", visibilityChanged); navigator.mediaDevices?.removeEventListener("devicechange", devicesChanged); - if (node) { node.port.onmessage = null; node.disconnect(); node.port.close(); } + if (node) node.disconnect(); if (context) { context.onstatechange = null; await context.close(); } - context = node = header = samples = null; + // 关闭上下文后音频线程已停止,随后才可解除最后一块共享缓冲的固定。 + if (header) notify(onReleased, generation); + if (node) { node.port.onmessage = null; node.port.close(); } + context = node = header = null; } From 118aeefb2bbcaa8ff8f37ed48b7bb2500db5a8f3 Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Sat, 14 Nov 2026 13:54:59 +0800 Subject: [PATCH 25/45] =?UTF-8?q?feature:=20=E5=90=91=E6=8F=92=E4=BB=B6?= =?UTF-8?q?=E6=8F=90=E4=BE=9B=E4=B8=8A=E4=B8=8B=E6=96=87=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E7=94=A8=E4=BA=8E=E4=B8=BB=E5=8A=A8=E5=88=92=E5=88=86phrase?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- OpenUtau.Core/Pipeline/PhraseSource.cs | 24 +++++++++++++++++++++++- OpenUtau.Core/Render/IRenderer.cs | 21 +++++++++++++++++++++ OpenUtau.Core/Render/RenderPhrase.cs | 21 +++++++++++++++++---- OpenUtauMobile/ViewConstants.cs | 4 ++-- 4 files changed, 63 insertions(+), 7 deletions(-) diff --git a/OpenUtau.Core/Pipeline/PhraseSource.cs b/OpenUtau.Core/Pipeline/PhraseSource.cs index 51d8a2bd..3454cf0a 100644 --- a/OpenUtau.Core/Pipeline/PhraseSource.cs +++ b/OpenUtau.Core/Pipeline/PhraseSource.cs @@ -403,6 +403,8 @@ public sealed class PhraseSource { public readonly PhonemeSource[] Phonemes; /// Half-open [start, end) index ranges into . public readonly (int Start, int End)[] PhraseGroups; + // 可选分组扩展:独占范围供表情图使用,共享上下文仅用于构造渲染输入。 + private readonly RenderPhraseGroup[]? rendererPhraseGroups; // Shared by graph contexts for this immutable snapshot; unused graphs pay no indexing cost. internal readonly Lazy PhraseNoteIndex; @@ -481,6 +483,25 @@ internal PhraseSource( Phonemes.Select(p => p.Position).ToArray(), numerical.ToDictionary(abbr => abbr, abbr => Phonemes.Select(p => p.Values![abbr]).ToArray())); } + + // 保留默认分句路径;只有显式提供分组的渲染器才接管连续音素的切分。 + // 延迟索引尚未求值,此时替换归属范围不会让表情图看到重叠的音符归属。 + rendererPhraseGroups = Renderer.GetPhraseGroups(this); + if (rendererPhraseGroups != null) + { + int previousEnd = 0; + foreach (RenderPhraseGroup group in rendererPhraseGroups) + { + if (group.Start < previousEnd || group.End <= group.Start + || group.ContextStart < 0 || group.ContextStart > group.Start + || group.ContextEnd < group.End || group.ContextEnd > Phonemes.Length) + { + throw new ArgumentException("渲染器返回了无效的乐句归属或上下文范围。"); + } + previousEnd = group.End; + } + PhraseGroups = [.. rendererPhraseGroups.Select(group => (group.Start, group.End))]; + } } /// @@ -546,7 +567,8 @@ public RenderPhrase[] BuildPhrases() { var phonemes = DrivenPhonemes(); var phrases = new RenderPhrase[PhraseGroups.Length]; for (int i = 0; i < PhraseGroups.Length; ++i) { - phrases[i] = new RenderPhrase(this, phonemes, PhraseGroups[i].Start, PhraseGroups[i].End); + phrases[i] = new RenderPhrase(this, phonemes, PhraseGroups[i].Start, PhraseGroups[i].End, + rendererPhraseGroups?[i]); } return phrases; } diff --git a/OpenUtau.Core/Render/IRenderer.cs b/OpenUtau.Core/Render/IRenderer.cs index 5bd36791..639efdad 100644 --- a/OpenUtau.Core/Render/IRenderer.cs +++ b/OpenUtau.Core/Render/IRenderer.cs @@ -91,6 +91,21 @@ public void ReportRealCurves(IReadOnlyList realCurves) { } } + /// 渲染器提供的只读乐句上下文;缓存键必须覆盖会影响音频的额外输入。 + public interface IRenderPhraseContext + { + /// 由渲染器提供的稳定缓存身份,不得包含账户凭据或可变对象标识。 + string CacheKey { get; } + } + + /// + /// 自定义乐句的音素索引范围,均为左闭右开。 + /// Start/End 表示表情图的独占归属,必须有序且不重叠;ContextStart/ContextEnd + /// 表示实际渲染所需的上下文,须包含归属范围,允许相邻乐句共享上下文。 + /// + public sealed record RenderPhraseGroup(int Start, int End, int ContextStart, int ContextEnd, + IRenderPhraseContext? Context = null); + /// /// Interface of phrase-based renderer. /// @@ -102,6 +117,12 @@ public interface IRenderer { bool SupportsExpression(UExpressionDescriptor descriptor); RenderResult Layout(RenderPhrase phrase); + /// + /// 在不可变快照建立后提供自定义分组,可切开连续音素;返回 null 沿用原有分句及合句上限。 + /// 这是可选扩展,默认实现不改变现有渲染器;实现方仅可读取快照,不得修改工程或发起网络请求。 + /// + RenderPhraseGroup[]? GetPhraseGroups(Pipeline.PhraseSource source) => null; + /// /// How much (ms) this renderer pads the rendered audio before the first /// phoneme (head) and after the last phoneme (tail) of a phrase. diff --git a/OpenUtau.Core/Render/RenderPhrase.cs b/OpenUtau.Core/Render/RenderPhrase.cs index 4ce0164a..d8f34eeb 100644 --- a/OpenUtau.Core/Render/RenderPhrase.cs +++ b/OpenUtau.Core/Render/RenderPhrase.cs @@ -217,19 +217,27 @@ public class RenderPhrase { /// public readonly PhraseLayout Layout; + /// 可选分组扩展的只读上下文;宿主不解释具体渲染器的数据。 + public IRenderPhraseContext? RendererContext { get; } + private List cacheFiles = new List(); /// /// The heavy phrase build over an immutable snapshot; pure over the /// snapshot, safe off the UI thread. /// - internal RenderPhrase(Pipeline.PhraseSource source, Pipeline.PhonemeSource[] phonemes, int phraseStart, int phraseEnd) { + internal RenderPhrase(Pipeline.PhraseSource source, Pipeline.PhonemeSource[] phonemes, int phraseStart, int phraseEnd, + RenderPhraseGroup? group = null) { + // 表情图仍以 phraseStart 定位独占归属,音素及音高输入可以包含相邻乐句共享的上下文。 + RendererContext = group?.Context; + int contextStart = group?.ContextStart ?? phraseStart; + int contextEnd = group?.ContextEnd ?? phraseEnd; var phrasePhonemes = phonemes - .Skip(phraseStart) - .Take(phraseEnd - phraseStart) + .Skip(contextStart) + .Take(contextEnd - contextStart) .ToList(); var notesOf = source.Notes; - var uNotes = source.PhraseNotes(phraseStart, phraseEnd); + var uNotes = source.PhraseNotes(contextStart, contextEnd); if (notesOf[uNotes.First()].Prev != -1 && notesOf[notesOf[uNotes.First()].Prev].End == notesOf[uNotes.First()].Position) { uNotes.Insert(0, notesOf[uNotes.First()].Prev); @@ -581,6 +589,11 @@ private ulong Hash(bool postEffect) { writer.Write(renderer?.ToString() ?? ""); writer.Write(wavtool ?? ""); writer.Write(timeAxis.Timestamp); + // 自定义分组的淡化、补白等额外输入也必须参与缓存;默认路径保持原哈希格式。 + if (RendererContext != null) + { + writer.Write(RendererContext.CacheKey); + } // R1.1 用乐句哈希作为噪声种子,输入须与桌面一致。 if (renderer?.ToString() != Renderers.WORLDLINE_R11) { diff --git a/OpenUtauMobile/ViewConstants.cs b/OpenUtauMobile/ViewConstants.cs index ba639cbb..daccef93 100644 --- a/OpenUtauMobile/ViewConstants.cs +++ b/OpenUtauMobile/ViewConstants.cs @@ -36,7 +36,7 @@ static class ViewConstants // 走带编曲区横向缩放(EditorViewModel.TickWidth,单位:像素/Tick) public const double TickWidthMax = 2; public const double TickWidthMin = 1.0 / 480.0; - public const double TickWidthDefault = 24.0 / 480.0; + public const double TickWidthDefault = 12.0 / 480.0; /// @@ -83,7 +83,7 @@ static class ViewConstants // 钢琴卷帘区横向缩放(PianoRollViewModel.TickWidth,单位:像素/Tick) public const double PianoRollTickWidthMax = 8; public const double PianoRollTickWidthMin = 8.0 / 480.0; - public const double PianoRollTickWidthDefault = 48.0 / 480.0; + public const double PianoRollTickWidthDefault = 96.0 / 480.0; public const double NoteHeightMax = 128; From 1ddc8ee158a5290f3031371af8c2e630c2c9ca95 Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:56:37 +0800 Subject: [PATCH 26/45] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E8=A7=86?= =?UTF-8?q?=E5=8F=A3=E9=99=90=E5=88=B6=E6=B2=A1=E6=9C=89=E5=8F=8A=E6=97=B6?= =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- OpenUtauMobile/ViewConstants.cs | 2 +- OpenUtauMobile/ViewModels/EditorViewModel.cs | 38 +++++++++---------- .../ViewModels/PianoRollViewModel.cs | 14 ++++++- 3 files changed, 33 insertions(+), 21 deletions(-) diff --git a/OpenUtauMobile/ViewConstants.cs b/OpenUtauMobile/ViewConstants.cs index daccef93..17a4f71d 100644 --- a/OpenUtauMobile/ViewConstants.cs +++ b/OpenUtauMobile/ViewConstants.cs @@ -83,7 +83,7 @@ static class ViewConstants // 钢琴卷帘区横向缩放(PianoRollViewModel.TickWidth,单位:像素/Tick) public const double PianoRollTickWidthMax = 8; public const double PianoRollTickWidthMin = 8.0 / 480.0; - public const double PianoRollTickWidthDefault = 96.0 / 480.0; + public const double PianoRollTickWidthDefault = 72.0 / 480.0; public const double NoteHeightMax = 128; diff --git a/OpenUtauMobile/ViewModels/EditorViewModel.cs b/OpenUtauMobile/ViewModels/EditorViewModel.cs index 27969402..0b3bd1ab 100644 --- a/OpenUtauMobile/ViewModels/EditorViewModel.cs +++ b/OpenUtauMobile/ViewModels/EditorViewModel.cs @@ -674,15 +674,9 @@ await VoiceColorMappingService.ValidateAsync(mappingProject, mappingTrack, { ProjectPath = loadProjectNotification.project.FilePath; RefreshProjectInfo(); - InvalidateMaxOffsets(); - PianoRollViewModel.InvalidateMaxOffsets(); - ApplyViewportLimits(); RequestInvalidateVisual?.Invoke(); }); break; - case TrackCommand: - InvalidateMaxOffsets(); - break; case PartCommand: RunOnUiThread(() => { @@ -696,10 +690,6 @@ await VoiceColorMappingService.ValidateAsync(mappingProject, mappingTrack, { ReplaceSelectedParts(remainingSelection); } - InvalidateMaxOffsets(); - ApplyViewportLimits(); - // 更新钢琴卷帘视口限制 - PianoRollViewModel.InvalidateMaxOffsets(); RequestInvalidateVisual?.Invoke(); }); break; @@ -718,6 +708,15 @@ await VoiceColorMappingService.ValidateAsync(mappingProject, mappingTrack, this.RaisePropertyChanged(nameof(Saved)); break; } + + // 文档命令执行后读取实际边界,涵盖音符命令隐式延长分片及撤销、重做。 + // 校验可能延后到下一帧或命令组结束,相关通知到达时再同步最终结果。 + if (cmd is not UNotification || + cmd is LoadProjectNotification or ValidateProjectNotification or PreRenderNotification or + SingersRefreshedNotification or OtoChangedNotification) + { + RefreshDocumentViewportLimits(); + } } private static void RunOnUiThread(Action action) @@ -1000,6 +999,16 @@ public void OnTrackAreaSizeChanged(double width, double height) /// private void InvalidateMaxOffsets() => _maxOffsetsDirty = true; + /// 从权威文档同步内容边界,再统一刷新编曲区与钢琴卷帘的视口限制。 + private void RefreshDocumentViewportLimits() + { + InvalidateMaxOffsets(); + ApplyViewportLimits(); + PianoRollViewModel.InvalidateMaxOffsets(); + PianoRollViewModel.ApplyViewportLimits(); + RequestInvalidateVisual?.Invoke(); + } + /// /// 若缓存有效直接返回(O(1)),否则遍历 Parts 重算并缓存(O(Parts.Count))。 /// @@ -1553,7 +1562,6 @@ part is UWavePart wavePart /// public void OnGestureDragEnd(Point point, ulong timestamp) { - bool completedResize = _inputState == TrackInputState.ResizingParts; if (_inputState == TrackInputState.MovingParts || _inputState == TrackInputState.ResizingParts) { DocManager.Inst.EndUndoGroup(); @@ -1569,14 +1577,6 @@ public void OnGestureDragEnd(Point point, ulong timestamp) _resizingReferencePartIndex = 0; _resizingEdge = PartResizeEdge.End; _resizingPointerTickOffset = 0; - - if (completedResize) - { - InvalidateMaxOffsets(); - ApplyViewportLimits(); - PianoRollViewModel.InvalidateMaxOffsets(); - RequestInvalidateVisual?.Invoke(); - } } /// diff --git a/OpenUtauMobile/ViewModels/PianoRollViewModel.cs b/OpenUtauMobile/ViewModels/PianoRollViewModel.cs index 00649b5f..bc55af96 100644 --- a/OpenUtauMobile/ViewModels/PianoRollViewModel.cs +++ b/OpenUtauMobile/ViewModels/PianoRollViewModel.cs @@ -383,7 +383,19 @@ private void RefreshExpressionSupport() private bool _maxOffsetsDirty = true; private double _cachedMaxTickOffset; private double _cachedMaxKeyOffset; - public double ContentEndTick; + private double _contentEndTick; + + /// 由编曲区从文档同步的内容末尾;边界变化时立即使视口缓存失效。 + internal double ContentEndTick + { + get => _contentEndTick; + set + { + if (_contentEndTick == value) return; + _contentEndTick = value; + InvalidateMaxOffsets(); + } + } #endregion From 8cbeb0d8df793a8e4be8d3496576ddbd3a92628b Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:51:50 +0800 Subject: [PATCH 27/45] =?UTF-8?q?ui:=20=E5=A2=9E=E5=8A=A0=E9=9F=B3?= =?UTF-8?q?=E7=AC=A6=E5=91=BC=E5=90=B8=E6=84=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- OpenUtauMobile/Controls/NotesCanvas.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/OpenUtauMobile/Controls/NotesCanvas.cs b/OpenUtauMobile/Controls/NotesCanvas.cs index fd7734f3..6a7fccf1 100644 --- a/OpenUtauMobile/Controls/NotesCanvas.cs +++ b/OpenUtauMobile/Controls/NotesCanvas.cs @@ -87,7 +87,7 @@ public double KeyOffset private const int RenderPitchSampleInterval = 5; // 音高采样间隔(tick) private const double PitchHandleRadius = 5.0; private const double PitchHandleDiameter = PitchHandleRadius * 2; - private const double NoteBodyCornerRadius = 4; + private const double NoteBodyCornerRadius = 8; private readonly Geometry _pointGeometry = new EllipseGeometry( new Rect(-PitchHandleRadius, -PitchHandleRadius, PitchHandleDiameter, PitchHandleDiameter)); @@ -220,7 +220,7 @@ public override void Render(DrawingContext context) Size size = ViewModel.TickToneToSize(note.duration, 1); Point rightBottom = new(leftTop.X + size.Width, leftTop.Y + size.Height); // 圆角矩形 - Rect rect = new(leftTop, rightBottom); + Rect rect = new Rect(leftTop, rightBottom).Deflate(new Thickness(0, 4)); RoundedRect roundedRect = new(rect, new CornerRadius(NoteBodyCornerRadius)); // 边框:表示选中状态 IPen borderPen = isSelected @@ -379,7 +379,7 @@ private void RenderNoteBody(UNote note, DrawingContext context, SolidColorBrush Point rightBottom = new(leftTop.X + size.Width, leftTop.Y + size.Height); // 圆角矩形 - Rect rect = new(leftTop, rightBottom); + Rect rect = new Rect(leftTop, rightBottom).Deflate(new Thickness(0, 4)); RoundedRect roundedRect = new(rect, new CornerRadius(NoteBodyCornerRadius)); // 根据错误状态选择颜色 From 4344e7f05e6d3c0b268bee1c7dd7f665797b2cb9 Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Sun, 15 Nov 2026 02:13:04 +0800 Subject: [PATCH 28/45] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E5=85=B3?= =?UTF-8?q?=E9=97=AD=E6=B7=B7=E9=9F=B3=E9=9D=A2=E6=9D=BF=E5=90=8E=E9=92=A2?= =?UTF-8?q?=E7=90=B4=E5=8D=B7=E5=B8=98=E8=A7=86=E5=8F=A3=E4=B8=8D=E5=90=8C?= =?UTF-8?q?=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- OpenUtauMobile/Views/EditorView.axaml.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/OpenUtauMobile/Views/EditorView.axaml.cs b/OpenUtauMobile/Views/EditorView.axaml.cs index 6b125499..f2032715 100644 --- a/OpenUtauMobile/Views/EditorView.axaml.cs +++ b/OpenUtauMobile/Views/EditorView.axaml.cs @@ -81,8 +81,8 @@ public void CloseMixer() if (DataContext is EditorViewModel vm) { vm.PianoRollViewModel.SetPresentationSuspended(false); - if (vm.IsPlaying || vm.IsWaitingRender) - vm.PianoRollViewModel.SyncPlaybackState(vm.PlayPosTick, vm.IsPlaying, vm.IsWaitingRender); + // 暂停展示期间播放头仍可能移动,恢复时也需同步停止状态下的位置。 + vm.PianoRollViewModel.SyncPlaybackState(vm.PlayPosTick, vm.IsPlaying, vm.IsWaitingRender); } } From 370c8811ef83bb2e1251e687770128965ee5381f Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:37:16 +0800 Subject: [PATCH 29/45] =?UTF-8?q?feature:=20=E5=A2=9E=E5=8A=A0ghost?= =?UTF-8?q?=E9=9F=B3=E7=AC=A6=E6=98=BE=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- OpenUtau.Core/Util/Preferences.cs | 3 + OpenUtauMobile/Assets/Lang/Strings.en.resx | 6 ++ OpenUtauMobile/Assets/Lang/Strings.ja.resx | 6 ++ OpenUtauMobile/Assets/Lang/Strings.ru.resx | 6 ++ OpenUtauMobile/Assets/Lang/Strings.uk.resx | 6 ++ .../Assets/Lang/Strings.zh-Hans.resx | 6 ++ .../GhostNotesVisibilityChangedEvent.cs | 4 ++ OpenUtauMobile/Controls/NotesCanvas.cs | 55 ++++++++++++++++--- .../ViewModels/PianoRollViewModel.cs | 4 ++ .../ViewModels/SettingsViewModel.cs | 41 +++++++++++--- OpenUtauMobile/Views/SettingsView.axaml | 23 +++++++- 11 files changed, 144 insertions(+), 16 deletions(-) create mode 100644 OpenUtauMobile/Controls/GhostNotesVisibilityChangedEvent.cs diff --git a/OpenUtau.Core/Util/Preferences.cs b/OpenUtau.Core/Util/Preferences.cs index 901dbea5..1ed0bc72 100644 --- a/OpenUtau.Core/Util/Preferences.cs +++ b/OpenUtau.Core/Util/Preferences.cs @@ -402,6 +402,9 @@ public class SerializablePreferences { /// public bool ShowRenderWaveform = false; + /// 是否在钢琴卷帘背景显示其它轨道中与当前片段重叠的音符。 + public bool PianoRollShowGhostNotes = true; + /// /// Path to SoundFont (SF2) file for piano key playback. /// If empty or file not found, falls back to SineWave. diff --git a/OpenUtauMobile/Assets/Lang/Strings.en.resx b/OpenUtauMobile/Assets/Lang/Strings.en.resx index 12bef8cf..5e2ab204 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.en.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.en.resx @@ -2647,4 +2647,10 @@ Applying replaces the source of this input. Applying track settings… Preparing voice color mapping… Phonemizing: {0} of {1} parts pending · {2}s + + Show other tracks’ notes + + + Show notes from other tracks overlapping the current part in the piano roll background. + diff --git a/OpenUtauMobile/Assets/Lang/Strings.ja.resx b/OpenUtauMobile/Assets/Lang/Strings.ja.resx index b17baafc..82a23d11 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.ja.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.ja.resx @@ -2641,4 +2641,10 @@ Applying replaces the source of this input. トラック設定を適用中… 音色マッピングを準備中… 音素変換中:残り {0}/{1} パート · {2} 秒経過 + + 他のトラックのノートを表示 + + + 現在のパートと重なる他のトラックのノートをピアノロールの背景に表示します。 + diff --git a/OpenUtauMobile/Assets/Lang/Strings.ru.resx b/OpenUtauMobile/Assets/Lang/Strings.ru.resx index ddede28f..c439b7de 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.ru.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.ru.resx @@ -2600,4 +2600,10 @@ Applying replaces the source of this input. Применение настроек дорожки… Подготовка сопоставления тембров… Фонемизация: осталось {0} из {1} партий · {2} с + + Показывать ноты других дорожек + + + Показывать на фоне пианоролла ноты других дорожек, пересекающихся с текущим фрагментом. + diff --git a/OpenUtauMobile/Assets/Lang/Strings.uk.resx b/OpenUtauMobile/Assets/Lang/Strings.uk.resx index 7d97a289..47a66e0b 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.uk.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.uk.resx @@ -2600,4 +2600,10 @@ Applying replaces the source of this input. Застосування налаштувань доріжки… Підготовка зіставлення тембрів… Фонемізація: залишилося {0} з {1} партій · {2} с + + Показувати ноти інших доріжок + + + Показувати на тлі фортепіанного редактора ноти інших доріжок, що перетинаються з поточним фрагментом. + diff --git a/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx b/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx index 51764dd6..ab7a663b 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx @@ -2647,4 +2647,10 @@ 正在应用轨道设置… 正在准备音色映射… 正在音素化:剩余 {0}/{1} 个片段 · 已等待 {2} 秒 + + 显示其它轨道音符 + + + 在钢琴卷帘背景显示与当前片段重叠的其它轨道音符。 + diff --git a/OpenUtauMobile/Controls/GhostNotesVisibilityChangedEvent.cs b/OpenUtauMobile/Controls/GhostNotesVisibilityChangedEvent.cs new file mode 100644 index 00000000..de11c8ed --- /dev/null +++ b/OpenUtauMobile/Controls/GhostNotesVisibilityChangedEvent.cs @@ -0,0 +1,4 @@ +namespace OpenUtauMobile.Controls; + +/// 通知钢琴卷帘更新背景音符的显示状态。 +public sealed record GhostNotesVisibilityChangedEvent; diff --git a/OpenUtauMobile/Controls/NotesCanvas.cs b/OpenUtauMobile/Controls/NotesCanvas.cs index 6a7fccf1..70d69d8e 100644 --- a/OpenUtauMobile/Controls/NotesCanvas.cs +++ b/OpenUtauMobile/Controls/NotesCanvas.cs @@ -148,7 +148,8 @@ protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) _renderViewSubscription?.Dispose(); _renderViewSubscription = RenderView.Inst.Observe(projection => { - if (ReferenceEquals(projection.Part, Part)) InvalidateVisual(); + if (ReferenceEquals(projection.Part, Part) || Preferences.Default.PianoRollShowGhostNotes) + InvalidateVisual(); }); ViewModel = DataContext as PianoRollViewModel; if (ViewModel != null) @@ -184,6 +185,7 @@ public override void Render(DrawingContext context) int rightTick = (int)(leftTick + Bounds.Width / TickWidth); SolidColorBrush brush = TrackPalette.GetTrackColor(DocManager.Inst.Project.tracks[Part.trackNo].TrackColor) .AccentColor; + RenderGhostNotes(context, leftTick, rightTick); RenderPitchPenHitArea(context); // ———— 绘制主体 ———— foreach (UNote note in Part.notes) @@ -216,17 +218,17 @@ public override void Render(DrawingContext context) bool isSelected = ViewModel.IsNoteSelected(note); // 定位 - Point leftTop = ViewModel.TickPitchToPoint(note.position + Part.position, note.AdjustedTone); + Point leftTop = ViewModel.TickPitchToPoint(note.position + Part.position, note.AdjustedTone) + new Avalonia.Vector(1, 0); Size size = ViewModel.TickToneToSize(note.duration, 1); Point rightBottom = new(leftTop.X + size.Width, leftTop.Y + size.Height); // 圆角矩形 Rect rect = new Rect(leftTop, rightBottom).Deflate(new Thickness(0, 4)); RoundedRect roundedRect = new(rect, new CornerRadius(NoteBodyCornerRadius)); // 边框:表示选中状态 - IPen borderPen = isSelected - ? ThemeResources.GetPen("Sem.Color.Primary", 1.5) - : ThemeResources.GetPen("Sem.Color.OutlineVariant", 0.5); - context.DrawRectangle(null, borderPen, roundedRect); + if (isSelected) + { + context.DrawRectangle(null, ThemeResources.GetPen("Sem.Color.Primary", 1.5), roundedRect); + } if ((ViewModel.EditMode != PianoRollEditMode.MultiSelect && ViewModel.EditMode != PianoRollEditMode.Note) || @@ -364,6 +366,43 @@ private void RenderPitchPenHitArea(DrawingContext context) } } + /// 绘制其它轨道中与当前片段重叠的背景音符,不参与编辑命中。 + private void RenderGhostNotes(DrawingContext context, int leftTick, int rightTick) + { + if (!Preferences.Default.PianoRollShowGhostNotes || Part == null || ViewModel == null) return; + + UProject project = DocManager.Inst.Project; + // 背景音符沿用上游的半行高度与内缩,保持在音高行中央。 + double height = Math.Floor(KeyHeight * 0.2 - 2); + if (height <= 0) return; + using (context.PushClip(new Rect(Bounds.Size))) + using (context.PushOpacity(0.2)) + { + foreach (UPart otherPart in project.parts) + { + if (otherPart is not UVoicePart voicePart || otherPart.trackNo == Part.trackNo || + otherPart.position >= Part.End || otherPart.End <= Part.position || + otherPart.position > rightTick || otherPart.End < leftTick) + continue; + + IBrush brush = TrackPalette.GetTrackColor(project.tracks[otherPart.trackNo].TrackColor).AccentColor; + foreach (UNote note in voicePart.notes) + { + int position = voicePart.position + note.position; + if (position > rightTick) break; + if (voicePart.position + note.End < leftTick) continue; + + Point topLeft = ViewModel.TickPitchToPoint(position, note.AdjustedTone); + double width = ViewModel.TickToneToSize(note.duration, 1).Width - 1; + if (width <= 0) continue; + Rect rect = new(topLeft.X + 1, Math.Round(topLeft.Y + 1 + Math.Floor(KeyHeight * 0.4)), width, height); + if (rect.Bottom < 0 || rect.Top > Bounds.Height) continue; + context.DrawRectangle(brush, null, rect, 2, 2); + } + } + } + } + /// /// 绘制音符主体(矩形 + 歌词) /// @@ -374,7 +413,7 @@ private void RenderNoteBody(UNote note, DrawingContext context, SolidColorBrush { if (ViewModel == null || Part == null) return; - Point leftTop = ViewModel.TickPitchToPoint(note.position + Part.position, note.AdjustedTone); + Point leftTop = ViewModel.TickPitchToPoint(note.position + Part.position, note.AdjustedTone) + new Avalonia.Vector(1, 0); Size size = ViewModel.TickToneToSize(note.duration, 1); Point rightBottom = new(leftTop.X + size.Width, leftTop.Y + size.Height); @@ -1122,6 +1161,8 @@ public void OnNext(UCommand cmd, bool isUndo) { case NoteCommand: case PartCommand: + case TrackCommand: + case LoadProjectNotification: case SetCurveCommand: case MaskedCurveCommand: case PhonemizedNotification: diff --git a/OpenUtauMobile/ViewModels/PianoRollViewModel.cs b/OpenUtauMobile/ViewModels/PianoRollViewModel.cs index bc55af96..914e4cab 100644 --- a/OpenUtauMobile/ViewModels/PianoRollViewModel.cs +++ b/OpenUtauMobile/ViewModels/PianoRollViewModel.cs @@ -877,6 +877,10 @@ public PianoRollViewModel() .Subscribe(_ => RequestInvalidateVisual?.Invoke()) .DisposeWith(_disposables); + MessageBus.Current.Listen() + .Subscribe(_ => RequestInvalidateVisual?.Invoke()) + .DisposeWith(_disposables); + PlayPosTick = DocManager.Inst.playPosTick; Gesture.Tap = OnGestureTap; diff --git a/OpenUtauMobile/ViewModels/SettingsViewModel.cs b/OpenUtauMobile/ViewModels/SettingsViewModel.cs index 8262f1fb..f793b81c 100644 --- a/OpenUtauMobile/ViewModels/SettingsViewModel.cs +++ b/OpenUtauMobile/ViewModels/SettingsViewModel.cs @@ -510,9 +510,19 @@ public partial class SettingsViewModel : NavigateViewModelBase, IDisposable [Reactive] public StopButtonBehaviorOption? SelectedStopButtonBehavior { get; set; } - /// 回放刷新率(1-60)。 + /// 回放刷新率档位,低帧率逐帧调整,高帧率使用常见刷新率。 + private static readonly int[] PlaybackRefreshRates = [.. Enumerable.Range(1, 30), 40, 50, 60, 90, 120]; + + /// 回放刷新率滑块的最大档位索引。 + public int PlaybackRefreshRateMaximumStep => PlaybackRefreshRates.Length - 1; + + /// 当前选中的回放刷新率档位索引。 + [Reactive] + public int PlaybackRefreshRateStep { get; set; } + + /// 当前档位对应的实际回放刷新率。 [Reactive] - public int PlaybackRefreshRate { get; set; } + public int PlaybackRefreshRate { get; private set; } /// 是否显示立绘。 [Reactive] @@ -530,6 +540,10 @@ public partial class SettingsViewModel : NavigateViewModelBase, IDisposable [Reactive] public bool ShowPitchPenHitArea { get; set; } + /// 是否显示其它轨道的背景音符。 + [Reactive] + public bool ShowGhostNotes { get; set; } + /// 扩展音符命中范围前后增加的 Tick 数。 [Reactive] public int PitchPenNoteHitTickExtension { get; set; } @@ -1112,11 +1126,13 @@ private void InitializeEditingSettings() .DisposeWith(_disposables); // 编辑与行为:回放刷新率 / 立绘开关 / 撤销上限 / 音高线拖拽 - PlaybackRefreshRate = Math.Clamp((int)Math.Round(Preferences.Default.PlaybackRefreshRate), 1, 60); + PlaybackRefreshRate = PlaybackRefreshRates.MinBy(rate => Math.Abs(rate - Preferences.Default.PlaybackRefreshRate)); + PlaybackRefreshRateStep = Array.IndexOf(PlaybackRefreshRates, PlaybackRefreshRate); ShowPortraitEnabled = Preferences.Default.ShowPortrait; UndoLimit = Math.Clamp(Preferences.Default.UndoLimit, 10, 100); PitchPenCanvasDragEnabled = Preferences.Default.PitchPenCanvasDragEnabled; ShowPitchPenHitArea = Preferences.Default.ShowPitchPenHitArea; + ShowGhostNotes = Preferences.Default.PianoRollShowGhostNotes; MagnifierMagnificationFactor = MagnifierSettings.Normalize(Preferences.Default.MagnifierMagnificationFactor); MagnifierSliderValue = MagnifierSettings.Snap(MagnifierMagnificationFactor); this.WhenAnyValue(x => x.MagnifierSliderValue) @@ -1144,18 +1160,19 @@ private void InitializeEditingSettings() Preferences.SerializablePreferences.PitchPenNoteHitToneExtensionMinimum, Preferences.SerializablePreferences.PitchPenNoteHitToneExtensionMaximum); - this.WhenAnyValue(x => x.PlaybackRefreshRate) + this.WhenAnyValue(x => x.PlaybackRefreshRateStep) .Skip(1) .Subscribe(value => { - int clamped = Math.Clamp(value, 1, 60); + int clamped = Math.Clamp(value, 0, PlaybackRefreshRateMaximumStep); if (clamped != value) { - PlaybackRefreshRate = clamped; + PlaybackRefreshRateStep = clamped; return; } - Preferences.Default.PlaybackRefreshRate = clamped; + PlaybackRefreshRate = PlaybackRefreshRates[clamped]; + Preferences.Default.PlaybackRefreshRate = PlaybackRefreshRate; Preferences.Save(); }) .DisposeWith(_disposables); @@ -1204,6 +1221,16 @@ private void InitializeEditingSettings() }) .DisposeWith(_disposables); + this.WhenAnyValue(x => x.ShowGhostNotes) + .Skip(1) + .Subscribe(enabled => + { + Preferences.Default.PianoRollShowGhostNotes = enabled; + Preferences.Save(); + MessageBus.Current.SendMessage(new GhostNotesVisibilityChangedEvent()); + }) + .DisposeWith(_disposables); + this.WhenAnyValue(x => x.PitchPenNoteHitTickExtension) .Skip(1) .Subscribe(value => diff --git a/OpenUtauMobile/Views/SettingsView.axaml b/OpenUtauMobile/Views/SettingsView.axaml index dd5f745a..ccc23b19 100644 --- a/OpenUtauMobile/Views/SettingsView.axaml +++ b/OpenUtauMobile/Views/SettingsView.axaml @@ -494,6 +494,24 @@ + + + + + + + + + + + @@ -711,11 +729,12 @@ FontSize="{x:Static semantic:TypographyTokens.BodyLSize}" Foreground="{DynamicResource Sem.Color.OnSurfaceVariant}" /> - Date: Sun, 15 Nov 2026 16:45:49 +0800 Subject: [PATCH 30/45] =?UTF-8?q?feature:=20=E5=BC=95=E5=85=A5=20Floating?= =?UTF-8?q?=20Toolbar=20=E5=B9=B6=E5=88=9D=E6=AC=A1=E5=BA=94=E7=94=A8?= =?UTF-8?q?=E5=9C=A8=E9=9F=B3=E7=AC=A6=E7=AC=94=E6=A8=A1=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Views/DesktopWorkspace.axaml | 6 +- .../Views/DesktopWorkspace.axaml.cs | 7 + OpenUtauMobile/Assets/Lang/Strings.en.resx | 3 + OpenUtauMobile/Assets/Lang/Strings.ja.resx | 3 + OpenUtauMobile/Assets/Lang/Strings.ru.resx | 3 + OpenUtauMobile/Assets/Lang/Strings.uk.resx | 3 + .../Assets/Lang/Strings.zh-Hans.resx | 3 + .../Editor/EditorInputController.Keyboard.cs | 2 + .../Editor/NoteSelectionToolbarBinding.cs | 83 +++++ .../Controls/ControlThemes.axaml | 1 + .../Controls/FloatingToolbar.axaml | 70 ++++ .../Controls/FloatingToolbar.cs | 322 ++++++++++++++++++ .../Controls/FloatingToolbarAction.cs | 23 ++ .../Themes/OpenUtauMobile/README.md | 33 ++ .../Components/FloatingToolbarTokens.cs | 25 ++ .../Tokens/Foundation/ShapeTokens.cs | 3 +- .../PianoRollViewModel.FloatingToolbar.cs | 90 +++++ .../ViewModels/PianoRollViewModel.cs | 9 +- OpenUtauMobile/Views/EditorView.axaml | 8 + OpenUtauMobile/Views/EditorView.axaml.cs | 2 + 20 files changed, 694 insertions(+), 5 deletions(-) create mode 100644 OpenUtauMobile/Services/Editor/NoteSelectionToolbarBinding.cs create mode 100644 OpenUtauMobile/Themes/OpenUtauMobile/Controls/FloatingToolbar.axaml create mode 100644 OpenUtauMobile/Themes/OpenUtauMobile/Controls/FloatingToolbar.cs create mode 100644 OpenUtauMobile/Themes/OpenUtauMobile/Controls/FloatingToolbarAction.cs create mode 100644 OpenUtauMobile/Themes/OpenUtauMobile/Tokens/Components/FloatingToolbarTokens.cs create mode 100644 OpenUtauMobile/ViewModels/PianoRollViewModel.FloatingToolbar.cs diff --git a/OpenUtauMobile.DesktopUI/Views/DesktopWorkspace.axaml b/OpenUtauMobile.DesktopUI/Views/DesktopWorkspace.axaml index 0ea40516..99d4833f 100644 --- a/OpenUtauMobile.DesktopUI/Views/DesktopWorkspace.axaml +++ b/OpenUtauMobile.DesktopUI/Views/DesktopWorkspace.axaml @@ -2,8 +2,9 @@ xmlns:vm="using:OpenUtauMobile.ViewModels" xmlns:c="clr-namespace:OpenUtauMobile.Controls;assembly=OpenUtauMobile" xmlns:desktop="using:OpenUtauMobile.DesktopUI.Views" xmlns:icons="https://github.com/MahApps/IconPacks.Avalonia" + xmlns:themeControls="clr-namespace:OpenUtauMobile.Themes.OpenUtauMobile.Controls;assembly=OpenUtauMobile" x:Class="OpenUtauMobile.DesktopUI.Views.DesktopWorkspace" x:DataType="vm:EditorViewModel" Classes="DesktopWorkspace"> - + @@ -47,5 +48,8 @@ + + diff --git a/OpenUtauMobile.DesktopUI/Views/DesktopWorkspace.axaml.cs b/OpenUtauMobile.DesktopUI/Views/DesktopWorkspace.axaml.cs index fd2310e9..b8ede449 100644 --- a/OpenUtauMobile.DesktopUI/Views/DesktopWorkspace.axaml.cs +++ b/OpenUtauMobile.DesktopUI/Views/DesktopWorkspace.axaml.cs @@ -33,6 +33,7 @@ public partial class DesktopWorkspace : UserControl, ICmdSubscriber, IDisposable { private readonly EditorViewModel _editor; private readonly EditorInputController _input; + private NoteSelectionToolbarBinding? _noteToolbarBinding; private readonly DesktopInspector _inspector; private readonly DesktopWorkspaceLayoutController _layoutController; private readonly DesktopInlineEditor _inline; @@ -139,6 +140,8 @@ public DesktopWorkspace(EditorViewModel editor, DesktopLayoutStore layout) { if (_attached || _disposed) return; _attached = true; + _noteToolbarBinding = new NoteSelectionToolbarBinding(NoteToolbar, EditorPageLayer, Piano.NotesCanvas, + _editor, () => IsPianoRollVisible, () => SetActiveArea(EditorInputController.EditArea.PianoRoll)); PianoRollViewModel.BatchEditRunningChanged += OnBatchEditRunningChanged; OnBatchEditRunningChanged(PianoRollViewModel.IsBatchEditRunning); _editor.PropertyChanged += OnEditorChanged; @@ -155,6 +158,8 @@ public DesktopWorkspace(EditorViewModel editor, DesktopLayoutStore layout) }; DetachedFromVisualTree += (_, _) => { + _noteToolbarBinding?.Dispose(); + _noteToolbarBinding = null; SavePanels(); PianoRollViewModel.BatchEditRunningChanged -= OnBatchEditRunningChanged; _editor.PropertyChanged -= OnEditorChanged; @@ -415,6 +420,8 @@ public void Dispose() { if (_disposed) return; _disposed = true; + _noteToolbarBinding?.Dispose(); + _noteToolbarBinding = null; PianoRollViewModel.BatchEditRunningChanged -= OnBatchEditRunningChanged; _inspector.RequestShowParameters -= ShowParameters; _mixer.Dispose(); diff --git a/OpenUtauMobile/Assets/Lang/Strings.en.resx b/OpenUtauMobile/Assets/Lang/Strings.en.resx index 5e2ab204..9f19042b 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.en.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.en.resx @@ -2653,4 +2653,7 @@ Applying replaces the source of this input. Show notes from other tracks overlapping the current part in the piano roll background. + + More actions + diff --git a/OpenUtauMobile/Assets/Lang/Strings.ja.resx b/OpenUtauMobile/Assets/Lang/Strings.ja.resx index 82a23d11..6c9245c0 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.ja.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.ja.resx @@ -2647,4 +2647,7 @@ Applying replaces the source of this input. 現在のパートと重なる他のトラックのノートをピアノロールの背景に表示します。 + + その他の操作 + diff --git a/OpenUtauMobile/Assets/Lang/Strings.ru.resx b/OpenUtauMobile/Assets/Lang/Strings.ru.resx index c439b7de..fe2d3ed4 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.ru.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.ru.resx @@ -2606,4 +2606,7 @@ Applying replaces the source of this input. Показывать на фоне пианоролла ноты других дорожек, пересекающихся с текущим фрагментом. + + Другие действия + diff --git a/OpenUtauMobile/Assets/Lang/Strings.uk.resx b/OpenUtauMobile/Assets/Lang/Strings.uk.resx index 47a66e0b..e5448cbf 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.uk.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.uk.resx @@ -2606,4 +2606,7 @@ Applying replaces the source of this input. Показувати на тлі фортепіанного редактора ноти інших доріжок, що перетинаються з поточним фрагментом. + + Інші дії + diff --git a/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx b/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx index ab7a663b..af234bb8 100644 --- a/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx +++ b/OpenUtauMobile/Assets/Lang/Strings.zh-Hans.resx @@ -2653,4 +2653,7 @@ 在钢琴卷帘背景显示与当前片段重叠的其它轨道音符。 + + 更多操作 + diff --git a/OpenUtauMobile/Services/Editor/EditorInputController.Keyboard.cs b/OpenUtauMobile/Services/Editor/EditorInputController.Keyboard.cs index 8fe6b3b2..f13fc052 100644 --- a/OpenUtauMobile/Services/Editor/EditorInputController.Keyboard.cs +++ b/OpenUtauMobile/Services/Editor/EditorInputController.Keyboard.cs @@ -159,6 +159,8 @@ private async void OnEditorKeyDown(object? sender, KeyEventArgs e) return; } if (EditorShortcuts.IsTextInput(source)) return; + // 浮动工具栏的方向键、空格及 Escape 交给控件自身处理。 + if (source?.GetSelfAndVisualAncestors().Any(node => node is Themes.OpenUtauMobile.Controls.FloatingToolbar) == true) return; if (e.Key == Key.Escape && vm.UseDesktopInput && _activeEditArea != EditArea.Mixer) { _piano.NotesCanvas.CancelTemporaryPitchErase(); diff --git a/OpenUtauMobile/Services/Editor/NoteSelectionToolbarBinding.cs b/OpenUtauMobile/Services/Editor/NoteSelectionToolbarBinding.cs new file mode 100644 index 00000000..666620a2 --- /dev/null +++ b/OpenUtauMobile/Services/Editor/NoteSelectionToolbarBinding.cs @@ -0,0 +1,83 @@ +using System; +using System.Reactive.Disposables; +using System.Reactive.Linq; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Interactivity; +using OpenUtau.Core.Ustx; +using OpenUtauMobile.Controls; +using OpenUtauMobile.Themes.OpenUtauMobile.Controls; +using OpenUtauMobile.ViewModels; +using ReactiveUI; + +namespace OpenUtauMobile.Services.Editor; + +/// 在移动与桌面编辑页中,将音符选择映射到页级浮动工具栏。 +public sealed class NoteSelectionToolbarBinding : IDisposable +{ + private readonly FloatingToolbar _toolbar; + private readonly Control _viewport; + private readonly NotesCanvas _notes; + private readonly EditorViewModel _editor; + private readonly Func _isPianoVisible; + private readonly Action _activatePiano; + private readonly CompositeDisposable _subscriptions = new(); + + /// 跟随编辑页的挂载生命周期建立绑定;视口应为工具栏所在的覆盖层。 + public NoteSelectionToolbarBinding(FloatingToolbar toolbar, Control viewport, NotesCanvas notes, + EditorViewModel editor, Func isPianoVisible, Action activatePiano) + { + _toolbar = toolbar; + _viewport = viewport; + _notes = notes; + _editor = editor; + _isPianoVisible = isPianoVisible; + _activatePiano = activatePiano; + viewport.LayoutUpdated += OnLayoutUpdated; + toolbar.AddHandler(InputElement.PointerPressedEvent, OnToolbarPressed, RoutingStrategies.Tunnel); + Observable.FromEvent( + handler => editor.PianoRollViewModel.RequestInvalidateVisual += handler, + handler => editor.PianoRollViewModel.RequestInvalidateVisual -= handler) + .Subscribe(_ => UpdateNoteToolbarAnchor()) + .DisposeWith(_subscriptions); + editor.PianoRollViewModel.WhenAnyValue(model => model.NoteToolbarActions) + .Subscribe(_ => UpdateNoteToolbarAnchor()) + .DisposeWith(_subscriptions); + } + + /// 页面布局、分割和窗口尺寸变化后重新换算坐标。 + private void OnLayoutUpdated(object? sender, EventArgs e) => UpdateNoteToolbarAnchor(); + + /// 选区工具栏的输入始终归属钢琴卷帘。 + private void OnToolbarPressed(object? sender, PointerPressedEventArgs e) => _activatePiano(); + + /// 将最后选中音符的实际绘制矩形从音符画布转换到编辑页覆盖层。 + private void UpdateNoteToolbarAnchor() + { + if (!_isPianoVisible() || _editor.IsLoadingProject || + _editor.PianoRollViewModel is not { EditMode: PianoRollEditMode.Note, EditingVoicePart: { } part } piano || + piano.SelectedNotes.Count == 0) + { + _toolbar.IsVisible = false; + return; + } + UNote note = piano.NoteToolbarAnchorNote!; + Point point = piano.TickPitchToPoint(part.position + note.position, note.AdjustedTone); + Point? origin = _notes.TranslatePoint(point, _viewport); + _toolbar.IsVisible = origin.HasValue; + if (origin.HasValue) + { + _toolbar.AnchorRect = new Rect(origin.Value, piano.TickToneToSize(note.duration, 1)); + } + } + + /// 解除页级输入、布局与视图模型订阅,离开页面后不再更新工具栏。 + public void Dispose() + { + _viewport.LayoutUpdated -= OnLayoutUpdated; + _toolbar.RemoveHandler(InputElement.PointerPressedEvent, OnToolbarPressed); + _subscriptions.Dispose(); + _toolbar.IsVisible = false; + } +} diff --git a/OpenUtauMobile/Themes/OpenUtauMobile/Controls/ControlThemes.axaml b/OpenUtauMobile/Themes/OpenUtauMobile/Controls/ControlThemes.axaml index b08b9fde..0155670c 100644 --- a/OpenUtauMobile/Themes/OpenUtauMobile/Controls/ControlThemes.axaml +++ b/OpenUtauMobile/Themes/OpenUtauMobile/Controls/ControlThemes.axaml @@ -60,6 +60,7 @@ + diff --git a/OpenUtauMobile/Themes/OpenUtauMobile/Controls/FloatingToolbar.axaml b/OpenUtauMobile/Themes/OpenUtauMobile/Controls/FloatingToolbar.axaml new file mode 100644 index 00000000..c0ace089 --- /dev/null +++ b/OpenUtauMobile/Themes/OpenUtauMobile/Controls/FloatingToolbar.axaml @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenUtauMobile/Themes/OpenUtauMobile/Controls/FloatingToolbar.cs b/OpenUtauMobile/Themes/OpenUtauMobile/Controls/FloatingToolbar.cs new file mode 100644 index 00000000..d497d8a5 --- /dev/null +++ b/OpenUtauMobile/Themes/OpenUtauMobile/Controls/FloatingToolbar.cs @@ -0,0 +1,322 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Avalonia; +using Avalonia.Automation; +using Avalonia.Controls; +using Avalonia.Controls.Primitives; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Layout; +using Avalonia.Styling; +using Avalonia.VisualTree; +using IconPacks.Avalonia.PhosphorIcons; +using OpenUtauMobile.Themes.OpenUtauMobile.Tokens.Components; +using OpenUtauMobile.Themes.OpenUtauMobile.Tokens.Semantic; + +namespace OpenUtauMobile.Themes.OpenUtauMobile.Controls; + +/// +/// 页内浮动操作栏。放入有限尺寸的覆盖层并拉伸至整个宿主,锚点使用宿主坐标。 +/// 操作按集合顺序排列;主面板放不下的尾部操作及固定收纳项进入溢出面板。 +/// +public sealed class FloatingToolbar : TemplatedControl +{ + /// 按优先顺序排列的操作;替换集合以更新工具栏。 + public static readonly StyledProperty> ActionsProperty = + AvaloniaProperty.Register>(nameof(Actions), []); + + /// 需要避让的选区或目标在宿主中的矩形。 + public static readonly StyledProperty AnchorRectProperty = + AvaloniaProperty.Register(nameof(AnchorRect)); + + /// 主面板是否只显示图标;操作名称仍用于提示、朗读及溢出面板。 + public static readonly StyledProperty IconOnlyProperty = + AvaloniaProperty.Register(nameof(IconOnly)); + + /// 溢出面板的展开状态。 + public static readonly StyledProperty IsOverflowOpenProperty = + AvaloniaProperty.Register(nameof(IsOverflowOpen)); + + /// 由使用者或主题资源提供的本地化更多按钮名称。 + public static readonly StyledProperty MoreTextProperty = + AvaloniaProperty.Register(nameof(MoreText), string.Empty); + + /// 按优先顺序排列的操作。 + public IReadOnlyList Actions + { + get => GetValue(ActionsProperty); + set => SetValue(ActionsProperty, value); + } + + /// 目标在覆盖层中的矩形;位置更新不关闭已展开的面板。 + public Rect AnchorRect + { + get => GetValue(AnchorRectProperty); + set => SetValue(AnchorRectProperty, value); + } + + /// 主面板只显示图标。 + public bool IconOnly + { + get => GetValue(IconOnlyProperty); + set => SetValue(IconOnlyProperty, value); + } + + /// 展开或收起溢出面板。 + public bool IsOverflowOpen + { + get => GetValue(IsOverflowOpenProperty); + set => SetValue(IsOverflowOpenProperty, value); + } + + /// 更多按钮的提示与无障碍名称。 + public string MoreText + { + get => GetValue(MoreTextProperty); + set => SetValue(MoreTextProperty, value); + } + + private Border? _mainPanel; + private Border _overflowPanel = null!; + private StackPanel _mainItems = null!; + private StackPanel _overflowItems = null!; + private ToggleButton _more = null!; + private TopLevel? _inputRoot; + private bool _expandUp; + + /// 绑定模板中的两个面板,具体交互状态由基础按钮主题负责。 + protected override void OnApplyTemplate(TemplateAppliedEventArgs e) + { + base.OnApplyTemplate(e); + _mainPanel = e.NameScope.Get("PART_MainPanel"); + _overflowPanel = e.NameScope.Get("PART_OverflowPanel"); + _mainItems = e.NameScope.Get("PART_MainItems"); + _overflowItems = e.NameScope.Get("PART_OverflowItems"); + _more = e.NameScope.Get("PART_More"); + RebuildActions(); + } + + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) + { + base.OnPropertyChanged(change); + if (_mainPanel == null) return; + if (change.Property == ActionsProperty || change.Property == IconOnlyProperty) + { + SetCurrentValue(IsOverflowOpenProperty, false); + RebuildActions(); + } + if (change.Property == AnchorRectProperty || change.Property == IsOverflowOpenProperty) + { + InvalidateMeasure(); + } + if (change.Property == IsVisibleProperty && !IsVisible) + { + SetCurrentValue(IsOverflowOpenProperty, false); + } + } + + /// 生成主面板和溢出面板共用命令的按钮,随后由测量分配可见项。 + private void RebuildActions() + { + _mainItems.Children.Clear(); + _overflowItems.Children.Clear(); + foreach (FloatingToolbarAction action in Actions) + { + _mainItems.Children.Add(CreateActionButton(action, false)); + _overflowItems.Children.Add(CreateActionButton(action, true)); + } + InvalidateMeasure(); + } + + /// 按钮直接使用 ICommand,因此两个面板同步响应 CanExecute。 + private Button CreateActionButton(FloatingToolbarAction action, bool overflow) + { + PackIconPhosphorIcons icon = new() + { + Kind = action.Icon, + Width = IconTokens.Standard, + Height = IconTokens.Standard, + VerticalAlignment = VerticalAlignment.Center + }; + Button button = new() + { + Command = action.Command, + CommandParameter = action.CommandParameter, + Theme = (ControlTheme)this.FindResource(overflow + ? "OpumFloatingToolbarOverflowAction" : "OpumFloatingToolbarAction")! + }; + if (!overflow && IconOnly) + { + button.Classes.Add("icon"); + button.Content = icon; + } + else + { + Grid content = new() + { + ColumnDefinitions = [new ColumnDefinition(GridLength.Auto), new ColumnDefinition(GridLength.Star)], + ColumnSpacing = overflow ? 16 : 12 + }; + TextBlock text = new() + { + Text = action.Text, + TextWrapping = Avalonia.Media.TextWrapping.Wrap, + VerticalAlignment = VerticalAlignment.Center + }; + Grid.SetColumn(text, 1); + content.Children.Add(icon); + content.Children.Add(text); + button.Content = content; + } + ToolTip.SetTip(button, action.Text); + AutomationProperties.SetName(button, action.Text); + button.Click += OnActionClick; + return button; + } + + /// 执行操作后收起溢出面板,保持选区及主面板由业务方控制。 + private void OnActionClick(object? sender, RoutedEventArgs e) + { + bool restoreFocus = IsOverflowOpen; + SetCurrentValue(IsOverflowOpenProperty, false); + if (restoreFocus) _more.Focus(); + } + + /// 按按钮实测宽度分配主面板;预留更多按钮后仍放不下的尾部操作收纳。 + protected override Size MeasureOverride(Size availableSize) + { + if (_mainPanel == null) return base.MeasureOverride(availableSize); + double width = Math.Max(0, availableSize.Width - FloatingToolbarTokens.ViewportInset * 2); + double contentWidth = Math.Max(0, width - FloatingToolbarTokens.ContainerInset * 2); + double requestedWidth = 0; + bool hasOverflow = false; + for (int i = 0; i < Actions.Count; i++) + { + Control button = _mainItems.Children[i]; + button.IsVisible = true; + button.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); + if (Actions[i].AlwaysInOverflow) hasOverflow = true; + else requestedWidth += button.DesiredSize.Width; + } + hasOverflow |= requestedWidth > contentWidth; + if (!hasOverflow) SetCurrentValue(IsOverflowOpenProperty, false); + double remaining = contentWidth - (hasOverflow ? InteractionTokens.TouchTarget : 0); + bool tailOverflow = false; + for (int i = 0; i < Actions.Count; i++) + { + Control button = _mainItems.Children[i]; + bool show = !Actions[i].AlwaysInOverflow && !tailOverflow && button.DesiredSize.Width <= remaining; + if (show) remaining -= button.DesiredSize.Width; + else if (!Actions[i].AlwaysInOverflow) tailOverflow = true; + button.IsVisible = show; + _overflowItems.Children[i].IsVisible = !show; + } + _more.IsVisible = hasOverflow; + _mainPanel.IsVisible = Actions.Count > 0; + _mainPanel.MaxWidth = width; + _mainPanel.Measure(availableSize); + _overflowPanel.IsVisible = hasOverflow && IsOverflowOpen; + if (_overflowPanel.IsVisible) + { + double menuWidth = Math.Min(width, FloatingToolbarTokens.OverflowMaxWidth); + _overflowItems.Measure(new Size(menuWidth, double.PositiveInfinity)); + _overflowPanel.Width = Math.Min(menuWidth, + Math.Max(FloatingToolbarTokens.OverflowMinWidth, _overflowItems.DesiredSize.Width)); + Point main = GetMainPosition(availableSize); + double above = Math.Max(0, main.Y - FloatingToolbarTokens.AnchorGap - FloatingToolbarTokens.ViewportInset); + double below = Math.Max(0, availableSize.Height - FloatingToolbarTokens.ViewportInset - + main.Y - _mainPanel.DesiredSize.Height - FloatingToolbarTokens.AnchorGap); + double requestedHeight = _overflowItems.DesiredSize.Height + FloatingToolbarTokens.ContainerInset * 2; + _expandUp = above >= requestedHeight || above > below; + _overflowPanel.MaxHeight = _expandUp ? above : below; + } + base.MeasureOverride(availableSize); + // 覆盖层本身不向父容器请求额外空间,由宿主拉伸到编辑页大小。 + return default; + } + + /// 优先放在锚点上方,不足时移至下方,最后限制在整个宿主视口内。 + private Point GetMainPosition(Size viewport) + { + Size panel = _mainPanel!.DesiredSize; + const double inset = FloatingToolbarTokens.ViewportInset; + double x = AnchorRect.Center.X - panel.Width / 2; + double y = AnchorRect.Top - FloatingToolbarTokens.AnchorGap - panel.Height; + if (y < inset) y = AnchorRect.Bottom + FloatingToolbarTokens.AnchorGap; + return new Point( + Math.Clamp(x, inset, Math.Max(inset, viewport.Width - inset - panel.Width)), + Math.Clamp(y, inset, Math.Max(inset, viewport.Height - inset - panel.Height))); + } + + /// 两个面板在同一个页内覆盖层中排布,不建立平台窗口或原生弹出层。 + protected override Size ArrangeOverride(Size finalSize) + { + if (_mainPanel == null) return base.ArrangeOverride(finalSize); + Point main = GetMainPosition(finalSize); + Canvas.SetLeft(_mainPanel, main.X); + Canvas.SetTop(_mainPanel, main.Y); + if (!_overflowPanel.IsVisible) return base.ArrangeOverride(finalSize); + double x = main.X + _mainPanel.DesiredSize.Width - _overflowPanel.DesiredSize.Width; + Canvas.SetLeft(_overflowPanel, Math.Clamp(x, FloatingToolbarTokens.ViewportInset, + Math.Max(FloatingToolbarTokens.ViewportInset, finalSize.Width - + FloatingToolbarTokens.ViewportInset - _overflowPanel.DesiredSize.Width))); + Canvas.SetTop(_overflowPanel, _expandUp + ? main.Y - FloatingToolbarTokens.AnchorGap - _overflowPanel.DesiredSize.Height + : main.Y + _mainPanel.DesiredSize.Height + FloatingToolbarTokens.AnchorGap); + return base.ArrangeOverride(finalSize); + } + + protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) + { + base.OnAttachedToVisualTree(e); + _inputRoot = TopLevel.GetTopLevel(this)!; + _inputRoot.AddHandler(PointerPressedEvent, OnRootPointerPressed, RoutingStrategies.Tunnel, true); + _inputRoot.AddHandler(KeyDownEvent, OnRootKeyDown, RoutingStrategies.Tunnel, true); + } + + protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e) + { + _inputRoot!.RemoveHandler(PointerPressedEvent, OnRootPointerPressed); + _inputRoot.RemoveHandler(KeyDownEvent, OnRootKeyDown); + _inputRoot = null; + SetCurrentValue(IsOverflowOpenProperty, false); + base.OnDetachedFromVisualTree(e); + } + + /// 外部按下只收起溢出面板,不拦截原有编辑手势。 + private void OnRootPointerPressed(object? sender, PointerPressedEventArgs e) + { + if (IsOverflowOpen && e.Source is Visual source && !source.GetSelfAndVisualAncestors().Contains(this)) + { + SetCurrentValue(IsOverflowOpenProperty, false); + } + } + + /// Escape 收起菜单并将焦点还给更多按钮。 + private void OnRootKeyDown(object? sender, KeyEventArgs e) + { + if (e.Key != Key.Escape || !IsOverflowOpen) return; + SetCurrentValue(IsOverflowOpenProperty, false); + _more.Focus(); + e.Handled = true; + } + + /// 方向键在当前面板的可用操作间移动,Tab 沿用框架的焦点导航。 + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + if (e.Handled || e.Key is not (Key.Left or Key.Right or Key.Up or Key.Down)) return; + Button[] buttons = IsOverflowOpen + ? [.. _overflowItems.Children.OfType private void RebuildPianoRollContextActions() { + RebuildNoteToolbarActions(); List items = []; bool hasNoteSelection = SelectedNotes.Count > 0; bool hasSingleNote = SelectedNotes.Count == 1; @@ -2405,12 +2407,13 @@ private void RebuildPianoRollContextActions() case PianoRollEditMode.Note: if (EditingVoicePart != null) { - items.Add(CreateBulkLyricEditAction()); + // 笔模式选区操作由页内浮动栏承载,桌面菜单保留原入口。 + if (!hasNoteSelection || UseDesktopMouseInput) items.Add(CreateBulkLyricEditAction()); // 批量编辑 items.Add(CreateBatchEditAction()); } - if (hasNoteSelection) + if (hasNoteSelection && UseDesktopMouseInput) { // 删除音符 items.Add(new ContextActionItem diff --git a/OpenUtauMobile/Views/EditorView.axaml b/OpenUtauMobile/Views/EditorView.axaml index 7de3e569..7d410b75 100644 --- a/OpenUtauMobile/Views/EditorView.axaml +++ b/OpenUtauMobile/Views/EditorView.axaml @@ -12,6 +12,7 @@ xmlns:iconPacks="https://github.com/MahApps/IconPacks.Avalonia" xmlns:foundation="clr-namespace:OpenUtauMobile.Themes.OpenUtauMobile.Tokens.Foundation" xmlns:semantic="clr-namespace:OpenUtauMobile.Themes.OpenUtauMobile.Tokens.Semantic" + xmlns:themeControls="clr-namespace:OpenUtauMobile.Themes.OpenUtauMobile.Controls" x:DataType="vm:EditorViewModel" IsEnabled="{Binding CanEditProject}" Background="{DynamicResource Sem.Color.SurfaceContainerLow}"> @@ -49,6 +50,8 @@ + + @@ -289,4 +292,9 @@ Margin="12" /> + + + diff --git a/OpenUtauMobile/Views/EditorView.axaml.cs b/OpenUtauMobile/Views/EditorView.axaml.cs index f2032715..1e2ba631 100644 --- a/OpenUtauMobile/Views/EditorView.axaml.cs +++ b/OpenUtauMobile/Views/EditorView.axaml.cs @@ -148,6 +148,8 @@ private void BindViewModel(EditorViewModel vm) _viewModelSubscription?.Dispose(); CompositeDisposable disp = new(); _viewModelSubscription = disp; + new NoteSelectionToolbarBinding(NoteToolbar, EditorPageLayer, PianoSurface.NotesCanvas, vm, + () => !IsMixerOpen, () => _input.ActiveArea = EditorInputController.EditArea.PianoRoll).DisposeWith(disp); // 立即设置初始列宽,不动画 SetColWidth(vm.IsTrackHeaderExpanded From 4d4c0558dee1c196e820a77590b69bea67ba41e2 Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:59:09 +0800 Subject: [PATCH 31/45] =?UTF-8?q?ui:=20=E5=B0=86=E4=B8=8A=E4=B8=8B?= =?UTF-8?q?=E6=96=87=E8=8F=9C=E5=8D=95=E6=94=B9=E4=B8=BA=20floating=20tool?= =?UTF-8?q?bar=E6=A0=B7=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 1 + .../Controls/ArrangementSurface.axaml | 20 +-- .../Controls/ArrangementSurface.axaml.cs | 2 +- .../Controls/EditorContextActions.axaml | 10 +- .../Controls/EditorContextActions.axaml.cs | 73 +++-------- .../Controls/EditorModePicker.axaml.cs | 2 +- OpenUtauMobile/Controls/EditorMorePopup.axaml | 6 + .../Controls/PianoRollEditModeSwitcher.axaml | 2 +- .../PianoRollEditModeSwitcher.axaml.cs | 15 +-- .../Controls/PianoRollSurface.axaml | 20 ++- .../Controls/Styles/EditModeSwitcher.axaml | 12 +- .../Styles/EditorContextActions.axaml | 29 ----- .../Controls/TrackEditModeSwitcher.axaml | 4 +- .../Controls/FloatingToolbar.axaml | 85 +++++++++--- .../Controls/FloatingToolbar.cs | 122 +++++++++++++----- .../Controls/FloatingToolbarAction.cs | 3 + .../Themes/OpenUtauMobile/README.md | 12 +- .../Components/FloatingToolbarTokens.cs | 9 +- .../ViewModels/EditorMoreViewModel.cs | 6 +- OpenUtauMobile/ViewModels/EditorViewModel.cs | 8 +- .../ViewModels/PianoRollViewModel.cs | 101 ++------------- 21 files changed, 270 insertions(+), 272 deletions(-) delete mode 100644 OpenUtauMobile/Controls/Styles/EditorContextActions.axaml diff --git a/AGENTS.md b/AGENTS.md index a94f9bb9..4e4c20da 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -44,3 +44,4 @@ - If apply_patch fails, report the exact error. Do not silently switch to string-based editing. - Search with rg and read only relevant code sections. - If an approach fails twice, reassess the root cause before retrying. +- IDE 报告的 InitializeComponent、命名控件等生成成员的解析错误若持续出现请忽略。 diff --git a/OpenUtauMobile/Controls/ArrangementSurface.axaml b/OpenUtauMobile/Controls/ArrangementSurface.axaml index 82348bca..5976f390 100644 --- a/OpenUtauMobile/Controls/ArrangementSurface.axaml +++ b/OpenUtauMobile/Controls/ArrangementSurface.axaml @@ -1,5 +1,4 @@ - + - - - - - - - + + + + + + diff --git a/OpenUtauMobile/Controls/ArrangementSurface.axaml.cs b/OpenUtauMobile/Controls/ArrangementSurface.axaml.cs index 5ac33555..f179c1f1 100644 --- a/OpenUtauMobile/Controls/ArrangementSurface.axaml.cs +++ b/OpenUtauMobile/Controls/ArrangementSurface.axaml.cs @@ -9,7 +9,7 @@ public partial class ArrangementSurface : UserControl public PartsCanvas PartsCanvas => PartsInputCanvas; public void SetHeaderExpanded(bool expanded) => TrackAreaGrid.ColumnDefinitions[0].Width = new Avalonia.Controls.GridLength(expanded ? ViewConstants.TrackHeaderWidthExpanded : ViewConstants.TrackHeaderWidthCollapsed); - public void SetDesktopChrome() { Ruler.IsVisible = true; FloatingActions.IsVisible = false; ArrangementToolbar.IsVisible = false; } + public void SetDesktopChrome() { Ruler.IsVisible = true; FloatingActions.IsVisible = false; } public ArrangementSurface() { InitializeComponent(); diff --git a/OpenUtauMobile/Controls/EditorContextActions.axaml b/OpenUtauMobile/Controls/EditorContextActions.axaml index 508371d9..17777309 100644 --- a/OpenUtauMobile/Controls/EditorContextActions.axaml +++ b/OpenUtauMobile/Controls/EditorContextActions.axaml @@ -1,11 +1,7 @@ - - - - - - + + diff --git a/OpenUtauMobile/Controls/EditorContextActions.axaml.cs b/OpenUtauMobile/Controls/EditorContextActions.axaml.cs index 96f64d72..dcfdbe63 100644 --- a/OpenUtauMobile/Controls/EditorContextActions.axaml.cs +++ b/OpenUtauMobile/Controls/EditorContextActions.axaml.cs @@ -1,26 +1,22 @@ using System.Collections.Generic; +using System.Linq; using Avalonia; -using Avalonia.Automation; using Avalonia.Controls; -using Avalonia.Controls.Primitives; -using Avalonia.Layout; -using Avalonia.Media; -using IconPacks.Avalonia.PhosphorIcons; -using OpenUtauMobile.Themes.OpenUtauMobile.Tokens.Semantic; +using OpenUtauMobile.Themes.OpenUtauMobile.Controls; using OpenUtauMobile.ViewModels; namespace OpenUtauMobile.Controls; -/// 沿编辑区边缘排列、始终显示的可滚动上下文操作栏。 +/// 编辑区右上角的固定纵向浮动工具栏,复用公共工具栏的溢出和键盘行为。 public partial class EditorContextActions : UserControl { /// 现有视图模型生成的上下文操作。 public static readonly StyledProperty?> ActionsProperty = AvaloniaProperty.Register?>(nameof(Actions)); - /// 沿所在编辑区边缘的排列方向。 - public static readonly StyledProperty OrientationProperty = - AvaloniaProperty.Register(nameof(Orientation), Orientation.Vertical); + /// 保留原有交互的编辑模式入口。 + public static readonly StyledProperty ModeSwitchProperty = + AvaloniaProperty.Register(nameof(ModeSwitch)); /// 现有视图模型生成的上下文操作。 public IReadOnlyList? Actions @@ -29,64 +25,37 @@ public IReadOnlyList? Actions set => SetValue(ActionsProperty, value); } - /// 横向用于走带底栏,纵向用于钢琴卷帘侧栏。 - public Orientation Orientation + /// 独立于操作列表的编辑模式入口。 + public Control? ModeSwitch { - get => GetValue(OrientationProperty); - set => SetValue(OrientationProperty, value); + get => GetValue(ModeSwitchProperty); + set => SetValue(ModeSwitchProperty, value); } - /// 初始化有限滚动视口。 + /// 初始化固定在当前编辑区内的浮动层。 public EditorContextActions() { InitializeComponent(); - UpdateOrientation(); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); - if (ActionsList == null) return; + if (Toolbar == null) return; if (change.Property == ActionsProperty) UpdateActionsList(); - if (change.Property == OrientationProperty) UpdateOrientation(); + if (change.Property == ModeSwitchProperty) Toolbar.LeadingContent = ModeSwitch; } - /// 将滚动方向同步到所在边缘。 - private void UpdateOrientation() - { - bool horizontal = Orientation == Orientation.Horizontal; - ActionsList.Orientation = Orientation; - ActionsScrollViewer.HorizontalScrollBarVisibility = horizontal ? ScrollBarVisibility.Hidden : ScrollBarVisibility.Disabled; - ActionsScrollViewer.VerticalScrollBarVisibility = horizontal ? ScrollBarVisibility.Disabled : ScrollBarVisibility.Hidden; - } - - /// 保留操作命令及状态文字,以紧凑图标和文字显示普通操作。 + /// 将现有操作适配到公共工具栏,命令与无障碍名称保持一致。 private void UpdateActionsList() { - ActionsList.Children.Clear(); - if (Actions == null) return; - foreach (ContextActionItem action in Actions) + IReadOnlyList actions = Actions == null ? [] : [.. Actions.Select(action => new FloatingToolbarAction { - Control symbol = action.Label != null - ? new TextBlock { Text = action.Label, FontSize = TypographyTokens.LabelSSize, FontWeight = FontWeight.SemiBold, HorizontalAlignment = HorizontalAlignment.Center } - : new PackIconPhosphorIcons { Kind = action.Icon, Width = IconTokens.Small, Height = IconTokens.Small, HorizontalAlignment = HorizontalAlignment.Center }; - Button button = new() - { - Classes = { "ContextActionBtn" }, - Command = action.Command, - Content = new StackPanel - { - Spacing = 2, - Children = - { - symbol, - new TextBlock { Classes = { "ContextActionCaption" }, Text = action.Tip, FontSize = TypographyTokens.LabelSSize, LineHeight = 14, MaxHeight = 28, TextWrapping = TextWrapping.Wrap, TextTrimming = TextTrimming.CharacterEllipsis, TextAlignment = TextAlignment.Center }, - }, - }, - }; - ToolTip.SetTip(button, action.Tip); - AutomationProperties.SetName(button, action.Tip); - ActionsList.Children.Add(button); - } + Text = action.Tip, + Icon = action.Icon, + Command = action.Command, + IsDanger = action.IsDanger + })]; + Toolbar.Actions = actions; } } diff --git a/OpenUtauMobile/Controls/EditorModePicker.axaml.cs b/OpenUtauMobile/Controls/EditorModePicker.axaml.cs index 4609532f..f61be6be 100644 --- a/OpenUtauMobile/Controls/EditorModePicker.axaml.cs +++ b/OpenUtauMobile/Controls/EditorModePicker.axaml.cs @@ -155,7 +155,7 @@ private void UpdateSelection() foreach (EditorModeOption option in _options) { if (option.Value == SelectedValue) - SwitchButton.Content = new PackIconPhosphorIcons { Kind = option.Icon, Width = IconTokens.Small, Height = IconTokens.Small }; + SwitchButton.Content = new PackIconPhosphorIcons { Classes = { "EditModeIcon" }, Kind = option.Icon }; } foreach (Control item in _layer.Items.Children) item.Classes.Set("Selected", Equals(item.Tag, SelectedValue)); diff --git a/OpenUtauMobile/Controls/EditorMorePopup.axaml b/OpenUtauMobile/Controls/EditorMorePopup.axaml index ab7c018d..3c2d82dc 100644 --- a/OpenUtauMobile/Controls/EditorMorePopup.axaml +++ b/OpenUtauMobile/Controls/EditorMorePopup.axaml @@ -41,6 +41,12 @@ Content="{DynamicResource ExpressionGraph.Title}" Command="{Binding ConfirmCommand}"> ExpressionGraphs + - + \ No newline at end of file diff --git a/OpenUtauMobile/Controls/PianoRollEditModeSwitcher.axaml.cs b/OpenUtauMobile/Controls/PianoRollEditModeSwitcher.axaml.cs index df3be363..f2385e0d 100644 --- a/OpenUtauMobile/Controls/PianoRollEditModeSwitcher.axaml.cs +++ b/OpenUtauMobile/Controls/PianoRollEditModeSwitcher.axaml.cs @@ -11,8 +11,7 @@ public partial class PianoRollEditModeSwitcher : UserControl { /// 当前编辑模式。 public static readonly StyledProperty CurrentModeProperty = - AvaloniaProperty.Register(nameof(CurrentMode), - PianoRollEditMode.Hand, defaultBindingMode: BindingMode.TwoWay); + AvaloniaProperty.Register(nameof(CurrentMode), defaultBindingMode: BindingMode.TwoWay); /// 当前编辑区使用的模式。 public PianoRollEditMode CurrentMode @@ -41,12 +40,12 @@ protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs chang private void UpdateOptions() { Picker.SetOptions([ - new((int)PianoRollEditMode.Hand, PackIconPhosphorIconsKind.Hand, "PianoRoll.DragSelect"), - new((int)PianoRollEditMode.MultiSelect, PackIconPhosphorIconsKind.Selection, "PianoRoll.MultiSelect"), - new((int)PianoRollEditMode.Note, PackIconPhosphorIconsKind.MusicNoteSimple, "PianoRoll.NotePen"), - new((int)PianoRollEditMode.PitchPen, PackIconPhosphorIconsKind.Pencil, "PianoRoll.PitchPen"), - new((int)PianoRollEditMode.Anchor, PackIconPhosphorIconsKind.Cursor, "PianoRoll.Anchor"), - new((int)PianoRollEditMode.Vibrato, PackIconPhosphorIconsKind.WaveSine, "PianoRoll.Vibrato"), + new EditorModeOption((int)PianoRollEditMode.Hand, PackIconPhosphorIconsKind.Hand, "PianoRoll.DragSelect"), + new EditorModeOption((int)PianoRollEditMode.MultiSelect, PackIconPhosphorIconsKind.Selection, "PianoRoll.MultiSelect"), + new EditorModeOption((int)PianoRollEditMode.Note, PackIconPhosphorIconsKind.MusicNoteSimple, "PianoRoll.NotePen"), + new EditorModeOption((int)PianoRollEditMode.PitchPen, PackIconPhosphorIconsKind.Pencil, "PianoRoll.PitchPen"), + new EditorModeOption((int)PianoRollEditMode.Anchor, PackIconPhosphorIconsKind.Cursor, "PianoRoll.Anchor"), + new EditorModeOption((int)PianoRollEditMode.Vibrato, PackIconPhosphorIconsKind.WaveSine, "PianoRoll.Vibrato"), ]); } } \ No newline at end of file diff --git a/OpenUtauMobile/Controls/PianoRollSurface.axaml b/OpenUtauMobile/Controls/PianoRollSurface.axaml index 42ae8279..24a26a23 100644 --- a/OpenUtauMobile/Controls/PianoRollSurface.axaml +++ b/OpenUtauMobile/Controls/PianoRollSurface.axaml @@ -10,7 +10,6 @@ xmlns:tools="clr-namespace:OpenUtauMobile.Tools" xmlns:iconPacks="https://github.com/MahApps/IconPacks.Avalonia" xmlns:foundation="clr-namespace:OpenUtauMobile.Themes.OpenUtauMobile.Tokens.Foundation" - xmlns:semantic="clr-namespace:OpenUtauMobile.Themes.OpenUtauMobile.Tokens.Semantic" x:DataType="vm:EditorViewModel" Background="{DynamicResource Sem.Color.SurfaceContainerLow}"> @@ -19,7 +18,7 @@ - @@ -244,17 +243,14 @@ VerticalAlignment="Center" /> - - + - - - - - + Actions="{Binding PianoRollContextActions}"> + + + + diff --git a/OpenUtauMobile/Controls/Styles/EditModeSwitcher.axaml b/OpenUtauMobile/Controls/Styles/EditModeSwitcher.axaml index 65bb94d3..b8ae4040 100644 --- a/OpenUtauMobile/Controls/Styles/EditModeSwitcher.axaml +++ b/OpenUtauMobile/Controls/Styles/EditModeSwitcher.axaml @@ -1,7 +1,15 @@ - + - - diff --git a/OpenUtauMobile/Controls/TrackEditModeSwitcher.axaml b/OpenUtauMobile/Controls/TrackEditModeSwitcher.axaml index b84ad996..512e09b1 100644 --- a/OpenUtauMobile/Controls/TrackEditModeSwitcher.axaml +++ b/OpenUtauMobile/Controls/TrackEditModeSwitcher.axaml @@ -2,5 +2,5 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:c="clr-namespace:OpenUtauMobile.Controls" x:Class="OpenUtauMobile.Controls.TrackEditModeSwitcher"> - - \ No newline at end of file + + diff --git a/OpenUtauMobile/Themes/OpenUtauMobile/Controls/FloatingToolbar.axaml b/OpenUtauMobile/Themes/OpenUtauMobile/Controls/FloatingToolbar.axaml index c0ace089..e185b2a4 100644 --- a/OpenUtauMobile/Themes/OpenUtauMobile/Controls/FloatingToolbar.axaml +++ b/OpenUtauMobile/Themes/OpenUtauMobile/Controls/FloatingToolbar.axaml @@ -9,12 +9,44 @@ - - + + + - + + + + + + + + + + + + + + + + + + + + + + + @@ -31,26 +63,44 @@ + + + + + + + - - - - - - + + + + + + + + + - + @@ -58,6 +108,9 @@ + + + + - + + + + + + + + + + + + + + + diff --git a/OpenUtauMobile/Views/PluginDetailsView.axaml.cs b/OpenUtauMobile/Views/PluginDetailsView.axaml.cs new file mode 100644 index 00000000..9df22e02 --- /dev/null +++ b/OpenUtauMobile/Views/PluginDetailsView.axaml.cs @@ -0,0 +1,13 @@ +using Avalonia.Controls; + +namespace OpenUtauMobile.Views; + +/// 插件详情导航页,界面状态与操作由视图模型统一管理。 +public partial class PluginDetailsView : UserControl +{ + /// 加载复用公共主题的详情界面。 + public PluginDetailsView() + { + InitializeComponent(); + } +} diff --git a/OpenUtauMobile/Views/PluginManagerView.axaml b/OpenUtauMobile/Views/PluginManagerView.axaml index 8189b851..e0a5233a 100644 --- a/OpenUtauMobile/Views/PluginManagerView.axaml +++ b/OpenUtauMobile/Views/PluginManagerView.axaml @@ -4,9 +4,18 @@ xmlns:services="clr-namespace:OpenUtauMobile.Services" xmlns:foundation="clr-namespace:OpenUtauMobile.Themes.OpenUtauMobile.Tokens.Foundation" xmlns:semantic="clr-namespace:OpenUtauMobile.Themes.OpenUtauMobile.Tokens.Semantic" + xmlns:components="clr-namespace:OpenUtauMobile.Themes.OpenUtauMobile.Tokens.Components" xmlns:icons="https://github.com/MahApps/IconPacks.Avalonia" x:Class="OpenUtauMobile.Views.PluginManagerView" x:DataType="vm:PluginManagerViewModel"> + + + + @@ -37,36 +46,30 @@ - - - - - - - - - - - From 533394828610cd45a6bed3c673f435ec6bfc7636 Mon Sep 17 00:00:00 2001 From: vocoder712 <100213316+vocoder712@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:32:00 +0800 Subject: [PATCH 45/45] =?UTF-8?q?docs:=20=E7=BC=96=E5=86=99=E6=8F=92?= =?UTF-8?q?=E4=BB=B6=E5=BC=80=E5=8F=91=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- OpenUtauMobile.Plugin.Abstractions/README.md | 180 +++++++++++++++++-- 1 file changed, 163 insertions(+), 17 deletions(-) diff --git a/OpenUtauMobile.Plugin.Abstractions/README.md b/OpenUtauMobile.Plugin.Abstractions/README.md index 23e1c72a..b7ff9c41 100644 --- a/OpenUtauMobile.Plugin.Abstractions/README.md +++ b/OpenUtauMobile.Plugin.Abstractions/README.md @@ -1,25 +1,171 @@ -# 歌手插件契约 v3 +# OPUM 歌手插件开发 -插件引用本程序集与 `OpenUtau.Core` 时设置 `Private="false"`,安装包只携带插件自身文件。 +本文面向以 OPUM 宿主 **`dev` 分支**为目标的插件开发者。当前歌手插件契约版本为 **3**,由 `SingerPluginContract.Version` 定义。 -使用 `[assembly: SingerPlugin(typeof(PluginEntry))]` 声明实现 `ISingerPlugin` 的公开无参入口。在 `Register` 内同步登记类型、发现提供方和安装器,不执行扫描或安装。设置通过运行时 WebUI 会话提供,详见 [Web 设置契约](../docs/PLUGIN_WEB_SETTINGS.md)。 +OPUM 依旧兼容跨平台的 OpenUtau 传统插件,不需要遵守本契约,但是传统插件仅能提供音素器而不能获得更加丰富的歌手能力。 -- 插件 ID 使用小写字母开头,最长 160 个字符,仅允许小写字母、数字、点、下划线和短横线,不能以点结尾或使用系统设备保留名;`opum.` 为保留前缀。`SingerPluginContract.ValidatePluginId` 保证它能直接作为跨平台单级目录名。能力 ID 使用 `:<名称>`。 -- 数据目录为 `DataPath/PluginData/`,不迁移或回退读取旧哈希目录。 -- 类型桥接值固定在 `0x10000000` 至 `int.MaxValue` 内,宿主检查冲突。 -- 可用类型的 renderer 工厂须与入口同程序集;类型值、renderer 集合和默认值须与 Core 一致。不可用类型填写原因,renderer 集合与默认值留空。 -- 安装器声明文件后缀,由用户先选安装器再选包;后缀允许重叠。 -- 插件安装使用独立的声明式页面;内置安装由宿主实现。 -- `PrepareAsync` 同时接收末步字段与目标;输入变化后须重新准备,计划只能提交一次。 -- 可选集合的默认值按空集合处理。登记失败不发布本批能力;替换插件需要重启。 -- 发现结果只返回条目;条目位置及状态供安装定位和卸载使用。v3 移除了发现条目、发现结果的 `Diagnostics` 及结果的 `IsComplete`,扫描诊断改用 `context.Log.Write(...)`。旧插件须适配并重新编译。 +## 插件能力 -发现、删除、安装和 Web 设置上下文通过 `Notifications` 提供用户警告: +OPUM 加载 .NET DLL 插件。歌手插件可以: + +- 定义歌手类型、显示名称、明暗主题颜色和可选渲染器。 +- 发现本地声库或从服务取得歌手列表,向宿主提供 `USinger` 实例。 +- 实现渲染器,将宿主的合成短句交给本地引擎或远端服务,返回音频和支持的曲线数据。 +- 提供声库安装器,由宿主展示多步表单、内容预览、安装目标和进度;插件负责包格式解析与安装逻辑。 +- 提供歌手删除操作,以及通过内嵌 WebView 或系统浏览器打开的设置页面。 +- 使用独立的数据目录、日志和用户警告通知。 + +扩展范围是歌手与合成流程;本契约不提供自定义原生页面、菜单命令或编辑器扩展接口。插件安装、更新和启停在重启后生效。 + +## 契约接口概况 + +`OpenUtauMobile.Plugin.Abstractions` 提供宿主接入契约,`OpenUtau.Core` 提供歌手和渲染接口。 + +| 接口或类型 | 用途 | +| --- | --- | +| `SingerPluginAttribute` | 在程序集上声明插件入口和契约版本。 | +| `ISingerPlugin` | 提供插件身份、登记能力,以及可选的 Web 设置入口。 | +| `ISingerPluginRegistrar` | 同步登记歌手类型、发现提供方和安装器。 | +| `SingerTypeDescriptor` | 描述歌手类型、桥接值、渲染器、颜色和本地化名称。 | +| `USinger`(Core) | 表示可供轨道选择和合成使用的歌手。 | +| `IRenderer`、`RendererAttribute`(Core) | 实现合成并声明渲染器 ID 与歌手类型的关联。 | +| `ISingerProvider` | 发现歌手,并按需实现删除。 | +| `ISingerPackageInstaller`、`ISingerInstallSession` | 描述安装入口,驱动包分析、步骤切换、预检与提交。 | +| `PluginFieldDescriptor`、`PluginValue` | 描述安装表单的文本、开关、数值、选项和文件路径字段。 | +| `IPluginWebSettingsSession` | 提供设置页地址,管理本次网页会话的资源。 | +| `PluginStorageContext` | 提供插件数据目录和资源目录。 | +| `IPluginLog`、`IPluginNotifications` | 记录诊断,发布、更新和清除用户警告。 | + +### 身份与类型 + +插件 ID 是持久身份,例如 `org.example.dummy`。使用小写字母开头,总长最多 160 个字符,字符集为小写字母、数字、点、下划线和短横线;结尾使用字母、数字、下划线或短横线。`opum.` 前缀及系统设备名由宿主保留。可调用 `SingerPluginContract.ValidatePluginId` 检查 ID。 + +类型、提供方和安装器的 ID 使用 `:<名称>`,例如 `org.example.dummy:voice`。完整 ID 最长 160 个字符,字符集同插件 ID,另允许冒号。显示名称可随语言变化,ID 保持稳定。 + +歌手类型通过 `BridgeValue` 与 Core 的 `USingerType` 对接。选择 `0x10000000` 至 `int.MaxValue` 范围内的独立整数,并在歌手实例、渲染器和类型描述中使用同一值。渲染器 ID 也应保持稳定,并与其他插件区分。 + +### 发现与安装 + +`Register` 同步提交能力描述;目录扫描、网络访问和安装工作放在对应的运行时方法中。 + +`ISingerProvider.DiscoverAsync` 接收歌手根目录、语言、存储、日志和取消令牌,返回 `SingerDiscoveryResult`。每个条目包含位置、名称、可用状态和可选的 `USinger`。宿主将发现结果汇入歌手列表,位置和状态也用于安装定位与删除。实现 `CanDelete` 和 `DeleteAsync` 即可提供删除能力;删除时根据 `SingerDeletionContext.Roots` 中的当前路径与写入权限处理文件。 + +安装时,用户先选择安装器,再按其 `Extensions` 选择文件。安装器创建会话,宿主依次调用: + +1. `AnalyzeAsync`:读取包并生成首个步骤。 +2. `NextAsync` / `BackAsync`:处理表单和步骤切换,以 `Revision` 标识当前状态版本。 +3. `PrepareAsync`:接收最终步骤字段和目标,生成包含摘要、目标路径及歌手引用的 `PreparedInstall`。 +4. `InstallAsync`:使用 `PlanId` 提交该计划,返回实际发布位置及歌手引用。 +5. `DisposeAsync`:释放会话资源,宿主清理临时工作区。 + +字段或目标变化后重新准备计划,每个计划提交一次。`SingerInstallContext` 提供文件流、本地包路径、临时工作区、可写目标和已安装歌手查询;使用 `Files.PublishAsync` 将准备好的文件或目录发布到目标。歌手引用由提供方 ID 和歌手 ID 组成,用于安装后刷新定位。 + +### 设置、存储与通知 + +实现 `GetWebSettingsAsync` 返回设置入口标题,用户打开时由 `OpenWebSettingsAsync` 创建 `IPluginWebSettingsSession`。查询方法只返回当前入口信息,网页服务在打开会话时启动。 + +会话的 `Address` 为绝对 HTTP/HTTPS 地址,可指向本地或远端页面。离开设置页时,宿主调用 `DisposeAsync`;插件在此关闭监听和其他会话资源。`ReloadResourcesOnClose` 默认 `true`,关闭设置后会重新发现歌手。 + +发现、安装和设置上下文共享 `Storage`: + +- `DataDirectory`:`DataPath/PluginData/`,用于配置、凭据和持久数据。 +- `ResourceDirectory`:数据目录下的 `Resources`,用于插件资源。 + +插件自行创建所需子目录,管理配置格式和凭据存储。通过 `context.Log.Write(...)` 记录诊断;需要用户处理的问题通过 `context.Notifications.PublishWarning(new PluginWarning(code, message))` 展示,恢复后调用 `ClearWarning(code)`。相同代码更新同一条警告,宿主按插件隔离通知。 + +## 构建最小插件 + +以下示例先完成入口加载,再添加歌手能力。需要 .NET 10 SDK,以及 OPUM `dev` 分支源码。示例目录布局: + +```text +工作目录/ +├─ OpenUtauMobile/ +└─ DummyPlugin/ + ├─ DummyPlugin.csproj + └─ PluginEntry.cs +``` + +### 1. 创建项目 + +在 `DummyPlugin` 中创建 `DummyPlugin.csproj`: + +```xml + + + net10.0 + enable + enable + $(MSBuildThisFileDirectory)..\OpenUtauMobile + + + + + + +``` + +两份宿主程序集由 OPUM 提供,`Private="false"` 用于让插件引用宿主提供的实例。交付文件包含插件自身程序集、资源及所需的额外依赖。 + +### 2. 声明入口 + +创建 `PluginEntry.cs`: + +```csharp +using OpenUtauMobile.Plugin.Abstractions; + +[assembly: SingerPlugin(typeof(DummyPlugin.PluginEntry))] + +namespace DummyPlugin +{ + /// 最小插件入口。 + public sealed class PluginEntry : ISingerPlugin + { + /// 插件的稳定身份与显示名称。 + public SingerPluginDescriptor Descriptor => new("org.example.dummy", "Dummy Plugin"); + + /// 在此登记插件提供的歌手能力。 + public void Register(ISingerPluginRegistrar registrar) + { + } + } +} +``` + +入口为公开类,具有公开无参构造函数。`SingerPluginAttribute` 默认携带编译时的 `SingerPluginContract.Version`。此例完成插件身份和入口声明,`Register` 留作后续能力登记。 + +### 3. 构建与安装 + +在 `DummyPlugin` 目录运行: + +```powershell +dotnet build DummyPlugin.csproj -c Release +``` + +产物为 `bin/Release/net10.0/DummyPlugin.dll`。宿主源码位于其他目录时,可在构建命令中传入 `-p:OpumRoot="宿主源码绝对路径"`。 + +在 OPUM 的“插件管理”中安装该 DLL,重启后查看插件详情中的身份和加载状态。也可将 DLL 放入 `DataPath/Plugins`,在插件管理中启用后重启。更新时先卸载旧 DLL 并重启,再安装新 DLL。 + +### 4. 接入可合成歌手 + +在最小入口上依次添加: + +1. 实现 Core 的 `USinger`,提供歌手身份、显示信息、资源加载和类型桥接值。 +2. 在入口所在程序集内实现公开、具有公开无参构造函数的 `IRenderer`,用 `[Renderer("org.example.dummy:render", (USingerType)0x10010001)]` 声明关联。`IRenderer.SingerType` 使用同一桥接值。 +3. 在 `Register` 中调用 `RegisterSingerType`,将该渲染器 ID 填入 `RendererIds` 和 `DefaultRendererId`。多个渲染器时,默认值取 `Renderers.GetDefaultRenderer(bridgeValue)`,集合取 `Renderers.GetSupportedRenderers(bridgeValue)`。 +4. 实现 `ISingerProvider`,以 `org.example.dummy:provider` 为 ID,`SingerTypeIds` 引用上述类型 ID;在 `DiscoverAsync` 中返回带有歌手实例的发现条目,再用 `RegisterProvider` 登记。 +5. 按需实现安装器或 Web 设置,并重新构建、安装和重启。 + +单渲染器类型的登记示例(放入 `Register` 方法): ```csharp -context.Notifications.PublishWarning(new("catalog.fetch-failed", "获取歌手列表失败。", "请检查网络或打开插件设置重新认证。")); -// 成功恢复后清除同代码警告。 -context.Notifications.ClearWarning("catalog.fetch-failed"); +registrar.RegisterSingerType(new SingerTypeDescriptor( + Id: "org.example.dummy:voice", + BridgeValue: (OpenUtau.Core.Ustx.USingerType)0x10010001, + DisplayName: "Example Voice", + RendererIds: ["org.example.dummy:render"], + DefaultRendererId: "org.example.dummy:render")); ``` -同插件同代码更新原警告,不重复堆积;宿主自动限定插件归属,允许后台线程调用。Message/Details 是插件本地化后的纯文本,不能包含凭据或认证 URL。`Log` 只负责诊断日志。 +完成渲染器和发现提供方后,刷新歌手列表,在轨道中选择歌手,输入音符和歌词,验证播放与音频导出。