Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion docs/launcher.md
Original file line number Diff line number Diff line change
Expand Up @@ -1335,6 +1335,8 @@ Mods, modules and leagues use the same editor on Windows and Linux. Each setting
left and its control in a column on the right; in a card under 520 pixels wide the control moves under the text.

- On/off switches; text with length and pattern checks; single and multiple choices, including typed game-value sources.
- Text fields declared with the `password` format are masked. The local settings file and configuration history
store the value as plain text.
- Numbers with exact-value boxes and sliders when bounded; percentages and multipliers are displayed in their declared units,
and durations are edited in seconds. Step sizes and integer restrictions are checked before saving.
- Ranges have separate minimum and maximum controls; low cannot exceed high.
Expand All @@ -1348,7 +1350,10 @@ Unreadable existing user files block editing instead of being silently replaced.
Modules and Leagues ask before discarding a draft when switching selection or refreshing. Saving checks the reviewed file's
hash, so another tool's changes require a refresh. Changes use the shared workspace lock and the normal optional save backup.
Previous configuration files are copied to Waypoint's `config-history/<id>/` before replacement, separately from save backups.
Reset to defaults asks first. Mod values use `data/mods/`, module values `data/modules/`, and league values `data/leagues/`.
Reset to defaults asks first. Mod values use `data/mods/` unless the installed mod declares a `userSettingsFile` and has its own `<id>.json` beside its
`mod.json`; Waypoint edits that file and preserves it across updates. Module values use `data/modules/` and league values
use `data/leagues/`. For GlobalChat’s channel maps, use **Add entry** or **Remove** to edit routes. Choose a route type
to show the applicable server address and port or Discord channel ID.

### Backups

