Snapshot for release 2026.10.15.2 (internal 9094d68)
This commit is contained in:
parent
8bb1c3aa23
commit
516ad2bdf2
121 changed files with 6486 additions and 781 deletions
|
|
@ -24,6 +24,9 @@
|
|||
<Compile Include="..\..\src\RynthCore.Engine\Plugins\EngineSettingsFile.cs" Link="Engine\EngineSettingsFile.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\ReloadCapNotice.cs" Link="Engine\ReloadCapNotice.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AutoIdPolicy.cs" Link="Engine\AutoIdPolicy.cs" />
|
||||
<!-- EditIltServerName starts from IltDetect's defaults (IltDetect shares a parser with AelrynthWire). -->
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\IltDetect.cs" Link="Engine\IltDetect.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AelrynthWire.cs" Link="Engine\AelrynthWire.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -52,6 +52,7 @@ namespace EngineSettingsTests
|
|||
Run(nameof(SaveLeavesMalformedFileAlone), SaveLeavesMalformedFileAlone);
|
||||
Run(nameof(MaxHotReloadsReadAndKept), MaxHotReloadsReadAndKept);
|
||||
Run(nameof(CloseOnServerDisconnectDefaultOnAndSaved), CloseOnServerDisconnectDefaultOnAndSaved);
|
||||
Run(nameof(IltServerNamesEdit), IltServerNamesEdit);
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
|
@ -88,6 +89,8 @@ namespace EngineSettingsTests
|
|||
if (!RynthCore.Engine.Compatibility.AutoIdPolicy.TryParseMode(args[1], out var aim)) throw new ArgumentException(args[1]);
|
||||
EngineSettings.AutoIdMode = aim;
|
||||
break;
|
||||
case "ilt-add": Console.WriteLine("Changed=" + EngineSettings.EditIltServerName(args[1], add: true)); break;
|
||||
case "ilt-remove": Console.WriteLine("Changed=" + EngineSettings.EditIltServerName(args[1], add: false)); break;
|
||||
case "dump":
|
||||
Console.WriteLine("AutoIdMode=" + EngineSettings.AutoIdMode);
|
||||
Console.WriteLine("PluginPaths=" + string.Join("|", EngineSettings.PluginPaths));
|
||||
|
|
@ -97,6 +100,7 @@ namespace EngineSettingsTests
|
|||
Console.WriteLine("ServerMessageStream=" + EngineSettings.ServerMessageStream);
|
||||
Console.WriteLine("MaxHotReloads=" + EngineSettings.MaxHotReloads);
|
||||
Console.WriteLine("CloseOnServerDisconnect=" + EngineSettings.CloseOnServerDisconnect);
|
||||
Console.WriteLine("IltServerNames=" + (EngineSettings.IltServerNames is { } n ? string.Join("|", n) : "(none)"));
|
||||
break;
|
||||
default: throw new ArgumentException(args[0]);
|
||||
}
|
||||
|
|
@ -359,6 +363,32 @@ namespace EngineSettingsTests
|
|||
}
|
||||
}
|
||||
|
||||
// /rc server names ilt add|remove (2026.10.5.46): the first edit starts from the defaults,
|
||||
// the edit is saved with the launcher's keys kept, and repeats, unknown, empty and overlong
|
||||
// patterns change nothing.
|
||||
private static void IltServerNamesEdit()
|
||||
{
|
||||
string dir = NewDir("iltnames");
|
||||
string path = Path.Combine(dir, "engine.json");
|
||||
File.WriteAllText(path, LauncherFile);
|
||||
JsonElement before = ReadJson(path);
|
||||
|
||||
Eq(DumpValue(RunChild(path, "dump").Out, "IltServerNames"), "(none)", "no list in the file");
|
||||
Eq(DumpValue(RunChild(path, "ilt-add", "Frosthaven").Out, "Changed"), "True", "add");
|
||||
string defaults = string.Join("|", RynthCore.Engine.Compatibility.IltDetect.DefaultServerNames);
|
||||
Eq(DumpValue(RunChild(path, "dump").Out, "IltServerNames"), defaults + "|Frosthaven", "the defaults kept, the new one added");
|
||||
Eq(Raw(ReadJson(path).GetProperty("LauncherWindow")), Raw(before.GetProperty("LauncherWindow")), "the launcher's keys kept");
|
||||
NoTempFilesLeft(dir);
|
||||
|
||||
Eq(DumpValue(RunChild(path, "ilt-add", "FROSTHAVEN").Out, "Changed"), "False", "adding again (any case) changes nothing");
|
||||
Eq(DumpValue(RunChild(path, "ilt-remove", "nope").Out, "Changed"), "False", "removing an unknown pattern changes nothing");
|
||||
Eq(DumpValue(RunChild(path, "ilt-add", " ").Out, "Changed"), "False", "an empty pattern is refused");
|
||||
Eq(DumpValue(RunChild(path, "ilt-add", new string('x', EngineSettings.MaxIltServerNameLength + 1)).Out, "Changed"), "False",
|
||||
"an overlong pattern is refused");
|
||||
Eq(DumpValue(RunChild(path, "ilt-remove", "frosthaven").Out, "Changed"), "True", "remove (any case)");
|
||||
Eq(DumpValue(RunChild(path, "dump").Out, "IltServerNames"), defaults, "back to the defaults");
|
||||
}
|
||||
|
||||
/// <summary>The value of a "Name=value" line of the child's dump output ("" if none).</summary>
|
||||
private static string DumpValue(string output, string name)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -28,6 +28,8 @@
|
|||
<Compile Include="..\..\src\RynthCore.App\AccountPasswordProtection.cs" Link="App\AccountPasswordProtection.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.App\LaunchServerProfile.cs" Link="App\LaunchServerProfile.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.App\AcLaunchArgumentBuilder.cs" Link="App\AcLaunchArgumentBuilder.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.App\FirstLoginRules.cs" Link="App\FirstLoginRules.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.App\UserPrefsSwapRecovery.cs" Link="App\UserPrefsSwapRecovery.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -179,8 +179,21 @@ internal static class Program
|
|||
string preview = builder.BuildMaskedArguments(ace, a);
|
||||
Check(!preview.Contains("t3st") && preview.Contains("-v " + AcLaunchArgumentBuilder.PasswordMask), "preview masked: " + preview);
|
||||
LaunchAccountProfile noPw = loaded.AccountProfiles.First(x => x.Id == "b");
|
||||
Check(builder.BuildMaskedArguments(ace, noPw).Contains("-v \"\""), "preview of an account without a password");
|
||||
Check(builder.BuildArguments(ace, noPw).Contains("-v \"\""), "no saved password still launches as before (empty)");
|
||||
Check(AcLaunchArgumentBuilder.NeedsPassword(noPw) && !AcLaunchArgumentBuilder.NeedsPassword(a), "NeedsPassword: only the account without one");
|
||||
Check(builder.BuildMaskedArguments(ace, noPw).StartsWith("No password is saved for account 'B'"),
|
||||
"preview of an account without a password says so: " + builder.BuildMaskedArguments(ace, noPw));
|
||||
// The client exits with "You can only run the game from the launcher program" on an
|
||||
// empty password (Conquest, 2026-10-13), so the launch is refused instead.
|
||||
string refusal = Throws(() => builder.BuildArguments(ace, noPw));
|
||||
Check(refusal.StartsWith("No password is saved for account 'B'"), "no saved password: launch refused: " + refusal);
|
||||
Check(Throws(() => builder.BuildArguments(gdle, noPw)).StartsWith("No password"), "GDLE refused too");
|
||||
|
||||
// Account names: ACE's 50-character limit; GDLE's "account:password" argument.
|
||||
Check(AcLaunchArgumentBuilder.AccountNameProblem("SK", AcEmulatorKind.Ace) == null, "a short name is fine");
|
||||
Check(AcLaunchArgumentBuilder.AccountNameProblem(new string('x', 51), AcEmulatorKind.Ace)?.Contains("50") == true, "51 characters: too long");
|
||||
Check(AcLaunchArgumentBuilder.AccountNameProblem("a:b", AcEmulatorKind.Ace) == null, "a colon is fine on ACE");
|
||||
Check(AcLaunchArgumentBuilder.AccountNameProblem("a:b", AcEmulatorKind.Gdle) != null, "a colon is refused on GDLE");
|
||||
Check(AcLaunchArgumentBuilder.AccountNameProblem(" ", AcEmulatorKind.Ace) != null, "blank is refused");
|
||||
|
||||
LaunchAccountProfile copy = a.Clone();
|
||||
Check(copy.PasswordProtected == a.PasswordProtected, "Clone keeps the encrypted password");
|
||||
|
|
@ -278,6 +291,96 @@ internal static class Program
|
|||
AppSettingsStore.Save(loaded);
|
||||
CheckNoPlainText("LEAK-CHECK-PW");
|
||||
});
|
||||
|
||||
// ── First Login dialog rules (a new server: no password, no characters yet) ──
|
||||
Scenario("first login on a new server", root, () =>
|
||||
{
|
||||
var withPw = new LaunchAccountProfile { Id = "ilt", AccountName = "silentkelpie" };
|
||||
withPw.SetPassword(Pw);
|
||||
var noPwSame = new LaunchAccountProfile { Id = "other", AccountName = "SilentKelpie" };
|
||||
var conquest = new LaunchAccountProfile { Id = "new", AccountName = "SK", CharacterName = LaunchAccountProfile.NoneOption };
|
||||
var all = new List<LaunchAccountProfile> { withPw, noPwSame, conquest };
|
||||
|
||||
Check(FirstLoginRules.KnownAccountNames(all, "new").SequenceEqual(new[] { "silentkelpie" }),
|
||||
"known names: the others, distinct ignoring case, not this profile's own");
|
||||
|
||||
Check(FirstLoginRules.SavedPasswordSource(all, "SILENTKELPIE", "new")?.Id == "ilt",
|
||||
"the same name with a saved password can be reused (case ignored)");
|
||||
Check(FirstLoginRules.SavedPasswordSource(all, "SK", "new") == null, "a new name has none to reuse");
|
||||
Check(FirstLoginRules.SavedPasswordSource(all, "silentkelpie", "ilt") == null, "never the profile itself");
|
||||
|
||||
var copy = new LaunchAccountProfile { AccountName = "silentkelpie" };
|
||||
copy.CopyPasswordFrom(withPw);
|
||||
Check(copy.PasswordProtected == withPw.PasswordProtected && copy.TryGetPasswordForLaunch(out string reused, out _) && reused == Pw,
|
||||
"reuse copies the encrypted blob, and it decrypts");
|
||||
|
||||
var none = new List<string>();
|
||||
List<string> firstChoices = FirstLoginRules.LoginChoices(none, conquest.CharacterName);
|
||||
Check(firstChoices.SequenceEqual(new[] { FirstLoginRules.StopAtCharacterSelect }),
|
||||
"no characters yet: only stop at character select (the old (None) isn't listed)");
|
||||
Check(FirstLoginRules.CharacterNameFor(FirstLoginRules.StopAtCharacterSelect, none) == "",
|
||||
"stop with none known saves \"\" so the first character created is picked next time");
|
||||
|
||||
var chars = new List<string> { "Alpha", "Beta" };
|
||||
Check(FirstLoginRules.LoginChoices(chars, "Gamma").SequenceEqual(new[] { FirstLoginRules.StopAtCharacterSelect, "Gamma", "Alpha", "Beta" }),
|
||||
"several characters: all listed, the saved one kept even if not seen yet");
|
||||
Check(FirstLoginRules.CharacterNameFor("Beta", chars) == "Beta", "picking a character saves it");
|
||||
Check(FirstLoginRules.CharacterNameFor(FirstLoginRules.StopAtCharacterSelect, chars) == LaunchAccountProfile.NoneOption,
|
||||
"stop with characters known saves the explicit (None)");
|
||||
|
||||
Check(FirstLoginRules.Problem("SK", "", "", false, AcEmulatorKind.Ace)?.StartsWith("Enter the password") == true, "a password is required");
|
||||
Check(FirstLoginRules.Problem("SK", "a", "b", false, AcEmulatorKind.Ace)?.Contains("don't match") == true, "the confirmation must match");
|
||||
Check(FirstLoginRules.Problem("SK", "pw", "pw", false, AcEmulatorKind.Ace) == null, "name + matching password: ready");
|
||||
Check(FirstLoginRules.Problem("silentkelpie", "", "", true, AcEmulatorKind.Ace) == null, "reusing a saved password needs no typing");
|
||||
Check(FirstLoginRules.Problem("a:b", "pw", "pw", false, AcEmulatorKind.Gdle) != null, "GDLE name with a colon refused");
|
||||
Check(FirstLoginRules.Problem("", "pw", "pw", false, AcEmulatorKind.Ace) != null, "a name is required");
|
||||
});
|
||||
|
||||
// A saved UserPreferences.ini whose display mode the PC can't use made every launch
|
||||
// fail with "Could not initialize Direct3D"; a quick exit must undo that swap.
|
||||
Scenario("prefs swap: did the swap change the live file", root, () =>
|
||||
{
|
||||
byte[] a = "[Display]\nResolution=2560x1440\n"u8.ToArray();
|
||||
byte[] b = "[Display]\nResolution=1920x1080\n"u8.ToArray();
|
||||
Check(!UserPrefsSwapRecovery.SwapChangedPrefs(new UserPrefsSwap("s", "l", a, (byte[])a.Clone())), "same bytes: not the cause");
|
||||
Check(UserPrefsSwapRecovery.SwapChangedPrefs(new UserPrefsSwap("s", "l", a, b)), "different bytes: changed");
|
||||
Check(UserPrefsSwapRecovery.SwapChangedPrefs(new UserPrefsSwap("s", "l", a, null)), "no live file before: changed");
|
||||
});
|
||||
|
||||
Scenario("prefs swap: failed stash set aside, live file put back", root, () =>
|
||||
{
|
||||
var (swap, legacy) = PrefsSwapFiles(legacyMatches: true);
|
||||
var now = new DateTime(2026, 10, 14, 16, 30, 5);
|
||||
UserPrefsRecoveryResult r = UserPrefsSwapRecovery.Recover(swap, quarantineStash: true, restoreLive: true, legacy, now);
|
||||
Check(!File.Exists(swap.StashPath), "stash no longer swappable");
|
||||
Check(r.QuarantinedStashPath == swap.StashPath + ".failed-20261014-163005" && File.Exists(r.QuarantinedStashPath), "stash kept as .failed-<time>");
|
||||
Check(!File.Exists(legacy) && r.QuarantinedLegacyPath != null, "identical name-only stash set aside too (it would re-seed)");
|
||||
Check(r.LiveRestored && File.ReadAllBytes(swap.LivePath).SequenceEqual(swap.PreviousLiveBytes!), "live file back to its pre-swap bytes");
|
||||
});
|
||||
|
||||
Scenario("prefs swap: different name-only stash kept", root, () =>
|
||||
{
|
||||
var (swap, legacy) = PrefsSwapFiles(legacyMatches: false);
|
||||
UserPrefsRecoveryResult r = UserPrefsSwapRecovery.Recover(swap, true, true, legacy, DateTime.Now);
|
||||
Check(File.Exists(legacy) && r.QuarantinedLegacyPath == null, "name-only stash with other settings left alone");
|
||||
});
|
||||
|
||||
Scenario("prefs swap: later swap or profile override", root, () =>
|
||||
{
|
||||
var (swap, legacy) = PrefsSwapFiles(legacyMatches: true);
|
||||
File.WriteAllText(swap.LivePath, "another account's settings");
|
||||
UserPrefsRecoveryResult r = UserPrefsSwapRecovery.Recover(swap, quarantineStash: false, restoreLive: false, legacy, DateTime.Now);
|
||||
Check(File.Exists(swap.StashPath) && File.Exists(legacy), "override: the user's file is never renamed");
|
||||
Check(!r.LiveRestored && File.ReadAllText(swap.LivePath) == "another account's settings", "later swap: live file untouched");
|
||||
});
|
||||
|
||||
Scenario("prefs swap: no live file before", root, () =>
|
||||
{
|
||||
var (swap, _) = PrefsSwapFiles(legacyMatches: false);
|
||||
swap = swap with { PreviousLiveBytes = null };
|
||||
UserPrefsSwapRecovery.Recover(swap, true, true, null, DateTime.Now);
|
||||
Check(!File.Exists(swap.LivePath), "live file removed so the game writes its defaults");
|
||||
});
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
|
@ -316,6 +419,23 @@ internal static class Program
|
|||
|
||||
private static InjectionMode Mode(AppSettings s, string id) => s.AccountProfiles.First(a => a.Id == id).InjectionMode;
|
||||
|
||||
/// <summary>
|
||||
/// A swap as the launcher leaves it: the failed per-server stash copied over the live file,
|
||||
/// plus the account's name-only stash (same bytes when <paramref name="legacyMatches"/>).
|
||||
/// </summary>
|
||||
private static (UserPrefsSwap Swap, string LegacyPath) PrefsSwapFiles(bool legacyMatches)
|
||||
{
|
||||
string stash = Path.Combine(_dir, "SK@Conquest.ini");
|
||||
string legacy = Path.Combine(_dir, "SK.ini");
|
||||
string live = Path.Combine(_dir, "UserPreferences.ini");
|
||||
byte[] bad = "[Display]\nResolution=2560x1440\nWindowed=False\n"u8.ToArray();
|
||||
byte[] good = "[Display]\nResolution=1920x1080\nWindowed=True\n"u8.ToArray();
|
||||
File.WriteAllBytes(stash, bad);
|
||||
File.WriteAllBytes(legacy, legacyMatches ? bad : good);
|
||||
File.WriteAllBytes(live, bad);
|
||||
return (new UserPrefsSwap(stash, live, bad, good), legacy);
|
||||
}
|
||||
|
||||
private static void CheckSharedFilesSafe()
|
||||
{
|
||||
foreach (string path in new[] { Main_, Bak })
|
||||
|
|
@ -382,6 +502,13 @@ internal static class Program
|
|||
Id = "s", Name = "Test", Host = "127.0.0.1", Port = 9000, Emulator = kind
|
||||
};
|
||||
|
||||
/// <summary>The message <paramref name="action"/> throws ("" when it doesn't throw).</summary>
|
||||
private static string Throws(Action action)
|
||||
{
|
||||
try { action(); return string.Empty; }
|
||||
catch (Exception ex) { return ex.Message; }
|
||||
}
|
||||
|
||||
private static string PwOf(AppSettings s, string id) =>
|
||||
s.AccountProfiles.First(a => a.Id == id).TryGetPasswordForLaunch(out string pw, out _) ? pw : "<unreadable>";
|
||||
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@
|
|||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.cs" Link="Linked\RynthUpdater.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.MapPacks.cs" Link="Linked\RynthUpdater.MapPacks.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.NavData.cs" Link="Linked\RynthUpdater.NavData.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.Available.cs" Link="Linked\RynthUpdater.Available.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.App.Avalonia\DownloadProgress.cs" Link="Linked\DownloadProgress.cs" />
|
||||
|
|
|
|||
|
|
@ -36,6 +36,7 @@
|
|||
<Compile Include="..\..\src\RynthCore.Engine\Net\ServerMessageInterest.cs" Link="Engine\ServerMessageInterest.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Net\InventoryOrder.cs" Link="Engine\InventoryOrder.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Net\AelrynthVaultWire.cs" Link="Engine\AelrynthVaultWire.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Net\ChatOrigin.cs" Link="Engine\ChatOrigin.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -33,6 +33,18 @@ internal static unsafe partial class Program
|
|||
Check(!AelrynthVaultWire.TryParse("~ael1 {\"t\":\"mule\",\"ready\":tru", out _), "damaged JSON is refused");
|
||||
Check(AelrynthVaultWire.IsUnknownCommand("Unknown command: mule-data"), "ACE's reply for a missing command");
|
||||
Check(!AelrynthVaultWire.IsUnknownCommand("Unknown command: mastery-data"), "another command's reply is not ours");
|
||||
|
||||
Case("vault wire: a player's copy of a server line is not ours");
|
||||
Check(!AelrynthVaultWire.IsMuleLine("Bob says, \"" + page + "\""), "spoken data line");
|
||||
Check(!AelrynthVaultWire.IsMuleLine("Bob " + page), "emoted data line (no quote)");
|
||||
Check(!AelrynthVaultWire.TryParse("[Allegiance] Bob says, \"" + page + "\"", out _), "a channel's copy does not parse");
|
||||
Check(AelrynthVaultWire.IsMuleLine(" " + page), "leading whitespace is fine");
|
||||
Check(AelrynthVaultWire.TryParse(" " + page, out _), "and parses");
|
||||
Check(!AelrynthVaultWire.IsUnknownCommand("Bob tells you, \"Unknown command: mule-data\""), "a told refusal");
|
||||
Check(!AelrynthVaultWire.IsUnknownCommand("Unknown command: mule-data-extra"), "a longer command name");
|
||||
Check(AelrynthVaultWire.IsUnknownCommand("Unknown command: /mule-data"), "a slash before the name is allowed");
|
||||
Check(ChatOrigin.IsPlayerAuthored(ChatOrigin.Emote) && ChatOrigin.IsPlayerAuthored(ChatOrigin.Tell), "emotes and tells are players'");
|
||||
Check(!ChatOrigin.IsPlayerAuthored(0) && !ChatOrigin.IsPlayerAuthored(0x0F), "Broadcast and Help (ACE's replies) are not");
|
||||
Eq(AelrynthVaultWire.PageCommand(1), "@mule-data", "first page is the bare command");
|
||||
Eq(AelrynthVaultWire.PageCommand(3), "@mule-data 3", "later pages say which");
|
||||
|
||||
|
|
|
|||
|
|
@ -50,6 +50,12 @@ internal static class Program
|
|||
Run(nameof(ReadsResourceFromPe32AndPe32Plus), ReadsResourceFromPe32AndPe32Plus);
|
||||
Run(nameof(NoResourceAndNotAPe), NoResourceAndNotAPe);
|
||||
Run(nameof(GatePlanFromFiles), GatePlanFromFiles);
|
||||
Run(nameof(ServerBlockParsesAndRoundTrips), ServerBlockParsesAndRoundTrips);
|
||||
Run(nameof(ServerBlockRejectsBadIds), ServerBlockRejectsBadIds);
|
||||
Run(nameof(ServerHostMatching), ServerHostMatching);
|
||||
Run(nameof(ServerGateKeepsOnlyTheHostsPlugin), ServerGateKeepsOnlyTheHostsPlugin);
|
||||
Run(nameof(ServerGateUnclaimedHost), ServerGateUnclaimedHost);
|
||||
Run(nameof(ServerGatePlanFromFiles), ServerGatePlanFromFiles);
|
||||
Run(nameof(SdkApiVersionCannotDrift), SdkApiVersionCannotDrift);
|
||||
Run(nameof(TrainingStructsMirror), TrainingStructsMirror);
|
||||
Run(nameof(ContainerOrderSlots), ContainerOrderSlots);
|
||||
|
|
@ -441,6 +447,117 @@ internal static class Program
|
|||
Check(none.Log.Any(l => l.Contains("no plugin has a manifest")), "said once");
|
||||
}
|
||||
|
||||
// ── Server plugins (the manifest's "server" block and the load gate) ────
|
||||
|
||||
private static RynthPluginManifest S(string name, string id, string[] hosts, params string[] worlds)
|
||||
{
|
||||
var m = M(name);
|
||||
m.Server = new RynthPluginServer { Id = id, Name = name, Hosts = hosts.ToList(), WorldNames = worlds.ToList() };
|
||||
return m;
|
||||
}
|
||||
|
||||
private static void ServerBlockParsesAndRoundTrips()
|
||||
{
|
||||
var m = RynthPluginManifest.Parse("""
|
||||
{ "name": "RynthColdeve", "minEngineApi": 66,
|
||||
"server": { "id": "Coldeve", "name": "Coldeve", "hosts": ["play.coldeve.ac", "", 5], "worldNames": ["Coldeve"] } }
|
||||
""");
|
||||
Check(m.Server != null, "server block read");
|
||||
Eq(m.Server!.Id, "coldeve", "id lower-cased");
|
||||
Eq(string.Join(",", m.Server.Hosts), "play.coldeve.ac", "blank and non-string hosts dropped");
|
||||
Eq(string.Join(",", m.Server.WorldNames), "Coldeve", "world names");
|
||||
var back = RynthPluginManifest.Parse(m.ToJson());
|
||||
Eq(back.Server?.Id, "coldeve", "round trip id");
|
||||
Eq(back.Server?.Hosts.Count, 1, "round trip hosts");
|
||||
Check(RynthPluginManifest.Parse("""{ "name": "RynthAi" }""").Server == null, "no block, not a server plugin");
|
||||
Check(!M("RynthAi").ToJson().Contains("\"server\""), "no server block written for other plugins");
|
||||
}
|
||||
|
||||
private static void ServerBlockRejectsBadIds()
|
||||
{
|
||||
string[] bad =
|
||||
{
|
||||
"""{ "name": "X", "server": "coldeve" }""",
|
||||
"""{ "name": "X", "server": { "name": "No id" } }""",
|
||||
"""{ "name": "X", "server": { "id": "has space" } }""",
|
||||
"""{ "name": "X", "server": { "id": "ok", "hosts": "not-an-array" } }""",
|
||||
};
|
||||
foreach (string json in bad)
|
||||
Check(RynthPluginManifest.TryParse(json, out string err) == null && err.Length > 0, $"refused: {json}");
|
||||
}
|
||||
|
||||
private static void ServerHostMatching()
|
||||
{
|
||||
var ilt = new RynthPluginServer { Id = "ilt", Hosts = { "infiniteleaftide.online" } };
|
||||
Check(ilt.MatchesHost("game.infiniteleaftide.online", out string hit) && hit == "infiniteleaftide.online", "a host under the name");
|
||||
Check(ilt.MatchesHost("INFINITELEAFTIDE.ONLINE.", out _), "case and trailing dot ignored");
|
||||
Check(!ilt.MatchesHost("notinfiniteleaftide.online", out _), "not a suffix without the dot");
|
||||
var ip = new RynthPluginServer { Id = "aelrynth", Hosts = { "144.217.84.148" } };
|
||||
Check(ip.MatchesHost("144.217.84.148", out _), "an IP matches itself");
|
||||
Check(!ip.MatchesHost("1.144.217.84.148", out _), "an IP never matches as a suffix");
|
||||
var wild = new RynthPluginServer { Id = "x", Hosts = { "*.ddns.net" } };
|
||||
Check(wild.MatchesHost("frostcull.ddns.net", out _), "wildcard");
|
||||
Check(!wild.MatchesHost("", out _), "no host, no match");
|
||||
}
|
||||
|
||||
private static void ServerGateKeepsOnlyTheHostsPlugin()
|
||||
{
|
||||
var list = new List<PluginCandidate>
|
||||
{
|
||||
C("RynthAi", M("RynthAi")),
|
||||
C("RynthChat"),
|
||||
C("RynthColdeve", S("RynthColdeve", "coldeve", new[] { "play.coldeve.ac" }, "Coldeve")),
|
||||
C("RynthLeafDawn", S("RynthLeafDawn", "leafdawn", new[] { "leafdawn.hopto.org" }, "LeafDawn")),
|
||||
C("RynthLeafdawning", S("RynthLeafdawning", "leafdawning", new[] { "leafdawning.duckdns.org" }, "Leafdawning")),
|
||||
};
|
||||
var log = new List<string>();
|
||||
HashSet<string> skip = PluginManifestGate.SelectServerPlugins(list, "leafdawn.hopto.org", false, log);
|
||||
Eq(skip.Count, 2, "the two other server plugins are left out");
|
||||
Check(skip.Contains(list[2].Key) && skip.Contains(list[4].Key), "Coldeve and Leafdawning left out");
|
||||
Check(!skip.Contains(list[0].Key) && !skip.Contains(list[1].Key), "other plugins always load");
|
||||
Check(log.Any(l => l.Contains("RynthColdeve") && l.Contains("not loaded")), "logged why");
|
||||
Eq(PluginManifestGate.SelectServerPlugins(list, "leafdawn.hopto.org", true, log).Count, 0, "LoadAllServerPlugins keeps every one");
|
||||
}
|
||||
|
||||
private static void ServerGateUnclaimedHost()
|
||||
{
|
||||
var list = new List<PluginCandidate>
|
||||
{
|
||||
C("RynthColdeve", S("RynthColdeve", "coldeve", new[] { "play.coldeve.ac" })),
|
||||
C("RynthFrostcull", S("RynthFrostcull", "frostcull", new[] { "frostcull.ddns.net" })),
|
||||
};
|
||||
var log = new List<string>();
|
||||
Eq(PluginManifestGate.SelectServerPlugins(list, "", false, log).Count, 0, "no connect host: all load");
|
||||
Eq(PluginManifestGate.SelectServerPlugins(list, "10.0.0.5", false, log).Count, 2, "a host nobody lists: none load now (late load by world name or a pick)");
|
||||
Check(log.Any(l => l.Contains("none lists host 10.0.0.5")), "said why");
|
||||
}
|
||||
|
||||
private static void ServerGatePlanFromFiles()
|
||||
{
|
||||
string dir = Path.Combine(_root, "servers");
|
||||
Directory.CreateDirectory(dir);
|
||||
string P(string name) => Path.Combine(dir, $"RynthCore.Plugin.{name}.dll");
|
||||
File.Copy(ThisDll, P("RynthAi"));
|
||||
Embed(P("RynthAi"), M("RynthAi").ToJson());
|
||||
File.Copy(ThisDll, P("RynthILT"));
|
||||
Embed(P("RynthILT"), S("RynthILT", "ilt", new[] { "infiniteleaftide.online" }, "*Leaftide*").ToJson());
|
||||
File.Copy(ThisDll, P("RynthAelrynth"));
|
||||
Embed(P("RynthAelrynth"), S("RynthAelrynth", "aelrynth", new[] { "144.217.84.148" }, "Aelrynth*").ToJson());
|
||||
|
||||
var paths = new[] { P("RynthAi"), P("RynthILT"), P("RynthAelrynth") };
|
||||
PluginManifestGate.LoadPlan onIlt = PluginManifestGate.Plan(paths, Api, null, "game.infiniteleaftide.online");
|
||||
Eq(string.Join(",", onIlt.Load.Select(l => RynthPluginManifest.NameFromFile(l.Path))), "RynthAi,RynthILT", "on ILT");
|
||||
Eq(onIlt.SkippedForServer.Count, 1, "Aelrynth's plugin skipped");
|
||||
// The skipped one keeps its manifest: Options > Diagnostics lists its server, and forcing it loads it.
|
||||
Eq(onIlt.SkippedServerPlugins.Count, 1, "skipped server plugin kept with its manifest");
|
||||
Eq(onIlt.SkippedServerPlugins[0].Manifest.Server?.Id ?? "", "aelrynth", "its server id");
|
||||
Eq(onIlt.SkippedServerPlugins[0].Path, P("RynthAelrynth"), "its path");
|
||||
Eq(onIlt.Refused.Count, 0, "skipping is not a refusal (no chat notice)");
|
||||
Check(onIlt.Log.Any(l => l.Contains("server ilt")), "the manifest line names the server");
|
||||
PluginManifestGate.LoadPlan onAelrynth = PluginManifestGate.Plan(paths, Api, null, "144.217.84.148");
|
||||
Eq(string.Join(",", onAelrynth.Load.Select(l => RynthPluginManifest.NameFromFile(l.Path))), "RynthAi,RynthAelrynth", "on Aelrynth");
|
||||
}
|
||||
|
||||
// ── The SDK's version ────────────────────────────────────────────────────
|
||||
|
||||
private static void SdkApiVersionCannotDrift()
|
||||
|
|
@ -474,11 +591,11 @@ internal static class Program
|
|||
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.TrainingEntryNative>(f.Name), (int)Marshal.OffsetOf<RynthCore.Engine.Plugins.TrainingEntryNative>(f.Name), "TrainingEntryNative." + f.Name + " offset");
|
||||
Eq(RynthCore.PluginSdk.TrainingInfoFlags.Busy, RynthCore.Engine.Plugins.TrainingInfoFlags.Busy, "info flag bits");
|
||||
Eq(RynthCore.PluginSdk.TrainingEntryFlags.Trainable, RynthCore.Engine.Plugins.TrainingEntryFlags.Trainable, "entry flag bits");
|
||||
// The three v79 slots follow v78's, then v80's two and v81's GetMergeStackResultFn (v82-v84 follow).
|
||||
var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(4).TakeLast(6).ToArray();
|
||||
// The three v79 slots follow v78's, then v80's two and v81's GetMergeStackResultFn (v82-v85 follow).
|
||||
var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(7).TakeLast(6).ToArray();
|
||||
Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn", "GetContainerOrderFn", "PutItemInContainerFn", "GetMergeStackResultFn" }),
|
||||
"v79, v80 then v81 slots last: " + string.Join(",", names));
|
||||
var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(4).TakeLast(6).ToArray();
|
||||
var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(7).TakeLast(6).ToArray();
|
||||
Check(sdkNames.SequenceEqual(names), "SDK v79, v80 and v81 slots in the same order");
|
||||
}
|
||||
|
||||
|
|
@ -490,13 +607,17 @@ internal static class Program
|
|||
var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).ToArray();
|
||||
var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).ToArray();
|
||||
// v81's GetMergeStackResultFn follows v80's two slots.
|
||||
Check(names.SkipLast(5).TakeLast(2).SequenceEqual(new[] { "GetContainerOrderFn", "PutItemInContainerFn" }), "v80 slots before v81's to v84's: " + string.Join(",", names.SkipLast(5).TakeLast(2)));
|
||||
Check(sdkNames.SkipLast(5).TakeLast(2).SequenceEqual(names.SkipLast(5).TakeLast(2)), "SDK v80 slots in the same order");
|
||||
Check(names.SkipLast(3).Last() == "SalvageDirectFn", "v82 slot before v83's");
|
||||
Check(names.SkipLast(8).TakeLast(2).SequenceEqual(new[] { "GetContainerOrderFn", "PutItemInContainerFn" }), "v80 slots before v81's to v85's: " + string.Join(",", names.SkipLast(8).TakeLast(2)));
|
||||
Check(sdkNames.SkipLast(8).TakeLast(2).SequenceEqual(names.SkipLast(8).TakeLast(2)), "SDK v80 slots in the same order");
|
||||
Check(names.SkipLast(6).Last() == "SalvageDirectFn", "v82 slot before v83's");
|
||||
// v83: GetObjectServerAge and RemoveClientObject (ghost creatures), then v84's slot.
|
||||
Check(names.SkipLast(1).TakeLast(2).SequenceEqual(new[] { "GetObjectServerAgeFn", "RemoveClientObjectFn" }), "v83 slots before v84's: " + string.Join(",", names.SkipLast(1).TakeLast(2)));
|
||||
// v84: GetObjectProperties ends the table (every property of an object, /ub propertydump).
|
||||
Check(names.Last() == "GetObjectPropertiesFn", "v84 slot last: " + names.Last());
|
||||
Check(names.SkipLast(4).TakeLast(2).SequenceEqual(new[] { "GetObjectServerAgeFn", "RemoveClientObjectFn" }), "v83 slots before v84's: " + string.Join(",", names.SkipLast(4).TakeLast(2)));
|
||||
// v84: GetObjectProperties (every property of an object, /ub propertydump), then v85's two.
|
||||
Check(names.SkipLast(3).Last() == "GetObjectPropertiesFn", "v84 slot before v85's: " + names.SkipLast(3).Last());
|
||||
// v85: ArmConfirmation and GetLastConfirmation (the server's yes/no prompts), then v86's slot.
|
||||
Check(names.SkipLast(1).TakeLast(2).SequenceEqual(new[] { "ArmConfirmationFn", "GetLastConfirmationFn" }), "v85 slots before v86's: " + string.Join(",", names.SkipLast(1).TakeLast(2)));
|
||||
// v86: GetServerStateJson ends the table (which server this is, for every plugin).
|
||||
Check(names.Last() == "GetServerStateJsonFn", "v86 slot last: " + names.Last());
|
||||
Check(typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SequenceEqual(typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name)), "SDK table has the engine's slots in the same order");
|
||||
Eq(Marshal.SizeOf<RynthCore.PluginSdk.RynthCoreApiNative>(), Marshal.SizeOf<RynthCore.Engine.Plugins.RynthCoreAPI>(), "SDK table size = engine table size");
|
||||
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>("PutItemInContainerFn"),
|
||||
|
|
@ -511,6 +632,14 @@ internal static class Program
|
|||
(int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("GetObjectPropertiesFn"), "GetObjectPropertiesFn offset");
|
||||
Eq((int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("GetObjectPropertiesFn"),
|
||||
(int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("RemoveClientObjectFn") + IntPtr.Size, "GetObjectPropertiesFn right after RemoveClientObjectFn");
|
||||
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>("ArmConfirmationFn"),
|
||||
(int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("ArmConfirmationFn"), "ArmConfirmationFn offset");
|
||||
Eq((int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("ArmConfirmationFn"),
|
||||
(int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("GetObjectPropertiesFn") + IntPtr.Size, "ArmConfirmationFn right after GetObjectPropertiesFn");
|
||||
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>("GetLastConfirmationFn"),
|
||||
(int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("GetLastConfirmationFn"), "GetLastConfirmationFn offset");
|
||||
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>("GetServerStateJsonFn"),
|
||||
(int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("GetServerStateJsonFn"), "GetServerStateJsonFn offset");
|
||||
}
|
||||
|
||||
private sealed class ProbePlugin : RynthCore.PluginCore.RynthPluginBase { }
|
||||
|
|
|
|||
452
tools/SectionsTests/Program.cs
Normal file
452
tools/SectionsTests/Program.cs
Normal file
|
|
@ -0,0 +1,452 @@
|
|||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.UI.Sections;
|
||||
|
||||
namespace SectionsTests;
|
||||
|
||||
/// <summary>
|
||||
/// The Mini Remote's sections, offline: per-character server overrides (server_force.txt),
|
||||
/// plugin manifests (RynthPluginGetSectionsJson) and the section catalog built from them.
|
||||
/// </summary>
|
||||
internal static class Program
|
||||
{
|
||||
private static int _checks, _failed;
|
||||
private static string _case = "";
|
||||
|
||||
private static int Main()
|
||||
{
|
||||
ForceText();
|
||||
ForceFile();
|
||||
ManifestBasics();
|
||||
ManifestRejects();
|
||||
ManifestLimits();
|
||||
CatalogCore();
|
||||
CatalogServers();
|
||||
CatalogPluginSections();
|
||||
DeclaredServers();
|
||||
SelectionPlan();
|
||||
NotLoadedServerList();
|
||||
SelectionCurrentPick();
|
||||
SelectionActiveAndOwner();
|
||||
StateJson();
|
||||
|
||||
Console.WriteLine();
|
||||
Console.WriteLine($"{_checks - _failed}/{_checks} checks passed.");
|
||||
if (_checks == 0) { Console.WriteLine("ABORT: no checks ran."); return 1; }
|
||||
Console.WriteLine(_failed == 0 ? "ALL SECTIONS TESTS PASSED." : $"{_failed} FAILED.");
|
||||
return _failed == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
// ── Overrides ──────────────────────────────────────────────────────
|
||||
|
||||
private static void ForceText()
|
||||
{
|
||||
Case("force text");
|
||||
Check(ServerForceText.TryParse("on", out ServerForce m) && m == ServerForce.On, "on");
|
||||
Check(ServerForceText.TryParse(" OFF ", out m) && m == ServerForce.Off, "OFF, padded");
|
||||
Check(ServerForceText.TryParse("auto", out m) && m == ServerForce.Auto, "auto");
|
||||
Check(!ServerForceText.TryParse("maybe", out _) && !ServerForceText.TryParse(null, out _), "junk and null");
|
||||
Check(ServerForceText.Name(ServerForce.On) == "on" && ServerForceText.Name(ServerForce.Auto) == "auto", "names");
|
||||
Check(ServerForceText.Apply(ServerForce.On, false), "On wins over not detected");
|
||||
Check(!ServerForceText.Apply(ServerForce.Off, true), "Off wins over detected");
|
||||
Check(ServerForceText.Apply(ServerForce.Auto, true) && !ServerForceText.Apply(ServerForce.Auto, false), "Auto follows detection");
|
||||
}
|
||||
|
||||
private static void ForceFile()
|
||||
{
|
||||
Case("force file");
|
||||
var f = new ServerForceFile();
|
||||
Check(f.Set("Kelpie@ILT", "ilt", ServerForce.On), "set on");
|
||||
Check(!f.Set("Kelpie@ILT", "ilt", ServerForce.On), "same value again is no change");
|
||||
Check(f.Get("kelpie@ilt", "ILT") == ServerForce.On, "keys are case-insensitive");
|
||||
Check(f.Get("Other", "ilt") == ServerForce.Auto, "another character is Auto");
|
||||
Check(f.Set("Kelpie@ILT", "aelrynth", ServerForce.Off), "a second server");
|
||||
Check(f.For("Kelpie@ILT").Count == 2, "For lists both");
|
||||
|
||||
var round = ServerForceFile.Parse(f.Write().Split('\n'));
|
||||
Check(round.Get("Kelpie@ILT", "ilt") == ServerForce.On && round.Get("Kelpie@ILT", "aelrynth") == ServerForce.Off, "round trip");
|
||||
|
||||
Check(f.Set("Kelpie@ILT", "ilt", ServerForce.Auto) && f.Get("Kelpie@ILT", "ilt") == ServerForce.Auto, "Auto removes");
|
||||
Check(!f.Set("Kelpie@ILT", "ilt", ServerForce.Auto), "removing again is no change");
|
||||
Check(!f.Set("bad\tkey", "ilt", ServerForce.On) && !f.Set("k", "a\nb", ServerForce.On), "tabs and line breaks refused");
|
||||
Check(!f.Set(new string('x', ServerForceFile.MaxFieldLength + 1), "ilt", ServerForce.On), "overlong key refused");
|
||||
Check(!f.Set("", "ilt", ServerForce.On) && !f.Set("k", " ", ServerForce.On), "empty fields refused");
|
||||
|
||||
var damaged = ServerForceFile.Parse(new[] { "# comment", "", "a\tilt", "a\tilt\tmaybe", "a\tilt\tauto", "b\tilt\ton\textra" });
|
||||
Check(damaged.For("a").Count == 0, "short, unknown and auto lines are skipped");
|
||||
Check(damaged.Get("b", "ilt") == ServerForce.On, "extra fields are ignored");
|
||||
Check(ServerForceFile.Parse(null).For("a").Count == 0, "no file");
|
||||
}
|
||||
|
||||
// ── Manifests ──────────────────────────────────────────────────────
|
||||
|
||||
private const string GoodManifest = """
|
||||
{
|
||||
"version": 1,
|
||||
"servers": [ { "id": "ilt", "name": "Infinite Leaftide", "worldNames": ["*Leaftide*"], "hosts": ["infiniteleaftide.online"] },
|
||||
{ "id": "Frost-Haven", "name": "Frosthaven", "worldNames": ["Frosthaven"], "hosts": [] } ],
|
||||
"sections": [ { "id": "quests", "label": "Quests", "order": 650 } ],
|
||||
"contributions": [
|
||||
{ "section": "pets", "server": "", "label": "Pets", "surface": "section:pets", "primary": true, "width": 560, "height": 580 },
|
||||
{ "section": "skills", "server": "ilt", "label": "Progression", "command": "/rc progression", "tooltip": "line one\nline two" },
|
||||
{ "section": "quests", "label": "Quests", "surface": "section:quests", "primary": true },
|
||||
{ "section": "char", "server": "ilt", "label": "Off now", "command": "/ra x", "enabled": false, "note": "Not reported." }
|
||||
],
|
||||
"future": { "ignored": true }
|
||||
}
|
||||
""";
|
||||
|
||||
private static void ManifestBasics()
|
||||
{
|
||||
Case("manifest basics");
|
||||
SectionManifest m = SectionManifestParser.Parse("RynthAi", GoodManifest, out string err);
|
||||
Check(err.Length == 0, "no error: " + err);
|
||||
Check(m.Plugin == "RynthAi", "plugin name kept");
|
||||
Check(m.Servers.Length == 2 && m.Servers[1].Id == "frost-haven", "server ids lower-cased");
|
||||
Check(m.Servers[0].WorldNames.SequenceEqual(new[] { "*Leaftide*" }) && m.Servers[0].Hosts.Length == 1, "server lists");
|
||||
Check(m.Sections.Length == 1 && m.Sections[0].Order == 650, "a plugin section with its order");
|
||||
Check(m.Contributions.Length == 4, "four contributions");
|
||||
SectionContribution pets = m.Contributions[0];
|
||||
Check(pets.IsSurface && pets.IsUniversal && pets.Primary && pets.Width == 560 && pets.Height == 580, "surface fields");
|
||||
SectionContribution prog = m.Contributions[1];
|
||||
Check(!prog.IsSurface && prog.Command == "/rc progression" && prog.Server == "ilt" && prog.Enabled, "command fields");
|
||||
Check(prog.Tooltip.Contains('\n'), "tooltips keep line breaks");
|
||||
Check(m.Contributions[2].Order == 1000, "order defaults to 1000");
|
||||
Check(!m.Contributions[3].Enabled && m.Contributions[3].Note == "Not reported.", "disabled with a note");
|
||||
}
|
||||
|
||||
private static void ManifestRejects()
|
||||
{
|
||||
Case("manifest rejects");
|
||||
Check(SectionManifestParser.Parse("p", null, out string e).Contributions.Length == 0 && e == "empty", "null");
|
||||
Check(SectionManifestParser.Parse("p", "[1,2]", out e).Contributions.Length == 0 && e.Length > 0, "not an object");
|
||||
Check(SectionManifestParser.Parse("p", "{ bad", out e).Contributions.Length == 0 && e.StartsWith("bad JSON"), "bad JSON");
|
||||
Check(SectionManifestParser.Parse("p", """{"version":0}""", out e).Contributions.Length == 0 && e.Length > 0, "version 0");
|
||||
|
||||
string deep = new string('[', 40) + new string(']', 40);
|
||||
Check(SectionManifestParser.Parse("p", "{\"x\":" + deep + "}", out e).Contributions.Length == 0 && e.Length > 0, "too deep");
|
||||
|
||||
SectionManifest m = SectionManifestParser.Parse("p", """
|
||||
{ "contributions": [
|
||||
{ "section": "Bad Id!", "label": "x", "command": "/a" },
|
||||
{ "section": "char", "label": "", "command": "/a" },
|
||||
{ "section": "char", "label": "no action" },
|
||||
{ "section": "char", "label": "not a command", "command": "say hi" },
|
||||
{ "section": "char", "label": "two lines", "command": "/a\n/b" },
|
||||
{ "section": "char", "label": "popout", "surface": "x:popout" },
|
||||
{ "section": "char", "label": "odd surface", "surface": "a b" },
|
||||
{ "section": "char", "label": "bad server", "server": "no way", "command": "/a" },
|
||||
{ "section": "char", "label": "Line\nbreak", "command": "/ok", "width": -5, "height": 99999 }
|
||||
] }
|
||||
""", out e);
|
||||
Check(e.Length == 0, "entries are skipped, not the manifest");
|
||||
Check(m.Contributions.Length == 1, "only the good entry survives");
|
||||
SectionContribution c = m.Contributions.Single();
|
||||
Check(c.Label == "Line break", "labels lose line breaks");
|
||||
Check(c.Width == 0 && c.Height == SectionManifestParser.MaxSurfaceSize, "sizes clamped");
|
||||
|
||||
Check(SectionManifestParser.Id("ab_c-1") == "ab_c-1" && SectionManifestParser.Id("A B") == "", "ids");
|
||||
Check(SectionManifestParser.Id(new string('a', SectionManifestParser.MaxIdLength + 1)) == "", "long ids");
|
||||
Check(SectionManifestParser.Command("/x") == "/x" && SectionManifestParser.Command("/") == "", "commands");
|
||||
Check(SectionManifestParser.Surface("section:ilt-options") == "section:ilt-options", "a section surface");
|
||||
}
|
||||
|
||||
private static void ManifestLimits()
|
||||
{
|
||||
Case("manifest limits");
|
||||
var items = string.Join(",", Enumerable.Range(0, 300).Select(i => $$"""{"section":"char","label":"L{{i}}","command":"/c {{i}}"}"""));
|
||||
SectionManifest m = SectionManifestParser.Parse("p", "{\"contributions\":[" + items + "]}", out _);
|
||||
Check(m.Contributions.Length == SectionManifestParser.MaxContributions, "contributions capped");
|
||||
|
||||
var servers = string.Join(",", Enumerable.Range(0, 40).Select(i => $$"""{"id":"s{{i}}"}"""));
|
||||
m = SectionManifestParser.Parse("p", "{\"servers\":[" + servers + "]}", out _);
|
||||
Check(m.Servers.Length == SectionManifestParser.MaxServers, "servers capped");
|
||||
|
||||
string big = "{\"x\":\"" + new string('a', SectionManifestParser.MaxJsonLength) + "\"}";
|
||||
Check(SectionManifestParser.Parse("p", big, out string e).Contributions.Length == 0 && e.StartsWith("too large"), "size capped");
|
||||
|
||||
string longLabel = new string('L', 200);
|
||||
m = SectionManifestParser.Parse("p", $$"""{"contributions":[{"section":"char","label":"{{longLabel}}","command":"/a"}]}""", out _);
|
||||
Check(m.Contributions[0].Label.Length == SectionManifestParser.MaxLabelLength, "labels capped");
|
||||
}
|
||||
|
||||
// ── Catalog ────────────────────────────────────────────────────────
|
||||
|
||||
private static readonly ServerState IltOn = new("ilt", "Infinite Leaftide", true, true, ServerForce.Auto, true, "world");
|
||||
private static readonly ServerState IltOff = IltOn with { Active = false, Detected = false };
|
||||
private static readonly ServerState AelOff = new("aelrynth", "Aelrynth", false, false, ServerForce.Auto, true, "");
|
||||
|
||||
private static bool Panels(string title) => title is "Radar" or "Skills" or "Nav" or "Inventory" or "Items" or "Chat";
|
||||
|
||||
private static void CatalogCore()
|
||||
{
|
||||
Case("catalog core");
|
||||
List<SectionView> views = SectionCatalog.Build(Array.Empty<SectionManifest>(), Panels, new[] { IltOff, AelOff });
|
||||
string[] ids = views.Select(v => v.Id).ToArray();
|
||||
Check(ids.SequenceEqual(new[] { "char", "map", "skills", "combat", "nav", "inventory", "crafting", "spells", "chat", "friends", "fellowship", "pets" }),
|
||||
"the twelve core sections, in order: " + string.Join(",", ids));
|
||||
Check(views.All(v => v.Core), "all core");
|
||||
Check(views[0].Panes.Single().Kind == SectionPaneKind.Overview, "Char starts with the overview");
|
||||
Check(views[0].Label == SectionCatalog.SessionStatsLabel && views[0].Label == "Session Stats", "the char section is labelled Session Stats");
|
||||
|
||||
// A plugin's universal primary surface in char (RynthAi's session stats) replaces the overview.
|
||||
var session = SectionManifestParser.Parse("RynthAi", """
|
||||
{ "contributions": [ { "section": "char", "label": "Session stats", "surface": "section:session", "primary": true } ] }
|
||||
""", out _);
|
||||
SectionView chr = SectionCatalog.Build(new[] { session }, Panels, new[] { IltOff }).Single(v => v.Id == "char");
|
||||
Check(chr.Panes.Single().Kind == SectionPaneKind.Surface && chr.Panes[0].Contribution!.Surface == "section:session",
|
||||
"a universal primary surface drops the overview");
|
||||
// A server-scoped primary surface doesn't: the overview stays beside it.
|
||||
var scoped = SectionManifestParser.Parse("p", """
|
||||
{ "contributions": [ { "section": "char", "server": "ilt", "label": "ILT", "surface": "section:ilt", "primary": true } ] }
|
||||
""", out _);
|
||||
chr = SectionCatalog.Build(new[] { scoped }, Panels, new[] { IltOn }).Single(v => v.Id == "char");
|
||||
Check(chr.Panes.Any(p => p.Kind == SectionPaneKind.Overview), "a server-scoped surface keeps the overview");
|
||||
Check(views[1].Panes.Select(p => p.Panel).SequenceEqual(new[] { "Radar" }), "Map has only the panels that exist");
|
||||
Check(views[5].Panes.Select(p => p.Panel).SequenceEqual(new[] { "Inventory", "Items" }), "Inventory keeps panel order");
|
||||
Check(!views[3].HasContent && !views[11].HasContent, "Combat (no panels here) and Pets are empty");
|
||||
Check(SectionCatalog.FindCore("PETS")?.Id == "pets" && SectionCatalog.FindCore("remote") == null, "FindCore");
|
||||
Check(SectionCatalog.Build(Array.Empty<SectionManifest>(), _ => throw new InvalidOperationException(), new[] { IltOff })
|
||||
.All(v => v.Panes.All(p => p.Kind != SectionPaneKind.CorePanel)), "a throwing panel check means no panels");
|
||||
}
|
||||
|
||||
private static void CatalogServers()
|
||||
{
|
||||
Case("catalog servers");
|
||||
SectionManifest m = SectionManifestParser.Parse("RynthAi", GoodManifest, out _);
|
||||
|
||||
List<SectionView> off = SectionCatalog.Build(new[] { m }, Panels, new[] { IltOff, AelOff });
|
||||
SectionView pets = off.Single(v => v.Id == "pets");
|
||||
Check(pets.Panes.Single().Kind == SectionPaneKind.Surface && pets.Panes[0].Contribution!.Surface == "section:pets", "a primary surface is a pane");
|
||||
SectionView skills = off.Single(v => v.Id == "skills");
|
||||
Check(skills.Groups.Length == 0, "ILT items hidden while ILT is off");
|
||||
|
||||
List<SectionView> on = SectionCatalog.Build(new[] { m }, Panels, new[] { IltOn, AelOff });
|
||||
skills = on.Single(v => v.Id == "skills");
|
||||
Check(skills.Groups.Length == 1 && skills.Groups[0].Title == "Server: Infinite Leaftide" && skills.Groups[0].Server == IltOn, "ILT group while active");
|
||||
Check(skills.Groups[0].Items.Single().Command == "/rc progression", "its command");
|
||||
SectionView chr = on.Single(v => v.Id == "char");
|
||||
Check(chr.Groups.Single().Items.Single().Label == "Off now", "disabled items still listed (with their note)");
|
||||
|
||||
var universal = SectionManifestParser.Parse("Other", """
|
||||
{ "contributions": [ { "section": "skills", "label": "Z", "command": "/z", "order": 5 },
|
||||
{ "section": "skills", "label": "A", "command": "/a", "order": 5 } ] }
|
||||
""", out _);
|
||||
skills = SectionCatalog.Build(new[] { m, universal }, Panels, new[] { IltOn }).Single(v => v.Id == "skills");
|
||||
Check(skills.Groups.Select(g => g.Title).SequenceEqual(new[] { "Server: Infinite Leaftide", "Plugins" }), "server groups first, then Plugins");
|
||||
Check(skills.Groups[1].Items.Select(i => i.Label).SequenceEqual(new[] { "A", "Z" }), "equal orders sort by label");
|
||||
}
|
||||
|
||||
private static void CatalogPluginSections()
|
||||
{
|
||||
Case("catalog plugin sections");
|
||||
SectionManifest m = SectionManifestParser.Parse("RynthAi", GoodManifest, out _);
|
||||
List<SectionView> views = SectionCatalog.Build(new[] { m }, Panels, new[] { IltOff });
|
||||
int quests = views.FindIndex(v => v.Id == "quests");
|
||||
Check(quests >= 0 && !views[quests].Core, "the plugin's Quests section shows");
|
||||
Check(views[quests - 1].Id == "crafting" && views[quests + 1].Id == "spells", "order 650 puts it between Crafting (600) and Spells (700)");
|
||||
var empty = SectionManifestParser.Parse("p", """{ "sections": [ { "id": "empty", "label": "Empty" } ] }""", out _);
|
||||
Check(SectionCatalog.Build(new[] { empty }, Panels, new[] { IltOff }).All(v => v.Id != "empty"), "an empty plugin section is hidden");
|
||||
var hijack = SectionManifestParser.Parse("p", """
|
||||
{ "sections": [ { "id": "pets", "label": "Mine" }, { "id": "remote", "label": "Mine" } ],
|
||||
"contributions": [ { "section": "remote", "label": "x", "command": "/x" } ] }
|
||||
""", out _);
|
||||
views = SectionCatalog.Build(new[] { hijack }, Panels, new[] { IltOff });
|
||||
Check(views.Count(v => v.Id == "pets") == 1 && views.Single(v => v.Id == "pets").Label == "Pets", "core ids can't be redeclared");
|
||||
Check(views.All(v => v.Id != "remote"), "the remote id can't be declared");
|
||||
var dup = SectionManifestParser.Parse("q", """
|
||||
{ "sections": [ { "id": "quests", "label": "Other quests", "order": 1 } ],
|
||||
"contributions": [ { "section": "quests", "label": "x", "command": "/x" } ] }
|
||||
""", out _);
|
||||
views = SectionCatalog.Build(new[] { m, dup }, Panels, new[] { IltOff });
|
||||
SectionView q = views.Single(v => v.Id == "quests");
|
||||
Check(q.Label == "Quests" && q.Order == 650, "the first declaration wins");
|
||||
Check(q.Panes.Length == 1 && q.Groups.Single().Items.Single().Plugin == "q", "both plugins' contributions land in it");
|
||||
}
|
||||
|
||||
private static void DeclaredServers()
|
||||
{
|
||||
Case("declared servers");
|
||||
var decl = new SectionServerDecl("frosthaven", "Frosthaven", new[] { "Frosthaven*" }, new[] { "frosthaven.example" });
|
||||
Check(SectionCatalog.DetectDeclared(decl, "play.frosthaven.example", null, out string why) && why.Contains("host"), "by host");
|
||||
Check(SectionCatalog.DetectDeclared(decl, null, "Frosthaven PvE", out why) && why.Contains("world"), "by world name");
|
||||
Check(!SectionCatalog.DetectDeclared(decl, "infiniteleaftide.online", "InfiniteLeaftide", out _), "not another server");
|
||||
var none = new SectionServerDecl("x", "X", Array.Empty<string>(), Array.Empty<string>());
|
||||
Check(!SectionCatalog.DetectDeclared(none, "a", "b", out why) && why.StartsWith("no host or world-name list"), "no lists");
|
||||
}
|
||||
|
||||
// -- Server selection (Diagnostics picker, "/rc server pick", plugin API v86) --
|
||||
|
||||
/// <summary>A server row as SectionRegistry builds it (Active = override applied to detection).</summary>
|
||||
private static ServerState Srv(string id, bool detected, ServerForce force, bool builtIn = false)
|
||||
=> new(id, id.ToUpperInvariant(), ServerForceText.Apply(force, detected), detected, force, builtIn, detected ? "host matches" : "");
|
||||
|
||||
private static void SelectionPlan()
|
||||
{
|
||||
Case("selection plan");
|
||||
var servers = new[] { Srv("ilt", true, ServerForce.Auto, true), Srv("aelrynth", false, ServerForce.Off, true), Srv("frost", false, ServerForce.Auto) };
|
||||
|
||||
var pick = ServerSelection.Plan(servers, "FROST");
|
||||
Check(pick != null && pick.Count == 3, "a known id plans every server");
|
||||
Check(pick!.Single(p => p.Id == "frost").Force == ServerForce.On, "the pick is forced On (case-insensitive)");
|
||||
Check(pick.Where(p => p.Id != "frost").All(p => p.Force == ServerForce.Off), "every other server is forced Off");
|
||||
|
||||
var auto = ServerSelection.Plan(servers, " Auto ");
|
||||
Check(auto != null && auto.All(p => p.Force == ServerForce.Auto), "auto resets every override");
|
||||
Check(ServerSelection.Plan(servers, "")!.All(p => p.Force == ServerForce.Auto), "empty means auto");
|
||||
Check(ServerSelection.Plan(servers, null)!.All(p => p.Force == ServerForce.Auto), "null means auto");
|
||||
Check(ServerSelection.Plan(servers, "nowhere") == null, "an unknown id is refused");
|
||||
Check(ServerSelection.Plan(Array.Empty<ServerState>(), "auto")!.Count == 0, "no servers, empty plan");
|
||||
}
|
||||
|
||||
private static void NotLoadedServerList()
|
||||
{
|
||||
Case("not-loaded server plugins");
|
||||
var forces = new Dictionary<string, ServerForce>(StringComparer.OrdinalIgnoreCase) { ["coldeve"] = ServerForce.On };
|
||||
ServerForce Force(string id) => forces.TryGetValue(id, out ServerForce f) ? f : ServerForce.Auto;
|
||||
var notLoaded = new[]
|
||||
{
|
||||
new NotLoadedServer("frost", "Frosthaven", "RynthFrostACE"),
|
||||
new NotLoadedServer("coldeve", "Coldeve", "RynthColdeve"),
|
||||
new NotLoadedServer("ilt", "Infinite Leaftide", "RynthILT"), // a built-in id: the built-in row wins
|
||||
new NotLoadedServer("", "No id", "RynthBroken"),
|
||||
};
|
||||
var list = new List<ServerState> { Srv("ilt", true, ServerForce.Auto, true) };
|
||||
NotLoadedServers.Append(list, notLoaded, Force);
|
||||
Check(list.Count == 3, "each new id added once, the built-in and the blank id skipped");
|
||||
ServerState frost = list.Single(s => s.Id == "frost");
|
||||
Check(!frost.Active && !frost.Detected && !frost.BuiltIn && frost.Name == "Frosthaven", "not loaded: listed, not detected, not active");
|
||||
Check(frost.Reason.Contains("RynthFrostACE") && frost.Reason.Contains("pick it"), "the reason names the plugin and how to load it");
|
||||
ServerState coldeve = list.Single(s => s.Id == "coldeve");
|
||||
Check(coldeve.Active && coldeve.Force == ServerForce.On && coldeve.Reason.Contains("loading RynthColdeve"), "forced On: active, loading its plugin");
|
||||
Check(list.Single(s => s.Id == "ilt").BuiltIn, "the built-in ilt row is kept");
|
||||
Check(ServerSelection.Plan(list, "frost") != null, "a not-loaded server can be picked");
|
||||
|
||||
var load = NotLoadedServers.ForcedOn(notLoaded, Force);
|
||||
Check(load.Count == 1 && load[0] == "coldeve", "only the server forced On asks for its plugin");
|
||||
forces["coldeve"] = ServerForce.Off;
|
||||
Check(NotLoadedServers.ForcedOn(notLoaded, Force).Count == 0, "Off loads nothing");
|
||||
|
||||
// The connect host is nobody's (none load at start); the world name the server announces
|
||||
// loads its plugin late, unless that server is forced Off.
|
||||
var byWorld = new[]
|
||||
{
|
||||
new NotLoadedServer("frost", "Frosthaven", "RynthFrostACE", new[] { "Frosthaven*" }),
|
||||
new NotLoadedServer("coldeve", "Coldeve", "RynthColdeve", new[] { "Coldeve" }),
|
||||
};
|
||||
Check(NotLoadedServers.ToLoad(byWorld, Force, null).Count == 0, "before login: nothing loads by world name");
|
||||
var hit = NotLoadedServers.ToLoad(byWorld, Force, "Frosthaven PvE");
|
||||
Check(hit.Count == 1 && hit[0] == "frost", "the announced world name loads its server's plugin");
|
||||
Check(NotLoadedServers.ToLoad(byWorld, Force, "Coldeve").Count == 0, "a server forced Off isn't loaded by its world name");
|
||||
Check(NotLoadedServers.ToLoad(byWorld, Force, "Somewhere Else").Count == 0, "a world nobody lists loads nothing");
|
||||
}
|
||||
|
||||
private static void SelectionCurrentPick()
|
||||
{
|
||||
Case("selection current pick");
|
||||
Check(ServerSelection.CurrentPick(new[] { Srv("ilt", true, ServerForce.Auto), Srv("ael", false, ServerForce.Auto) }) == ServerSelection.Auto, "no overrides is auto");
|
||||
Check(ServerSelection.CurrentPick(new[] { Srv("ilt", true, ServerForce.Off), Srv("ael", false, ServerForce.On) }) == "ael", "one On, rest Off is that pick");
|
||||
Check(ServerSelection.CurrentPick(new[] { Srv("ilt", true, ServerForce.On), Srv("ael", false, ServerForce.On) }) == null, "two On is a mix");
|
||||
Check(ServerSelection.CurrentPick(new[] { Srv("ilt", true, ServerForce.On), Srv("ael", false, ServerForce.Auto) }) == null, "one On, another Auto is a mix");
|
||||
Check(ServerSelection.CurrentPick(new[] { Srv("ilt", true, ServerForce.Off), Srv("ael", false, ServerForce.Auto) }) == null, "only Offs is a mix");
|
||||
Check(ServerSelection.CurrentPick(Array.Empty<ServerState>()) == ServerSelection.Auto, "no servers is auto");
|
||||
|
||||
// A plan applied gives back the same pick.
|
||||
var servers = new[] { Srv("ilt", true, ServerForce.Auto), Srv("ael", false, ServerForce.Auto) };
|
||||
var applied = ServerSelection.Plan(servers, "ael")!.Select(p => Srv(p.Id, servers.Single(s => s.Id == p.Id).Detected, p.Force)).ToArray();
|
||||
Check(ServerSelection.CurrentPick(applied) == "ael", "plan round trip");
|
||||
}
|
||||
|
||||
private static void SelectionActiveAndOwner()
|
||||
{
|
||||
Case("selection active and owner");
|
||||
Check(ServerSelection.ActiveServer(new[] { Srv("ilt", true, ServerForce.Auto), Srv("frost", true, ServerForce.Auto) })!.Id == "ilt", "first detected wins");
|
||||
Check(ServerSelection.ActiveServer(new[] { Srv("ilt", true, ServerForce.Auto), Srv("frost", false, ServerForce.On) })!.Id == "frost", "forced On beats detection");
|
||||
Check(ServerSelection.ActiveServer(new[] { Srv("ilt", true, ServerForce.Off) }) == null, "Off hides a detected server");
|
||||
Check(ServerSelection.ActiveServer(Array.Empty<ServerState>()) == null, "none");
|
||||
|
||||
var pack = SectionManifestParser.Parse("RynthServerPack", """
|
||||
{ "servers": [ { "id": "frost", "name": "Frosthaven", "hosts": [ "frost.example" ] } ] }
|
||||
""", out _);
|
||||
var ilt = SectionManifestParser.Parse("RynthILT", """
|
||||
{ "contributions": [ { "section": "skills", "server": "ilt", "label": "A", "command": "/a" },
|
||||
{ "section": "char", "server": "ilt", "label": "B", "command": "/b" } ] }
|
||||
""", out _);
|
||||
var ai = SectionManifestParser.Parse("RynthAi", """
|
||||
{ "contributions": [ { "section": "skills", "server": "ilt", "label": "C", "command": "/c" },
|
||||
{ "section": "skills", "server": "frost", "label": "D", "command": "/d" } ] }
|
||||
""", out _);
|
||||
var engine = SectionManifestParser.Parse("RynthCore", """
|
||||
{ "servers": [ { "id": "ilt", "name": "Infinite Leaftide" } ] }
|
||||
""", out _);
|
||||
var all = new[] { engine, ai, ilt, pack };
|
||||
|
||||
Check(ServerSelection.OwnerPlugin(all, "frost", "RynthCore") == "RynthServerPack", "the declaring plugin owns a server");
|
||||
Check(ServerSelection.OwnerPlugin(all, "ILT", "RynthCore") == "RynthILT", "else the most contributions (engine skipped)");
|
||||
Check(ServerSelection.OwnerPlugin(all, "nowhere", "RynthCore") == "", "nobody");
|
||||
var tie = SectionManifestParser.Parse("Alpha", """
|
||||
{ "contributions": [ { "section": "skills", "server": "x", "label": "A", "command": "/a" } ] }
|
||||
""", out _);
|
||||
var tie2 = SectionManifestParser.Parse("Beta", """
|
||||
{ "contributions": [ { "section": "skills", "server": "x", "label": "A", "command": "/a" } ] }
|
||||
""", out _);
|
||||
Check(ServerSelection.OwnerPlugin(new[] { tie2, tie }, "x", "RynthCore") == "Alpha", "ties go to the name that sorts first");
|
||||
}
|
||||
|
||||
private static unsafe void StateJson()
|
||||
{
|
||||
Case("state json");
|
||||
var ilt = SectionManifestParser.Parse("RynthILT", """
|
||||
{ "contributions": [ { "section": "skills", "server": "ilt", "label": "A", "command": "/a" } ] }
|
||||
""", out _);
|
||||
var servers = new[] { Srv("ilt", true, ServerForce.Auto, true), Srv("aelrynth", false, ServerForce.Auto, true) };
|
||||
string json = ServerStateJson.Build(servers, new[] { ilt }, 7, "infiniteleaftide.online", "Infinite \"Leaf\"", "RynthCore");
|
||||
|
||||
using var doc = System.Text.Json.JsonDocument.Parse(json);
|
||||
var root = doc.RootElement;
|
||||
Check(root.GetProperty("schema").GetInt32() == ServerStateJson.Schema && root.GetProperty("revision").GetInt32() == 7, "schema and revision");
|
||||
Check(root.GetProperty("host").GetString() == "infiniteleaftide.online", "host");
|
||||
Check(root.GetProperty("world").GetString() == "Infinite \"Leaf\"", "world (quotes escaped)");
|
||||
Check(root.GetProperty("pick").GetString() == "auto", "pick auto");
|
||||
Check(root.GetProperty("active").GetString() == "ilt" && root.GetProperty("activeName").GetString() == "ILT", "active server");
|
||||
Check(root.GetProperty("activePlugin").GetString() == "RynthILT", "active server's owner plugin");
|
||||
var rows = root.GetProperty("servers");
|
||||
Check(rows.GetArrayLength() == 2, "every server listed");
|
||||
var first = rows[0];
|
||||
Check(first.GetProperty("id").GetString() == "ilt" && first.GetProperty("active").GetBoolean() && first.GetProperty("detected").GetBoolean(), "row state");
|
||||
Check(first.GetProperty("force").GetString() == "auto" && first.GetProperty("builtIn").GetBoolean(), "row override and built-in");
|
||||
Check(rows[1].GetProperty("plugin").GetString() == "" && rows[1].GetProperty("reason").GetString() == "", "row with no owner");
|
||||
|
||||
var mixed = new[] { Srv("ilt", true, ServerForce.On), Srv("ael", false, ServerForce.On) };
|
||||
using (var m = System.Text.Json.JsonDocument.Parse(ServerStateJson.Build(mixed, Array.Empty<SectionManifest>(), 1, null, null, "RynthCore")))
|
||||
Check(m.RootElement.GetProperty("pick").GetString() == "mixed" && m.RootElement.GetProperty("host").GetString() == "", "mixed pick, null host");
|
||||
using (var n = System.Text.Json.JsonDocument.Parse(ServerStateJson.Build(new[] { Srv("ilt", false, ServerForce.Auto) }, Array.Empty<SectionManifest>(), 1, "h", "w", "RynthCore")))
|
||||
Check(n.RootElement.GetProperty("active").GetString() == "" && n.RootElement.GetProperty("activePlugin").GetString() == "", "no active server");
|
||||
|
||||
// Write: the plugin API's buffer convention (length returned; nothing written when too small).
|
||||
int length = System.Text.Encoding.UTF8.GetByteCount(json);
|
||||
byte[] small = new byte[length];
|
||||
fixed (byte* p = small)
|
||||
Check(ServerStateJson.Write(json, p, small.Length) == length && small.All(b => b == 0), "too small: length only, nothing written");
|
||||
Check(ServerStateJson.Write(json, null, 0) == length, "null buffer: length only");
|
||||
byte[] big = new byte[length + 1];
|
||||
fixed (byte* p = big)
|
||||
Check(ServerStateJson.Write(json, p, big.Length) == length, "fits: length");
|
||||
Check(System.Text.Encoding.UTF8.GetString(big, 0, length) == json && big[length] == 0, "fits: text and NUL");
|
||||
}
|
||||
|
||||
// ── Harness ────────────────────────────────────────────────────────
|
||||
|
||||
private static void Case(string name)
|
||||
{
|
||||
_case = name;
|
||||
Console.WriteLine($"-- {name}");
|
||||
}
|
||||
|
||||
private static void Check(bool ok, string what)
|
||||
{
|
||||
_checks++;
|
||||
if (ok) return;
|
||||
_failed++;
|
||||
Console.WriteLine($"FAIL [{_case}] {what}");
|
||||
}
|
||||
}
|
||||
36
tools/SectionsTests/SectionsTests.csproj
Normal file
36
tools/SectionsTests/SectionsTests.csproj
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Offline checks for the Mini Remote's sections (src\RynthCore.Engine\UI\Sections, the pure
|
||||
files compiled in): the per-character server overrides file, the plugin manifest parser and
|
||||
its limits, and the section catalog (core sections, server-scoped contributions, ordering).
|
||||
IltDetect.cs (with AelrynthWire.cs, which it shares a parser with) supplies the matching a
|
||||
plugin-declared server is detected with. Nothing native: no AC, no engine state.
|
||||
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>SectionsTests</RootNamespace>
|
||||
<!-- ServerStateJson.Write copies into a native (plugin API) buffer. -->
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\RynthCore.Engine\UI\Sections\ServerForce.cs" Link="Engine\ServerForce.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\UI\Sections\SectionManifest.cs" Link="Engine\SectionManifest.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\UI\Sections\SectionCatalog.cs" Link="Engine\SectionCatalog.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\IltDetect.cs" Link="Engine\IltDetect.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AelrynthWire.cs" Link="Engine\AelrynthWire.cs" />
|
||||
<!-- The Diagnostics server picker's plan and the plugin API v86 server-state JSON. -->
|
||||
<Compile Include="..\..\src\RynthCore.Engine\UI\Sections\ServerSelection.cs" Link="Engine\ServerSelection.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\UI\Sections\ServerStateJson.cs" Link="Engine\ServerStateJson.cs" />
|
||||
<!-- Installed server plugins the connect host left out: listed in the picker, loaded when forced On. -->
|
||||
<Compile Include="..\..\src\RynthCore.Engine\UI\Sections\NotLoadedServers.cs" Link="Engine\NotLoadedServers.cs" />
|
||||
<!-- The status feed's / Session Stats' XP and luminance session formula (pure). -->
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
@ -33,6 +33,7 @@ internal static class Program
|
|||
StatusFileReads();
|
||||
MoveProtocol();
|
||||
LogRollover();
|
||||
ServeGuards();
|
||||
if (Arg(args, "--atlas") is { } atlas) RealAtlas(atlas);
|
||||
if (portal != null) RealSpellTable(portal);
|
||||
if (cell != null) RealWorldMap(cell, outFile);
|
||||
|
|
@ -42,6 +43,53 @@ internal static class Program
|
|||
return _failed == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
// ── serve guards (remote access) ────────────────────────────────────────
|
||||
|
||||
private static void ServeGuards()
|
||||
{
|
||||
Section("status server: loopback, token length, lockout, bounded bodies, log-safe text");
|
||||
Check(ServeGuard.IsLoopbackPrefix("http://127.0.0.1:8740/"), "127.0.0.1 is loopback");
|
||||
Check(ServeGuard.IsLoopbackPrefix("http://localhost:8740/"), "localhost is loopback");
|
||||
Check(ServeGuard.IsLoopbackPrefix("http://[::1]:8740/"), "[::1] is loopback");
|
||||
Check(!ServeGuard.IsLoopbackPrefix("http://+:8740/"), "+ is every address");
|
||||
Check(!ServeGuard.IsLoopbackPrefix("http://*:8740/"), "* is every address");
|
||||
Check(!ServeGuard.IsLoopbackPrefix("http://100.64.1.2:8740/"), "a Tailscale address is not");
|
||||
Check(!ServeGuard.IsLoopbackPrefix("http://127.0.0.1.evil.example:8740/"), "a name starting 127.0.0.1 is not");
|
||||
|
||||
Check(ServeGuard.TokenProblem("http://127.0.0.1:8740/", "") != null, "no token: never serves");
|
||||
Check(ServeGuard.TokenProblem("http://127.0.0.1:8740/", "short") == null, "loopback: any token");
|
||||
Check(ServeGuard.TokenProblem("http://+:8740/", "short") != null, "remote bind: a short token is refused");
|
||||
Check(ServeGuard.TokenProblem("http://+:8740/", new string('k', 16)) == null, "remote bind: 16 characters is fine");
|
||||
|
||||
var t = new AuthThrottle();
|
||||
var lan = System.Net.IPAddress.Parse("192.168.1.50");
|
||||
var t0 = new DateTime(2026, 10, 13, 12, 0, 0, DateTimeKind.Utc);
|
||||
bool started = false;
|
||||
for (int i = 0; i < AuthThrottle.MaxFailures - 1; i++) started |= t.Fail(lan, t0.AddSeconds(i));
|
||||
Check(!started && !t.IsBlocked(lan, t0.AddSeconds(10)), "under the limit: not blocked");
|
||||
Check(t.Fail(lan, t0.AddSeconds(10)), "the limit starts a lockout (reported once)");
|
||||
Check(t.IsBlocked(lan, t0.AddMinutes(4)), "still blocked inside the lockout");
|
||||
Check(!t.IsBlocked(lan, t0.AddMinutes(6)), "free again after it");
|
||||
var slow = System.Net.IPAddress.Parse("192.168.1.51");
|
||||
for (int i = 0; i < AuthThrottle.MaxFailures * 2; i++) t.Fail(slow, t0.AddSeconds(i * 61));
|
||||
Check(!t.IsBlocked(slow, t0.AddSeconds(AuthThrottle.MaxFailures * 2 * 61)), "failures spread past the window don't add up");
|
||||
var other = System.Net.IPAddress.Parse("192.168.1.52");
|
||||
for (int i = 0; i < AuthThrottle.MaxFailures - 1; i++) t.Fail(other, t0);
|
||||
t.Succeed(other);
|
||||
Check(!t.Fail(other, t0), "a good token clears the count");
|
||||
for (int i = 0; i < AuthThrottle.MaxFailures * 2; i++) t.Fail(System.Net.IPAddress.Loopback, t0);
|
||||
Check(!t.IsBlocked(System.Net.IPAddress.Loopback, t0), "loopback is never locked out");
|
||||
|
||||
Check(ServeGuard.TryReadBounded(new MemoryStream(Encoding.UTF8.GetBytes("{\"pid\":1}")), 9, 64, null, out string small) && small == "{\"pid\":1}", "a small body reads");
|
||||
Check(!ServeGuard.TryReadBounded(new MemoryStream(new byte[100]), 100, 64, null, out _), "a declared length over the limit is refused");
|
||||
Check(!ServeGuard.TryReadBounded(new MemoryStream(new byte[100]), -1, 64, null, out _), "chunked (no length) over the limit is refused");
|
||||
Check(ServeGuard.TryReadBounded(new MemoryStream(new byte[64]), -1, 64, null, out _), "exactly the limit reads");
|
||||
|
||||
Check(ServeGuard.LogSafe("a\r\nFAKE LOG LINE") == "a FAKE LOG LINE", "CR/LF can't start a log line");
|
||||
Check(ServeGuard.LogSafe(new string('x', 500), 10) == "xxxxxxxxxx...", "capped");
|
||||
Check(ServeGuard.LogSafe(null) == "", "null is empty");
|
||||
}
|
||||
|
||||
// ── log rollover ────────────────────────────────────────────────────────
|
||||
|
||||
private static void LogRollover()
|
||||
|
|
|
|||
|
|
@ -32,6 +32,7 @@
|
|||
<Compile Include="..\..\src\RynthCore.StatusAgent\NavAtlasService.cs" Link="Agent\NavAtlasService.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.StatusAgent\Dat\DatDatabase.cs" Link="Agent\Dat\DatDatabase.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.StatusAgent\StatusFileCache.cs" Link="Agent\StatusFileCache.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.StatusAgent\ServeGuard.cs" Link="Agent\ServeGuard.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
|
|
@ -8,6 +8,15 @@ thread - the first time that line runs. Run after adding ImGui code:
|
|||
python tools/check_imgui_calls.py
|
||||
|
||||
Exit code 1 lists the calls with no matching export.
|
||||
|
||||
It also flags ImGui.Text / TextColored / TextWrapped / TextDisabled /
|
||||
BulletText / SetTooltip / SetItemTooltip / LabelText(value) calls anywhere in
|
||||
the engine whose text isn't a plain literal: ImGui.NET passes that text to
|
||||
native ImGui as a printf format, so a '%' in it reads missing arguments. Such
|
||||
text goes through SafeImGui instead. To check another tree (a RynthSuite
|
||||
checkout's Plugins folder) for those calls only:
|
||||
|
||||
python tools/check_imgui_calls.py C:/path/to/RynthSuite/Plugins
|
||||
"""
|
||||
import re
|
||||
import struct
|
||||
|
|
@ -16,7 +25,8 @@ from pathlib import Path
|
|||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
DLL = ROOT / "src" / "RynthCore.Engine" / "Native" / "cimgui.dll"
|
||||
SOURCES = ROOT / "src" / "RynthCore.Engine" / "ImGui"
|
||||
ENGINE = ROOT / "src" / "RynthCore.Engine"
|
||||
SOURCES = ENGINE / "ImGui"
|
||||
# Old diagnostic shell, FORCE-gated and never run: not held to this check.
|
||||
SKIP = {"RynthCoreShell.cs"}
|
||||
|
||||
|
|
@ -58,7 +68,202 @@ def pe_exports(path: Path) -> set[str]:
|
|||
return names
|
||||
|
||||
|
||||
# --- Text drawn as a printf format -------------------------------------------
|
||||
# ImGui.NET hands the string of these calls to native ImGui as a printf format
|
||||
# with no arguments: a '%' in a chat line, name, server reply or setting reads
|
||||
# arguments that were never passed (garbage, or a crash on %s / %n). Text that
|
||||
# isn't a literal goes through SafeImGui (engine: ImGui/SafeImGui.cs, RynthSuite:
|
||||
# Plugins/Shared/SafeImGui.cs), which doubles every '%'. The number is the
|
||||
# index of the format argument.
|
||||
FORMAT_TEXT_CALLS = {
|
||||
"Text": 0, "TextColored": 1, "TextWrapped": 0, "TextDisabled": 0,
|
||||
"BulletText": 0, "SetTooltip": 0, "SetItemTooltip": 0, "LabelText": 1,
|
||||
}
|
||||
FORMAT_CALL_RE = re.compile(
|
||||
r"(?<![\w.])(?:ImGuiNET\.)?ImGui\.(" + "|".join(FORMAT_TEXT_CALLS) + r")\s*\(")
|
||||
STRING_START_RE = re.compile(r'(\$*)(@?)(\$*)"')
|
||||
# The wrappers themselves pass their (escaped) text on.
|
||||
FORMAT_SKIP = {"SafeImGui.cs"}
|
||||
|
||||
|
||||
def skip_token(s: str, i: int):
|
||||
"""End of the comment, string or char literal starting at i, else None."""
|
||||
if s.startswith("//", i):
|
||||
j = s.find("\n", i)
|
||||
return len(s) if j < 0 else j
|
||||
if s.startswith("/*", i):
|
||||
j = s.find("*/", i + 2)
|
||||
return len(s) if j < 0 else j + 2
|
||||
c = s[i]
|
||||
if c == "'":
|
||||
j = i + 1
|
||||
while j < len(s) and s[j] != "'":
|
||||
j += 2 if s[j] == "\\" else 1
|
||||
return j + 1
|
||||
if c not in '"$@':
|
||||
return None
|
||||
m = STRING_START_RE.match(s, i)
|
||||
if not m:
|
||||
return None
|
||||
dollars = len(m.group(1)) + len(m.group(3))
|
||||
verbatim = bool(m.group(2))
|
||||
q = m.end() - 1
|
||||
n = 0
|
||||
while q + n < len(s) and s[q + n] == '"':
|
||||
n += 1
|
||||
if n == 2: # ""
|
||||
return q + 2
|
||||
if n >= 3: # raw string literal
|
||||
j = q + n
|
||||
close = '"' * n
|
||||
while j < len(s) and not s.startswith(close, j):
|
||||
if dollars and s.startswith("{" * dollars, j):
|
||||
j = skip_code(s, j + dollars, "}") + 1
|
||||
else:
|
||||
j += 1
|
||||
return j + n
|
||||
j = q + 1
|
||||
while j < len(s):
|
||||
ch = s[j]
|
||||
if ch == "\\" and not verbatim:
|
||||
j += 2
|
||||
elif ch == '"':
|
||||
if verbatim and s.startswith('""', j):
|
||||
j += 2
|
||||
else:
|
||||
return j + 1
|
||||
elif dollars and ch == "{":
|
||||
if s.startswith("{{", j):
|
||||
j += 2
|
||||
else:
|
||||
j = skip_code(s, j + 1, "}") + 1
|
||||
else:
|
||||
j += 1
|
||||
return j
|
||||
|
||||
|
||||
def skip_code(s: str, i: int, closer: str) -> int:
|
||||
"""Index of the closer that ends the code starting at i (nesting, strings and comments skipped)."""
|
||||
depth = 0
|
||||
j = i
|
||||
while j < len(s):
|
||||
end = skip_token(s, j)
|
||||
if end is not None:
|
||||
j = end
|
||||
continue
|
||||
ch = s[j]
|
||||
if ch in "([{":
|
||||
depth += 1
|
||||
elif ch in ")]}":
|
||||
if depth == 0 and ch == closer:
|
||||
return j
|
||||
depth -= 1
|
||||
j += 1
|
||||
return j
|
||||
|
||||
|
||||
def call_args(s: str, open_paren: int):
|
||||
"""[(start, end)] of each top-level argument of the call whose '(' is at open_paren."""
|
||||
args = []
|
||||
depth = 0
|
||||
start = open_paren + 1
|
||||
j = start
|
||||
while j < len(s):
|
||||
end = skip_token(s, j)
|
||||
if end is not None:
|
||||
j = end
|
||||
continue
|
||||
ch = s[j]
|
||||
if ch in "([{":
|
||||
depth += 1
|
||||
elif ch in ")]}":
|
||||
if depth == 0:
|
||||
args.append((start, j))
|
||||
return args, j
|
||||
depth -= 1
|
||||
elif ch == "," and depth == 0:
|
||||
args.append((start, j))
|
||||
start = j + 1
|
||||
j += 1
|
||||
return args, j
|
||||
|
||||
|
||||
def literal_kind(arg: str) -> str:
|
||||
"""'literal' for plain string literals (joined with '+' at most), 'percent' for such
|
||||
literals holding a lone '%', else 'expression'."""
|
||||
j = 0
|
||||
pieces = []
|
||||
while j < len(arg):
|
||||
ch = arg[j]
|
||||
if ch.isspace() or ch == "+":
|
||||
j += 1
|
||||
continue
|
||||
end = skip_token(arg, j)
|
||||
if end is None:
|
||||
return "expression"
|
||||
piece = arg[j:end]
|
||||
if not (piece.startswith("//") or piece.startswith("/*")):
|
||||
if piece[0] not in '"@$' or "$" in piece[:piece.index('"')]:
|
||||
return "expression"
|
||||
pieces.append(piece)
|
||||
j = end
|
||||
if not pieces:
|
||||
return "expression"
|
||||
return "percent" if any("%" in p.replace("%%", "") for p in pieces) else "literal"
|
||||
|
||||
|
||||
def format_text_calls(text: str):
|
||||
"""Every format-text ImGui call in C# source: (match, arg_start, arg_end, kind).
|
||||
Calls inside comments and strings (e.g. Lua script text) are skipped."""
|
||||
code = []
|
||||
j = 0
|
||||
while j < len(text):
|
||||
end = skip_token(text, j)
|
||||
if end is None:
|
||||
code.append(text[j])
|
||||
j += 1
|
||||
else:
|
||||
code.append("".join(c if c == "\n" else " " for c in text[j:end]))
|
||||
j = end
|
||||
masked = "".join(code)
|
||||
for m in FORMAT_CALL_RE.finditer(masked):
|
||||
args, _ = call_args(text, m.end() - 1)
|
||||
index = FORMAT_TEXT_CALLS[m.group(1)]
|
||||
if index >= len(args):
|
||||
yield m, m.end(), m.end(), "expression"
|
||||
continue
|
||||
a, b = args[index]
|
||||
yield m, a, b, literal_kind(text[a:b])
|
||||
|
||||
|
||||
def unsafe_format_text(roots) -> list[str]:
|
||||
found = []
|
||||
for root in roots:
|
||||
for f in sorted(Path(root).rglob("*.cs")):
|
||||
if f.name in FORMAT_SKIP or {"bin", "obj"} & set(f.parts):
|
||||
continue
|
||||
text = f.read_text(encoding="utf-8-sig")
|
||||
for m, a, b, kind in format_text_calls(text):
|
||||
if kind == "literal":
|
||||
continue
|
||||
line = text.count("\n", 0, m.start()) + 1
|
||||
what = "a literal with a lone '%'" if kind == "percent" else "text that isn't a literal"
|
||||
found.append(f"{f}:{line}: ImGui.{m.group(1)} with {what}: {' '.join(text[a:b].split())[:80]}")
|
||||
return found
|
||||
|
||||
|
||||
def main() -> int:
|
||||
# python tools/check_imgui_calls.py DIR... checks only the format text under DIR
|
||||
# (e.g. a RynthSuite checkout's Plugins folder).
|
||||
if len(sys.argv) > 1:
|
||||
unsafe = unsafe_format_text(sys.argv[1:])
|
||||
if unsafe:
|
||||
print("ImGui text calls that draw non-literal text as a printf format (use SafeImGui):")
|
||||
print("\n".join(" " + u for u in unsafe))
|
||||
return 1
|
||||
print("OK: no ImGui text call draws non-literal text as a format.")
|
||||
return 0
|
||||
|
||||
exports = pe_exports(DLL)
|
||||
|
||||
def found(prefix: str, name: str) -> bool:
|
||||
|
|
@ -70,7 +275,7 @@ def main() -> int:
|
|||
if f.name in SKIP:
|
||||
continue
|
||||
text = f.read_text(encoding="utf-8")
|
||||
for m in re.finditer(r"ImGui(?:NET\.ImGui)?\.(\w+)\(", text):
|
||||
for m in re.finditer(r"(?<!\w)ImGui(?:NET\.ImGui)?\.(\w+)\(", text):
|
||||
if not found("ig", m.group(1)):
|
||||
missing.append(f"{f.relative_to(ROOT)}:{text.count(chr(10), 0, m.start()) + 1}: ImGui.{m.group(1)}")
|
||||
# Direct native calls name the exact export (overload suffix included).
|
||||
|
|
@ -81,11 +286,17 @@ def main() -> int:
|
|||
if not found(MEMBER_PREFIX[m.group(1)], m.group(2)):
|
||||
missing.append(f"{f.relative_to(ROOT)}:{text.count(chr(10), 0, m.start()) + 1}: {m.group(1)}.{m.group(2)}")
|
||||
|
||||
unsafe = unsafe_format_text([ENGINE])
|
||||
|
||||
if missing:
|
||||
print("ImGui calls with no export in cimgui.dll:")
|
||||
print("\n".join(" " + m for m in missing))
|
||||
if unsafe:
|
||||
print("ImGui text calls that draw non-literal text as a printf format (use SafeImGui):")
|
||||
print("\n".join(" " + u for u in unsafe))
|
||||
if missing or unsafe:
|
||||
return 1
|
||||
print(f"OK: every ImGui call resolves ({len(exports)} exports).")
|
||||
print(f"OK: every ImGui call resolves ({len(exports)} exports); no text call draws non-literal text as a format.")
|
||||
return 0
|
||||
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue