Skip to content

Commit 25efb4b

Browse files
committed
refactor: MaaAgentServer
1 parent 4fa224b commit 25efb4b

3 files changed

Lines changed: 146 additions & 47 deletions

File tree

src/MaaFramework.Binding.Native/MaaAgentServer.cs

Lines changed: 118 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -10,55 +10,143 @@ namespace MaaFramework.Binding;
1010
/// A wrapper class providing a reference implementation for <see cref="MaaFramework.Binding.Interop.Native.MaaAgentServer"/>.
1111
/// </summary>
1212
[DebuggerDisplay("{DebuggerDisplay,nq}")]
13-
public class MaaAgentServer : IMaaAgentServer
13+
public sealed class MaaAgentServer : IMaaAgentServer
1414
{
15+
/// <summary>
16+
/// Gets the unique identifier used to communicate with the agent client.
17+
/// </summary>
18+
public static string CurrentId { get; private set; }
19+
20+
/// <summary>
21+
/// Gets the current <see cref="MaaAgentServer"/> instance.
22+
/// </summary>
23+
public static MaaAgentServer Current { get; }
24+
25+
/// <summary>
26+
/// Creates a <see cref="MaaAgentServer"/> instance.
27+
/// </summary>
28+
private MaaAgentServer() { }
29+
static MaaAgentServer()
30+
{
31+
NativeLibrary.Init(isAgentServer: true);
32+
CurrentId = string.Empty;
33+
Current = new();
34+
}
35+
1536
private readonly MaaMarshaledApiRegistry<MaaCustomActionCallback> _actions = new();
1637
private readonly MaaMarshaledApiRegistry<MaaCustomRecognitionCallback> _recognitions = new();
17-
private string? _debugSocketId;
1838

1939
[ExcludeFromCodeCoverage(Justification = "Debugger display.")]
2040
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
21-
private string DebuggerDisplay => $"{GetType().Name} {{ SocketId = {_debugSocketId}, CustomActions = [{string.Join(", ", _actions.Names)}] , CustomRecognitions = [{string.Join(" & ", _recognitions.Names)}] }}";
41+
private string DebuggerDisplay => $"{GetType().Name} {{ {nameof(CurrentId)} = {CurrentId}, CustomActions = [{string.Join(", ", _actions.Names)}] , CustomRecognitions = [{string.Join(" & ", _recognitions.Names)}] }}";
42+
43+
IMaaAgentServer IMaaAgentServer.WithIdentifier(string identifier) => WithIdentifier(identifier);
44+
IMaaAgentServer IMaaAgentServer.Register<T>(string name, T custom) => Register(name, custom);
45+
IMaaAgentServer IMaaAgentServer.Register<T>(T custom) => Register(custom);
46+
IMaaAgentServer IMaaAgentServer.StartUp() => StartUp();
47+
IMaaAgentServer IMaaAgentServer.ShutDown() => ShutDown();
48+
IMaaAgentServer IMaaAgentServer.Join() => Join();
49+
IMaaAgentServer IMaaAgentServer.Detach() => Detach();
50+
51+
/// <inheritdoc cref="IMaaAgentServer.WithIdentifier"/>
52+
public MaaAgentServer WithIdentifier(string identifier)
53+
{
54+
CurrentId = identifier;
55+
return this;
56+
}
2257

23-
/// <inheritdoc/>
24-
public bool Register<T>(string name, T custom) where T : IMaaCustomResource
58+
/// <inheritdoc cref="IMaaAgentServer.Register{T}(string, T)"/>
59+
public MaaAgentServer Register<T>(string name, T custom) where T : IMaaCustomResource
2560
{
2661
custom.Name = name;
2762
return Register(custom);
2863
}
2964

30-
/// <inheritdoc/>
65+
/// <inheritdoc cref="IMaaAgentServer.Register{T}(T)"/>
3166
/// <remarks>
3267
/// Wrapper of <see cref="MaaAgentServerRegisterCustomAction"/> and <see cref="MaaAgentServerRegisterCustomRecognition"/>.
3368
/// </remarks>
34-
public bool Register<T>(T custom) where T : IMaaCustomResource => custom switch
69+
public MaaAgentServer Register<T>(T custom) where T : IMaaCustomResource
3570
{
36-
IMaaCustomAction res
37-
=> MaaAgentServerRegisterCustomAction(res.Name, res.Convert(out var callback), nint.Zero)
38-
&& _actions.Register(res.Name, callback),
39-
IMaaCustomRecognition res
40-
=> MaaAgentServerRegisterCustomRecognition(res.Name, res.Convert(out var callback), nint.Zero)
41-
&& _recognitions.Register(res.Name, callback),
42-
_
43-
=> throw new NotImplementedException($"Type '{typeof(T)}' is not implemented."),
44-
};
45-
46-
/// <inheritdoc/>
47-
public bool StartUp(string identifier)
71+
var ret = custom switch
72+
{
73+
IMaaCustomAction res
74+
=> MaaAgentServerRegisterCustomAction(res.Name, res.Convert(out var callback), nint.Zero)
75+
&& _actions.Register(res.Name, callback),
76+
IMaaCustomRecognition res
77+
=> MaaAgentServerRegisterCustomRecognition(res.Name, res.Convert(out var callback), nint.Zero)
78+
&& _recognitions.Register(res.Name, callback),
79+
_
80+
=> throw new NotImplementedException($"Type '{typeof(T)}' is not implemented."),
81+
};
82+
_ = ret.ThrowIfFalse();
83+
return this;
84+
}
85+
86+
/// <inheritdoc cref="IMaaAgentServer.StartUp"/>
87+
/// <remarks>
88+
/// Wrapper of <see cref="MaaAgentServerStartUp"/>.
89+
/// </remarks>
90+
public MaaAgentServer StartUp()
4891
{
49-
_debugSocketId = identifier;
50-
return MaaAgentServerStartUp(_debugSocketId);
92+
if (string.IsNullOrEmpty(CurrentId))
93+
throw new InvalidOperationException("Identifier is not set. Use 'WithIdentifier' method to set it.");
94+
_ = MaaAgentServerStartUp(CurrentId).ThrowIfFalse();
95+
return this;
5196
}
5297

