Skip to content
Open
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
11 changes: 9 additions & 2 deletions (S)NES Mini - Lua Compiler.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,17 @@
</ItemGroup>

<PropertyGroup>
<!-- Which native tools (LuaJIT + decompiler) get embedded. Override with -p:TargetOs=linux|windows. -->
<!-- Which native tools (LuaJIT + decompiler) get embedded. Override with -p:TargetOs=linux|windows|macos. -->
<TargetOs Condition="'$(TargetOs)' == '' And $([MSBuild]::IsOSPlatform('Windows'))">windows</TargetOs>
<TargetOs Condition="'$(TargetOs)' == '' And $([MSBuild]::IsOSPlatform('OSX'))">macos</TargetOs>
<TargetOs Condition="'$(TargetOs)' == ''">linux</TargetOs>
</PropertyGroup>

<!-- Resources are named Lib/<path> (real path, so files without extension work).
Lib\luajit-linux and Lib\decompiler-linux are embedded as Lib/luajit and Lib/decompiler on Linux. -->
<ItemGroup>
<EmbeddedResource Include="Lib\**"
Exclude="Lib\luajit\**;Lib\decompiler\**;Lib\luajit-linux\**;Lib\decompiler-linux\**"
Exclude="Lib\luajit\**;Lib\decompiler\**;Lib\luajit-linux\**;Lib\decompiler-linux\**;Lib\luajit-macos\**;Lib\decompiler-macos\**"
LogicalName="Lib/%(RecursiveDir)%(Filename)%(Extension)" />
<EmbeddedResource Include="Lib\luajit\**" Condition="'$(TargetOs)' == 'windows'"
LogicalName="Lib/luajit/%(RecursiveDir)%(Filename)%(Extension)" />
Expand All @@ -53,6 +54,10 @@
LogicalName="Lib/luajit/%(RecursiveDir)%(Filename)%(Extension)" />
<EmbeddedResource Include="Lib\decompiler-linux\**" Condition="'$(TargetOs)' == 'linux'"
LogicalName="Lib/decompiler/%(RecursiveDir)%(Filename)%(Extension)" />
<EmbeddedResource Include="Lib\luajit-macos\**" Condition="'$(TargetOs)' == 'macos'"
LogicalName="Lib/luajit/%(RecursiveDir)%(Filename)%(Extension)" />
<EmbeddedResource Include="Lib\decompiler-macos\**" Condition="'$(TargetOs)' == 'macos'"
LogicalName="Lib/decompiler/%(RecursiveDir)%(Filename)%(Extension)" />
</ItemGroup>

<ItemGroup>
Expand All @@ -64,8 +69,10 @@
<PrivateAssets Condition="'$(Configuration)' != 'Debug'">All</PrivateAssets>
</PackageReference>
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0" />
<PackageReference Include="LTRData.DiscUtils.SquashFs" Version="1.0.90" />
<PackageReference Include="Lucide.Avalonia" Version="0.2.28" />
<PackageReference Include="Semi.Avalonia" Version="11.3.7" />
<PackageReference Include="SharpCompress" Version="0.50.5" />
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
<!-- Avalonia pulls in 0.21.2 (GHSA-xrw6-gwf8-vvr9); 0.21.3 is the patched release of the same line -->
<PackageReference Include="Tmds.DBus.Protocol" Version="0.21.3" />
Expand Down
54 changes: 54 additions & 0 deletions Firmware/ConsoleLayout.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using SNESMiniLuaCompiler.Models;

