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" />
-