53-
/// <inheritdoc/>
54-
public void ShutDown()
55-
=> MaaAgentServerShutDown();
98+
/// <inheritdoc cref="IMaaAgentServer.ShutDown"/>
99+
/// <remarks>
100+
/// Wrapper of <see cref="MaaAgentServerShutDown"/>.
101+
/// </remarks>
102+
public MaaAgentServer ShutDown()
103+
{
104+
MaaAgentServerShutDown();
105+
return this;
106+
}
56107

57-
/// <inheritdoc/>
58-
public void Join()
59-
=> MaaAgentServerJoin();
108+
/// <inheritdoc cref="IMaaAgentServer.Join"/>
109+
/// <remarks>
110+
/// Wrapper of <see cref="MaaAgentServerJoin"/>.
111+
/// </remarks>
112+
public MaaAgentServer Join()
113+
{
114+
MaaAgentServerJoin();
115+
return this;
116+
}
117+
118+
/// <inheritdoc cref="IMaaAgentServer.Detach"/>
119+
/// <remarks>
120+
/// Wrapper of <see cref="MaaAgentServerDetach"/>.
121+
/// </remarks>
122+
public MaaAgentServer Detach()
123+
{
124+
MaaAgentServerDetach();
125+
return this;
126+
}
127+
}
60128

61-
/// <inheritdoc/>
62-
public void Detach()
63-
=> MaaAgentServerDetach();
129+
/// <summary>
130+
/// A static class providing extension methods for <see cref="MaaAgentServer"/>.
131+
/// </summary>
132+
public static class MaaAgentServerExtensions
133+
{
134+
/// <returns></returns>
135+
/// <inheritdoc cref="IMaaToolkitConfig.InitOption"/>
136+
public static MaaAgentServer WithToolkitConfig_InitOption(this MaaAgentServer server, string userPath = nameof(Environment.CurrentDirectory), [StringSyntax("Json")] string defaultJson = "{}")
137+
{
138+
_ = MaaToolkit.Shared.Config.InitOption(userPath, defaultJson).ThrowIfFalse();
139+
return server;
140+
}
141+
142+
/// <summary>
143+
/// Configures the MaaAgentServer to use the specified native libraries.
144+
/// </summary>
145+
/// <param name="server">The server.</param>
146+
/// <param name="paths">The directory paths to search for native libraries.</param>
147+
public static MaaAgentServer WithNativeLibrary(this MaaAgentServer server, params string[] paths)
148+
{
149+
NativeLibrary.Init(true, paths);
150+
return server;
151+
}
64152
}