namespace SNESMiniLuaCompiler.Firmware
{
/// <summary>
/// Where a console keeps its Lua files inside its firmware, the folder the app uses for that console, and how
/// to recognise its files. The firmware paths are the ones of the original firmware images (the same registry
/// the MiniThemeStudio uses).
/// </summary>
/// <param name="DisplayName">The name of the console.</param>
/// <param name="FolderName">The folder of the console in the app.</param>
/// <param name="UiPath">The UI folder in the firmware.</param>
/// <param name="FolderAliases">Names a folder of this console is known by (normalised: lower case, no - _ or space).</param>
/// <param name="RequiredFile">A file only this family of consoles has, relative to the resources folder.</param>
/// <param name="ForbiddenFile">A file that shows the files are of a sister console, relative to the resources folder.</param>
internal sealed record ConsoleLayout(
string DisplayName,
string FolderName,
string UiPath,
IReadOnlyList<string> FolderAliases,
string RequiredFile,
string? ForbiddenFile = null)
{
private const string SnesPalette = "scripts/env/colors_usa.lua";

public static IReadOnlyList<SystemModel> All { get; } = Enum.GetValues<SystemModel>();

public static ConsoleLayout For(SystemModel system) => system switch
{
SystemModel.Nes => new("NES Classic Edition", "nes", "usr/share/clover-ui", ["nes"], "scripts/colors_nes.lua"),
SystemModel.Famicom => new("Famicom Mini", "hvc", "usr/share/clover-ui", ["hvc", "famicom"], "scripts/colors_hvc.lua", "scripts/constants.lua"),
SystemModel.Shonen => new("Famicom Shonen Jump 50th", "hvcj", "usr/share/ui/hvc", ["hvcj", "hvcjshonen", "shonen"], "scripts/constants.lua"),
SystemModel.SuperFamicom => new("Super Famicom", "shvc", "usr/share/ui/shvc", ["shvc", "superfamicom"], SnesPalette),
SystemModel.SnesPal => new("SNES Mini (Europe)", "snes-eur", "usr/share/ui/snes-eur", ["sneseur"], SnesPalette),
_ => new("SNES Mini (USA)", "snes-usa", "usr/share/ui/snes-usa", ["snesusa", "snes"], SnesPalette),
};

/// <summary>
/// Folders of a console where the UI can be read: the untouched original first, then the live one
/// (with hakchi, an installed theme is mounted over the live folder).
/// </summary>
public IReadOnlyList<string> ConsolePaths => [$"/var/squashfs/{UiPath}", $"/{UiPath}"];

/// <summary>Is <paramref name="folderName"/> the name of a folder of this console (hvc, snesusa, snes-usa...)?</summary>
public bool MatchesFolderName(string folderName) =>
FolderAliases.Contains(Normalize(folderName));

private static string Normalize(string name) =>
new string(name.Where(c => c is not ('-' or '_' or ' ')).ToArray()).ToLowerInvariant();
}
}
94 changes: 94 additions & 0 deletions Firmware/ConsoleSsh.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace SNESMiniLuaCompiler.Firmware
{
/// <summary>Reads the Lua files of a console over SSH (hakchi), with the ssh client of the system and tar on the console.</summary>
internal static class ConsoleSsh
{
/// <summary>The address of a console connected by USB (hakchi).</summary>
public const string UsbHost = "169.254.13.37";

public static bool IsValidHost(string host) =>
host.Length is > 0 and <= 253 && !host.StartsWith('-') && host.All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '-' or ':' or '_');

public static async Task DownloadLuaAsync(string host, ConsoleTarget target, CancellationToken cancellationToken)
{
ConsoleLayout layout = target.Layout;
if (!IsValidHost(host))
throw new ArgumentException("That is not a valid address.", nameof(host));

string? folder = null;
foreach (string candidate in layout.ConsolePaths)
{
if (await RunAsync(host, $"test -d {Quote(candidate)}", cancellationToken) == 0)
{
folder = candidate;
break;
}
}

if (folder is null)
throw new InvalidDataException($"The console at {host} has no {layout.UiPath} folder. Is it the console you picked?");

// only the Lua files travel: the UI folder also holds the images, fonts and sounds
using Process process = Start(host, $"cd {Quote(folder)} && tar -cf - $(find resources -type f -name '*.lua')");
Task<string> error = process.StandardError.ReadToEndAsync(cancellationToken);
await Task.Run(() => LuaSourceReader.ExtractFromTar(process.StandardOutput.BaseStream, target, cancellationToken), cancellationToken);

// tar pads the archive after its end marker: read it, or ssh blocks writing it and never exits
await process.StandardOutput.BaseStream.CopyToAsync(Stream.Null, cancellationToken);
await process.WaitForExitAsync(cancellationToken);

if (process.ExitCode != 0)
throw new IOException($"The console did not send the files (ssh exit code {process.ExitCode}): {(await error).Trim()}");
}

private static async Task<int> RunAsync(string host, string command, CancellationToken cancellationToken)
{
using Process process = Start(host, command);
Task<string> output = process.StandardOutput.ReadToEndAsync(cancellationToken);
Task<string> error = process.StandardError.ReadToEndAsync(cancellationToken);
await process.WaitForExitAsync(cancellationToken);
await Task.WhenAll(output, error);

// 255 is ssh itself failing: no route to the host, a refused login...
if (process.ExitCode == 255)
throw new IOException($"Could not connect to {host}: {error.Result.Trim()}");

return process.ExitCode;
}

private static Process Start(string host, string command)
{
var startInfo = new ProcessStartInfo("ssh")
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
};

foreach (string argument in new[] { "-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "-o", "StrictHostKeyChecking=accept-new", "-p", "22", $"root@{host}", command })
startInfo.ArgumentList.Add(argument);

try
{
return Process.Start(startInfo) ?? throw new InvalidOperationException("Could not start the ssh client.");
}
catch (Win32Exception exception)
{
throw new InvalidOperationException(
"The OpenSSH client (ssh) was not found. On Windows it is an optional feature (Settings > Apps > Optional features > OpenSSH Client); on Linux install openssh-client.",
exception);
}
}

private static string Quote(string value) => $"'{value.Replace("'", "'\"'\"'", StringComparison.Ordinal)}'";
}
}
28 changes: 28 additions & 0 deletions Firmware/ConsoleTarget.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using SNESMiniLuaCompiler.Models;

namespace SNESMiniLuaCompiler.Firmware
{
/// <summary>One console an import tries to fill: where its files are collected, and what was found for it.</summary>
internal sealed class ConsoleTarget(SystemModel system, ConsoleLayout layout)
{
public ConsoleTarget(SystemModel system)
: this(system, ConsoleLayout.For(system))
{
}

public SystemModel System { get; } = system;

public ConsoleLayout Layout { get; } = layout;

/// <summary>The folder the Lua files are collected in until the import is known to be good.</summary>
public string Staging { get; } = OriginalsStore.NewStagingPath();

public ImportResult Result { get; } = new();

/// <summary>Did the source have files for this console?</summary>
public bool Found { get; set; }

/// <summary>Why not, when it matters (the console the user asked for).</summary>
public string? NotFoundMessage { get; set; }
}
}
10 changes: 10 additions & 0 deletions Firmware/ImportResult.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace SNESMiniLuaCompiler.Firmware
{
/// <summary>What an import found: the Lua files it kept and the ones it skipped because they are not LuaJIT bytecode.</summary>
internal sealed class ImportResult
{
public int Files { get; set; }

public int NotBytecode { get; set; }
}
}
Loading
Loading