Expand Down
7 changes: 4 additions & 3 deletions docs/runtime-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -285,9 +285,10 @@ BuildMod or live.ps1 builds it; refused on release installs). Under the mutex an
dropped. UninstallMod moves `Mods/Binaries/<id>` (and `Mods/Source/<id>` in a checkout) the same way, drops the
registry entry and the mod's line of `mod-state.txt`. A batch passes `-ModIds a;b` (all checked first, one backup):
InstallMod adds `-ModStageds` and `-ModTargets` in the same order, and BuildMod's `-ModProjects a;b` builds several in one
parallel MSBuild run over a temporary traversal project. SaveModSettings atomically writes `data/mods/<id>.json` from
validated values. Core reads `settings.json` and the user file itself; script mods are fingerprinted by their scripts'
hashes. The one checkout write outside the adapter is the on/off switch: Core replaces `mod-state.txt` atomically
parallel MSBuild run over a temporary traversal project. SaveModSettings atomically writes the mod's user settings from
validated values. When the installed manifest declares `userSettingsFile` as `<id>.json` and that file exists beside the
manifest, Core reads it and the adapter writes it there. Waypoint preserves the file during binary updates. Otherwise,
Core and the adapter use `data/mods/<id>.json`. Script mods are fingerprinted by their scripts' hashes. The one checkout write outside the adapter is the on/off switch: Core replaces `mod-state.txt` atomically
(`ModCatalog.WriteChoice`) while holding Shared's workspace lock, so a switch is instant; EnableMod and DisableMod remain
for other callers. A running server with no verified source hook gets a restart notice in both interfaces; releases are
unknown because they have no source. Saved choices are not proof of a runtime load.
Expand Down
33 changes: 28 additions & 5 deletions scripts/ModBridge.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,20 @@ function Get-StagedModPath([string]$path, [switch]$File) {
else { Require (Test-Path -LiteralPath $full -PathType Container) 'The prepared mod folder is missing.' }
return $full
}
function Get-InstalledModSettings([string]$folder, [string]$id) {
if ($id -cin @('mod','settings')) { return }
$name = $id + '.json'
$path = Join-Path $folder $name
$manifest = Join-Path $folder 'mod.json'
if (-not (Test-Path -LiteralPath $path -PathType Leaf) -or -not (Test-Path -LiteralPath $manifest -PathType Leaf)) { return }
Assert-Physical $manifest
Require ((Get-Item -LiteralPath $manifest).Length -le 262144) 'Mod manifest exceeds its size limit.'
$declaration = [IO.File]::ReadAllText($manifest) | ConvertFrom-Json
if ($declaration.PSObject.Properties['userSettingsFile'] -and $declaration.userSettingsFile -ceq $name) {
Assert-Physical $path
return $path
}
}
function Move-ModAside([string]$folder, [string]$target) {
# Never deleted: the previous copy of a mod moves to Mods/.replaced/, where the Gateway does not look.
if (-not (Test-Path -LiteralPath $folder)) { return }
Expand All @@ -235,6 +249,7 @@ function Move-ModAside([string]$folder, [string]$target) {
New-Item -ItemType Directory -Path (Split-Path $aside) -Force | Out-Null
Move-Item -LiteralPath $folder -Destination $aside
Write-Host "The previous Mods/$target/$ModId is kept at $aside."
return $aside
}
function Install-StagedMod($snapshot) {
# -ModIds, -ModStageds and -ModTargets (';'-separated, in the same order) install several with one backup; every one is
Expand Down Expand Up @@ -266,10 +281,17 @@ function Install-StagedMod($snapshot) {
Assert-Physical $root
New-Item -ItemType Directory -Path $root -Force | Out-Null
$destination = Join-Path $root $mod.Id
Move-ModAside $destination $mod.Target
$settingsName = $mod.Id + '.json'
$installedSettings = Join-Path $destination $settingsName
$keepSettings = $mod.Target -eq 'Binaries' -and [bool](Get-InstalledModSettings $destination $mod.Id)
$aside = Move-ModAside $destination $mod.Target
# A release replaces a source install of the same mod, which live.ps1 would otherwise build over it.
if ($mod.Target -eq 'Binaries' -and -not $script:isRelease) { Move-ModAside (At "Mods/Source/$($mod.Id)") 'Source' }
if ($mod.Target -eq 'Binaries' -and -not $script:isRelease) { $null = Move-ModAside (At "Mods/Source/$($mod.Id)") 'Source' }
Copy-Item -LiteralPath $mod.Staged -Destination $destination -Recurse
if ($keepSettings) {
Assert-Physical $installedSettings
Copy-Item -LiteralPath (Join-Path $aside $settingsName) -Destination $installedSettings -Force
}
Remove-Item -LiteralPath $mod.Staged -Recurse -Force
Write-Host "Installed $($mod.Id) into Mods/$($mod.Target)."
}
Expand All @@ -285,7 +307,8 @@ function Save-ModSettings($snapshot) {
Require ($parsed -is [Management.Automation.PSCustomObject]) 'Mod settings must be a JSON object.'
Backup-Saves $snapshot
Set-Stage 'Saving mod settings' $ModId
$folder = At 'data/mods'
$installed = Join-Path (Get-ModFolder) $ModId
$folder = if (Get-InstalledModSettings $installed $ModId) { $installed } else { At 'data/mods' }
Assert-Physical $folder
New-Item -ItemType Directory -Path $folder -Force | Out-Null
$path = Join-Path $folder "$ModId.json"
Expand Down Expand Up @@ -322,8 +345,8 @@ function Uninstall-Mod($snapshot) {
Set-Stage $(if ($mods.Count -eq 1) { 'Uninstalling mod' } else { 'Uninstalling mods' }) (($ids -join ', ') + ' to Mods/.replaced')
foreach ($mod in $mods) {
$script:ModId = $mod.Id
if ($mod.HasSource) { Move-ModAside $mod.Source 'Source' }
Move-ModAside $mod.Binary 'Binaries'
if ($mod.HasSource) { $null = Move-ModAside $mod.Source 'Source' }
$null = Move-ModAside $mod.Binary 'Binaries'
}
if (-not $script:isRelease) { Write-ManagedMods @(Read-ManagedMods | Where-Object { $_.Id -cnotin $ids }) }
$state = Join-Path (Get-ModFolder) 'mod-state.txt'
Expand Down
33 changes: 27 additions & 6 deletions src/Launcher.Core/ModSettingsForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,20 @@ public static ModSettingsForm Load(string id, string declarationsPath, string ro
var settings = Parse(declarations);
var user = new JsonObject();
string userPath = Path.Combine(root, UserFile(id, kind));
if (kind == "mods" && id is not ("mod" or "settings"))
{
string folder = Path.GetDirectoryName(declarationsPath)!;
string name = id + ".json";
string manifest = Path.Combine(folder, "mod.json");
string besideMod = Path.Combine(folder, name);
if (File.Exists(besideMod) && File.Exists(manifest))
{
if (!ModCatalog.Physical(manifest) || new FileInfo(manifest).Length > 256 * 1024)
throw new IOException(L.Text("The existing settings cannot be safely read. Nothing was changed."));
if (JsonNode.Parse(File.ReadAllText(manifest), NodeOptions, Jsonc)?["userSettingsFile"] is JsonValue marker
&& marker.TryGetValue(out string? configured) && configured == name) userPath = besideMod;
}
}
string userHash = GameSystems.Hash(userPath);
if (File.Exists(userPath))
{
Expand Down Expand Up @@ -94,11 +108,13 @@ static IReadOnlyList<ModSetting> ParseSettings(JsonObject settings, int depth, b
: (o!.DeepClone(), Show(o!))).ToList()
: [];
string type = Text("type");
string format = Text("format");
if (!ModSetting.EditableTypes.Contains(type)) throw new InvalidDataException(L.Text("Unsupported setting type: {0}", type));
if (d["when"] is not (null or JsonObject) || d["advanced"] is { } advanced && advanced.GetValueKind() is not (JsonValueKind.True or JsonValueKind.False)
|| d["options"] is not null && (d["options"] is not JsonArray { Count: > 0 } || options.Count == 0 || d["source"] is not null)
|| type is "choice" or "choices" && options.Count == 0 && Text("source").Length == 0
|| Text("format") is not ("" or "percent" or "duration" or "multiplier")
|| format is not ("" or "percent" or "duration" or "multiplier" or "password")
|| format == "password" && type != "text"
|| Text("applies") is not ("" or "now" or "nextArea" or "restart")
|| Text("of") is not ("" or "integer" or "number") || Text("of").Length > 0 && type != "range") throw Invalid();
if (Text("pattern").Length > 0)
Expand All @@ -107,7 +123,7 @@ static IReadOnlyList<ModSetting> ParseSettings(JsonObject settings, int depth, b
var children = type == "group" && d["settings"] is JsonObject group ? ParseSettings(group, depth + 1) : null;
ModSetting? Nested(string key) => d[key] is JsonObject child ? ParseSettings(new JsonObject { [key] = child.DeepClone() }, depth + 1, needsDefault: false)[0] : null;
JsonNode? defaults = children is null ? d["default"]?.DeepClone() : new JsonObject(children.Select(c => KeyValuePair.Create(c.Name, c.Default?.DeepClone())));
result.Add(new(name, type, defaults, Text("label"), Text("description"), Text("unit"), Text("format"),
result.Add(new(name, type, defaults, Text("label"), Text("description"), Text("unit"), format,
Number("min"), Number("max"), options, Text("source"), Whole("minItems"), Whole("maxItems"), Whole("minLength"), Whole("maxLength"),
Text("applies") is { Length: > 0 } applies ? applies : "now", d["advanced"] is JsonValue a && a.TryGetValue(out bool adv) && adv,
Number("step"), Text("pattern"), Text("of") == "integer", type == "list" ? Nested("item") : null,
Expand Down Expand Up @@ -211,6 +227,12 @@ bool Numeric(JsonNode? n, bool whole = false) => n?.GetValueKind() == JsonValueK
bool Allowed(JsonNode? n) => setting.Options.Count > 0 ? setting.Options.Any(o => Equal(o.Value, n))
: setting.Source.Length > 0 && n?.GetValueKind() == JsonValueKind.String && n.GetValue<string>().Length > 0;
bool Count(int n) => !(n < setting.MinItems || n > setting.MaxItems);
bool MatchesPattern(string text)
{
try { return setting.Pattern.Length == 0 || System.Text.RegularExpressions.Regex.IsMatch(text, @"\A(?:" + setting.Pattern + @")\z",
System.Text.RegularExpressions.RegexOptions.None, TimeSpan.FromMilliseconds(100)); }
catch (Exception e) when (e is ArgumentException or System.Text.RegularExpressions.RegexMatchTimeoutException) { return false; }
}
switch (setting.Type)
{
case "bool": return kind is JsonValueKind.True or JsonValueKind.False ? null : Invalid();
Expand All @@ -224,13 +246,12 @@ bool Allowed(JsonNode? n) => setting.Options.Count > 0 ? setting.Options.Any(o =
if (kind != JsonValueKind.String) return Invalid();
string text = value.GetValue<string>();
if (text.Length < setting.MinLength || text.Length > setting.MaxLength) return Invalid();
try { return setting.Pattern.Length == 0 || System.Text.RegularExpressions.Regex.IsMatch(text, "\\A(?:" + setting.Pattern + ")\\z",
System.Text.RegularExpressions.RegexOptions.None, TimeSpan.FromMilliseconds(100)) ? null : Invalid(); }
catch (Exception e) when (e is ArgumentException or System.Text.RegularExpressions.RegexMatchTimeoutException) { return Invalid(); }
return MatchesPattern(text) ? null : Invalid();
case "list": return value is JsonArray list && Count(list.Count) && setting.Item is { } item
&& list.All(n => Validate(item, n) is null) ? null : Invalid();
case "map": return value is JsonObject map && setting.Value is { } entry
&& map.All(p => (setting.Options.Count == 0 && setting.Source.Length == 0 || Allowed(JsonValue.Create(p.Key)))
&& Count(map.Count) && map.All(p => MatchesPattern(p.Key)
&& (setting.Options.Count == 0 && setting.Source.Length == 0 || Allowed(JsonValue.Create(p.Key)))
&& Validate(entry, p.Value) is null) ? null : Invalid();
case "group": return value is JsonObject group && setting.Children is { } children
&& children.All(c => group.FirstOrDefault(p => p.Key.Equals(c.Name, StringComparison.OrdinalIgnoreCase)).Value is not { } child
Expand Down
22 changes: 21 additions & 1 deletion src/Waypoint/SettingsEditor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,19 @@ void BuildGroup(StackPanel panel, IReadOnlyList<ModSetting> settings, Func<ModSe
// A list of labels needs the width: it stays under the description, with no control column.
foreach (var (_, box) in boxes) { text.Children.Add(box); CheckChanged(box, Change); }
read = () => new JsonArray(boxes.Where(b => b.Box.IsChecked == true).Select(b => b.Value.DeepClone()).ToArray()); break;
case "text" when setting.Format == "password":
#if WINDOWS
var password = new PasswordBox { Password = ModSettingsForm.Show(value), MaxLength = setting.MaxLength ?? 0 };
password.PasswordChanged += (_, _) => Change();
read = () => JsonValue.Create(password.Password);
#else
var password = new TextBox { Text = ModSettingsForm.Show(value), PasswordChar = '●', MaxLength = setting.MaxLength ?? 0 };
password.TextChanged += (_, _) => Change();
read = () => JsonValue.Create(password.Text ?? "");
#endif
A11y.SetName(password, setting.Title);
control.Children.Add(password);
break;
default:
var entry = new TextBox { Text = ModSettingsForm.Show(value) };
A11y.SetName(entry, setting.Title);
Expand Down Expand Up @@ -255,7 +268,14 @@ void Add(JsonNode? current, string key = "")
keys.SelectedItem = keys.Items.OfType<ComboBoxItem>().FirstOrDefault(i => (string?)i.Tag == key);
row.Children.Add(keys); keys.SelectionChanged += (_, _) => Change(); readKey = () => (keys.SelectedItem as ComboBoxItem)?.Tag as string ?? "";
}
else { var keyBox = new TextBox { Text = key }; row.Children.Add(keyBox); keyBox.TextChanged += (_, _) => Change(); readKey = () => keyBox.Text ?? ""; }
else
{
var keyBox = new TextBox { Text = key };
A11y.SetName(keyBox, L.Text("Key"));
row.Children.Add(keyBox);
keyBox.TextChanged += (_, _) => Change();
readKey = () => keyBox.Text?.Trim() ?? "";
}
}
var read = Field(row, item, current);
var remove = Button(L.Text("Remove"), () => { rows.Children.Remove(row); entries.RemoveAll(e => e.Row == row); Change(); });
Expand Down
10 changes: 10 additions & 0 deletions tests/ModBrowser.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,21 @@ try {
[IO.File]::WriteAllText($settings, '[]')
Refused { Operation 'SaveModSettings' 'alpha' $settings } 'non-object settings are refused'
Check ([IO.File]::ReadAllText((At 'data/mods/alpha.json')).Contains('ownerValue')) 'refused settings preserve the previous values'
$manifest = Get-Content -Raw -LiteralPath (At 'Mods/Binaries/alpha/mod.json') | ConvertFrom-Json
$manifest | Add-Member -NotePropertyName userSettingsFile -NotePropertyValue alpha.json
$manifest | ConvertTo-Json | Set-Content -LiteralPath (At 'Mods/Binaries/alpha/mod.json')
[IO.File]::WriteAllText((At 'Mods/Binaries/alpha/alpha.json'), '{"quantity":3}')
[IO.File]::WriteAllText($settings, '{"quantity":4}')
Operation 'SaveModSettings' 'alpha' $settings
Check ((Get-Content -LiteralPath (At 'Mods/Binaries/alpha/alpha.json') -Raw | ConvertFrom-Json).quantity -eq 4) 'save updates the installed mod settings'
Check ((Get-Content -LiteralPath (At 'data/mods/alpha.json') -Raw | ConvertFrom-Json).quantity -eq 2) 'save leaves fallback settings intact'
New-Item -ItemType Directory -Force (At 'Mods/Source/alpha') | Out-Null
Set-Content -LiteralPath (At 'Mods/Source/alpha/owner.cs') 'owner source'
Operation 'InstallMod' 'alpha' (Stage 'alpha' '2') 'Binaries'
Check ((Get-Content -LiteralPath (At 'Mods/Binaries/alpha/mod.json') -Raw | ConvertFrom-Json).version -eq '2') 'update installs the new version'
Check (-not (Test-Path -LiteralPath (At 'Mods/Source/alpha'))) 'binary update retires the source that could overwrite it'
Check ((Get-Content -LiteralPath (At 'Mods/Binaries/alpha/alpha.json') -Raw | ConvertFrom-Json).quantity -eq 4) 'upgrade preserves installed mod settings'

Check (@(Get-ChildItem -LiteralPath (At 'Mods/.replaced') -Recurse -Filter owner.cs).Count -eq 1) 'retired source remains recoverable'
Check (@(Get-ChildItem -LiteralPath (At 'Mods/.replaced') -Recurse -Filter alpha.dll | Where-Object { [IO.File]::ReadAllText($_.FullName) -eq 'inert fixture 1' }).Count -eq 1) 'previous binary remains recoverable'
Check ([IO.File]::ReadAllText((At 'Mods/Binaries/mod-state.txt')).Contains('alpha off')) 'update preserves disabled choices'
Expand Down
Loading