src/MaaFramework.Binding.UnitTests/Test_IMaaAgentServer.cs

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,21 @@ public static int Main()
1414
var socketId = commandLineArgs[^1];
1515
var userPath = commandLineArgs[^2];
1616
var dllPath = commandLineArgs[^3];
17+
Test(socketId, userPath, dllPath);
1718

18-
NativeBindingInfo.Set(isAgentServer: true, dllPath); // First step
19-
_ = new MaaToolkit(true, userPath);
20-
var agentServer = new MaaAgentServer();
21-
_ = agentServer.Register(Custom.Recognition);
22-
_ = agentServer.Register(Custom.Action);
23-
_ = agentServer.StartUp(socketId);
24-
agentServer.Join();
25-
agentServer.ShutDown();
2619
return 0;
2720
}
21+
22+
public static void Test(string id, string userPath, string dllPath)
23+
{
24+
_ = MaaAgentServer.Current // test double call
25+
.WithIdentifier(id).WithIdentifier(id)
26+
.WithNativeLibrary(dllPath).WithNativeLibrary(dllPath)
27+
.WithToolkitConfig_InitOption(userPath).WithToolkitConfig_InitOption(userPath)
28+
.Register(Custom.Recognition) // cat not double call from here
29+
.Register(Custom.Action)
30+
.StartUp()
31+
.Join().Join() // test double call
32+
.ShutDown().ShutDown();
33+
}
2834
}

src/MaaFramework.Binding/IMaaAgentServer.cs

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,37 +7,42 @@ namespace MaaFramework.Binding;
77
/// </summary>
88
public interface IMaaAgentServer
99
{
10+
/// <summary>
11+
/// Configures the unique identifier used to communicate with the agent client.
12+
/// </summary>
13+
/// <param name="identifier">The unique identifier used to communicate with the agent client.</param>
14+
IMaaAgentServer WithIdentifier(string identifier);
15+
1016
/// <summary>
1117
/// Registers a <see cref="IMaaCustomAction"/> or <see cref="IMaaCustomRecognition"/> in the <see cref="IMaaAgentServer"/>.
1218
/// </summary>
1319
/// <typeparam name="T">The <see cref="IMaaCustomAction"/> or <see cref="IMaaCustomRecognition"/>.</typeparam>
1420
/// <param name="name">The new name that will be used to reference the custom resource.</param>
1521
/// <param name="custom">The custom resource instance to register.</param>
16-
/// <returns><see langword="true"/> if the registration was successful; otherwise, <see langword="false"/>.</returns>
17-
bool Register<T>(string name, T custom) where T : IMaaCustomResource;
22+
/// <exception cref="MaaInteroperationException">Thrown if the registration fails.</exception>
23+
IMaaAgentServer Register<T>(string name, T custom) where T : IMaaCustomResource;
1824

1925
/// <inheritdoc cref="Register{T}(string, T)"/>
20-
bool Register<T>(T custom) where T : IMaaCustomResource;
26+
IMaaAgentServer Register<T>(T custom) where T : IMaaCustomResource;
2127

2228
/// <summary>
2329
/// Starts up the agent server to prepare for receiving client messages from the specified connection.
2430
/// </summary>
25-
/// <param name="identifier">The connection identifier.</param>
26-
/// <returns><see langword="true"/> if the server started successfully; otherwise, <see langword="false"/>.</returns>
27-
bool StartUp(string identifier);
31+
/// <exception cref="MaaInteroperationException">Thrown if the registration fails.</exception>
32+
IMaaAgentServer StartUp();
2833

2934
/// <summary>
3035
/// Shuts down the agent server.
3136
/// </summary>
32-
void ShutDown();
37+
IMaaAgentServer ShutDown();
3338

3439
/// <summary>
3540
/// Blocks the calling thread until the thread for receiving client messages finishes its execution.
3641
/// </summary>
37-
void Join();
42+
IMaaAgentServer Join();
3843

3944
/// <summary>
4045
/// Separates the thread for receiving client messages, allowing execution to continue independently.
4146
/// </summary>
42-
void Detach();
47+
IMaaAgentServer Detach();
4348
}

0 commit comments

Comments
 (0)