mirror of
https://github.com/MaSzyna-EU07/StarterNG.git
synced 2026-11-19 15:02:15 +01:00
Add graphics levels, screen choices and the rest of the simulator's keys
Six levels of detail climbing in even steps, High being where a player with no settings of their own starts. Five parts of the picture can also take a level of their own. Resolutions start from the monitors in the computer. uartfeature with nothing selected writes "no no no no"; uart and uarttune are written whole or not at all. On Linux the file's contents tell a Windows build, a native one and a script from a note that merely has the execute bit.
This commit is contained in:
16
StarterNG/Infrastructure/CpuFeatures.cs
Normal file
16
StarterNG/Infrastructure/CpuFeatures.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Intrinsics.X86;
|
||||
|
||||
namespace StarterNG.Infrastructure;
|
||||
|
||||
/// <summary>What the processor offers against what the simulator builds assume.</summary>
|
||||
public static class CpuFeatures
|
||||
{
|
||||
/// <summary>
|
||||
/// The simulator's CMakeLists has ENABLE_AVX2 on by default since May 2026, so
|
||||
/// the published builds stop at the first AVX2 instruction on an older x86
|
||||
/// processor. Other architectures cannot run them at all, which is not this.
|
||||
/// </summary>
|
||||
public static bool LacksAvx2 =>
|
||||
RuntimeInformation.ProcessArchitecture is Architecture.X64 or Architecture.X86 && !Avx2.IsSupported;
|
||||
}
|
||||
188
StarterNG/Infrastructure/Displays.cs
Normal file
188
StarterNG/Infrastructure/Displays.cs
Normal file
@@ -0,0 +1,188 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.RegularExpressions;
|
||||
using StarterNG.Application.Abstractions;
|
||||
|
||||
namespace StarterNG.Infrastructure;
|
||||
|
||||
/// <summary>A screen, and the fastest it refreshes.</summary>
|
||||
/// <param name="Name">The connector on Linux (eDP-1, HDMI-A-1); empty for the primary screen on Windows.</param>
|
||||
public sealed record Display(string Name, int RefreshRate);
|
||||
|
||||
/// <summary>
|
||||
/// The screens attached, for a frame rate limit to match: on Linux from the EDID
|
||||
/// each connected connector of /sys/class/drm passes on - the most the panel can
|
||||
/// do, which the desktop may not be using - and on Windows the primary screen's
|
||||
/// current mode.
|
||||
/// </summary>
|
||||
public sealed class Displays
|
||||
{
|
||||
private const string DrmClass = "/sys/class/drm";
|
||||
|
||||
private static readonly Regex Connector = new(@"^card\d+-(.+)$", RegexOptions.CultureInvariant);
|
||||
|
||||
private readonly IFileSystem _files;
|
||||
private readonly IEnvironment _environment;
|
||||
|
||||
public Displays(IFileSystem files, IEnvironment environment)
|
||||
{
|
||||
_files = files;
|
||||
_environment = environment;
|
||||
}
|
||||
|
||||
/// <summary>Every screen whose refresh rate could be read; empty where none could.</summary>
|
||||
public IReadOnlyList<Display> List()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_environment.IsLinux)
|
||||
return FromDrm();
|
||||
if (_environment.IsWindows && OperatingSystem.IsWindows())
|
||||
return PrimaryOnWindows() is { } rate ? new[] { new Display(string.Empty, rate) } : Array.Empty<Display>();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// A screen we cannot read leaves the limit to the player, as before.
|
||||
}
|
||||
|
||||
return Array.Empty<Display>();
|
||||
}
|
||||
|
||||
private IReadOnlyList<Display> FromDrm()
|
||||
{
|
||||
var displays = new List<Display>();
|
||||
foreach (string directory in _files.GetDirectories(DrmClass))
|
||||
{
|
||||
var match = Connector.Match(Path.GetFileName(directory));
|
||||
if (!match.Success || match.Groups[1].Value.StartsWith("Writeback", StringComparison.Ordinal))
|
||||
continue;
|
||||
|
||||
try
|
||||
{
|
||||
string status = Path.Combine(directory, "status");
|
||||
if (!_files.FileExists(status) || _files.ReadAllText(status).Trim() != "connected")
|
||||
continue;
|
||||
int rate = Edid.HighestRefreshRate(_files.ReadAllBytes(Path.Combine(directory, "edid")));
|
||||
if (rate > 0)
|
||||
displays.Add(new Display(match.Groups[1].Value, rate));
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// One connector we cannot read says nothing of the others.
|
||||
}
|
||||
}
|
||||
|
||||
return displays;
|
||||
}
|
||||
|
||||
// DEVMODEW: dmSize at 68, dmDisplayFrequency at 184, 220 bytes with no driver data.
|
||||
private const int DevModeSize = 220;
|
||||
private const int DevModeSizeOffset = 68;
|
||||
private const int DisplayFrequencyOffset = 184;
|
||||
private const int CurrentSettings = -1;
|
||||
|
||||
[DllImport("user32.dll", ExactSpelling = true)]
|
||||
private static extern int EnumDisplaySettingsW(IntPtr deviceName, int modeNum, IntPtr devMode);
|
||||
|
||||
private static int? PrimaryOnWindows()
|
||||
{
|
||||
IntPtr mode = Marshal.AllocHGlobal(DevModeSize);
|
||||
try
|
||||
{
|
||||
for (int i = 0; i < DevModeSize; i++)
|
||||
Marshal.WriteByte(mode, i, 0);
|
||||
Marshal.WriteInt16(mode, DevModeSizeOffset, DevModeSize);
|
||||
if (EnumDisplaySettingsW(IntPtr.Zero, CurrentSettings, mode) == 0)
|
||||
return null;
|
||||
int rate = Marshal.ReadInt32(mode, DisplayFrequencyOffset);
|
||||
// 0 and 1 stand for the hardware's default rate.
|
||||
return rate > 1 ? rate : null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.FreeHGlobal(mode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The timings an EDID lists, as far as a refresh rate goes.</summary>
|
||||
public static class Edid
|
||||
{
|
||||
/// <summary>The fastest refresh rate among the detailed timings, rounded; 0 for none.</summary>
|
||||
public static int HighestRefreshRate(byte[] edid)
|
||||
{
|
||||
if (edid.Length < 128)
|
||||
return 0;
|
||||
|
||||
// The base block's four descriptors.
|
||||
double best = 0;
|
||||
for (int at = 54; at + 18 <= 126; at += 18)
|
||||
best = Math.Max(best, DetailedTiming(edid, at));
|
||||
|
||||
for (int block = 128; block + 128 <= edid.Length; block += 128)
|
||||
{
|
||||
switch (edid[block])
|
||||
{
|
||||
// CTA-861: detailed timings from the offset in its third byte on.
|
||||
case 0x02 when edid[block + 2] >= 4:
|
||||
for (int at = block + edid[block + 2]; at + 18 <= block + 127; at += 18)
|
||||
best = Math.Max(best, DetailedTiming(edid, at));
|
||||
break;
|
||||
// DisplayID, where a panel faster than 60 Hz often keeps its only fast mode.
|
||||
case 0x70:
|
||||
best = Math.Max(best, DisplayId(edid, block));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return (int)Math.Round(best);
|
||||
}
|
||||
|
||||
// An 18-byte detailed timing; a pixel clock of zero marks some other descriptor.
|
||||
private static double DetailedTiming(byte[] e, int at)
|
||||
{
|
||||
int clock = e[at] | e[at + 1] << 8;
|
||||
if (clock == 0)
|
||||
return 0;
|
||||
|
||||
int hActive = e[at + 2] | (e[at + 4] & 0xF0) << 4, hBlank = e[at + 3] | (e[at + 4] & 0x0F) << 8;
|
||||
int vActive = e[at + 5] | (e[at + 7] & 0xF0) << 4, vBlank = e[at + 6] | (e[at + 7] & 0x0F) << 8;
|
||||
return Rate(clock * 10_000.0, hActive + hBlank, vActive + vBlank);
|
||||
}
|
||||
|
||||
// Data blocks from the sixth byte on; type I timings (DisplayID 1.3) count the
|
||||
// pixel clock in 10 kHz, type VII (2.0) in kHz, and both store each size less one.
|
||||
private static double DisplayId(byte[] e, int block)
|
||||
{
|
||||
double best = 0;
|
||||
int end = Math.Min(block + 5 + e[block + 2], block + 127);
|
||||
for (int at = block + 5; at + 3 <= end;)
|
||||
{
|
||||
int tag = e[at], length = e[at + 2];
|
||||
if (tag == 0 && length == 0)
|
||||
break;
|
||||
|
||||
int payload = at + 3;
|
||||
if (tag is 0x03 or 0x22)
|
||||
{
|
||||
for (int t = payload; t + 20 <= Math.Min(payload + length, end); t += 20)
|
||||
{
|
||||
double clock = (e[t] | e[t + 1] << 8 | e[t + 2] << 16) + 1;
|
||||
clock *= tag == 0x03 ? 10_000 : 1_000;
|
||||
int hTotal = (e[t + 4] | e[t + 5] << 8) + 1 + (e[t + 6] | e[t + 7] << 8) + 1;
|
||||
int vTotal = (e[t + 12] | e[t + 13] << 8) + 1 + (e[t + 14] | e[t + 15] << 8) + 1;
|
||||
best = Math.Max(best, Rate(clock, hTotal, vTotal));
|
||||
}
|
||||
}
|
||||
|
||||
at = payload + length;
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
private static double Rate(double pixelClock, int hTotal, int vTotal) =>
|
||||
hTotal > 0 && vTotal > 0 ? pixelClock / ((double)hTotal * vTotal) : 0;
|
||||
}
|
||||
74
StarterNG/Infrastructure/LinuxGpus.cs
Normal file
74
StarterNG/Infrastructure/LinuxGpus.cs
Normal file
@@ -0,0 +1,74 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using StarterNG.Application.Abstractions;
|
||||
using StarterNG.Domain.Settings;
|
||||
|
||||
namespace StarterNG.Infrastructure;
|
||||
|
||||
/// <summary>
|
||||
/// The graphics cards of a Linux machine, read from /sys/class/drm - which the
|
||||
/// Steam Linux Runtime container shows too, unlike some of the host's tools.
|
||||
/// </summary>
|
||||
public sealed class LinuxGpus
|
||||
{
|
||||
private const string DrmClass = "/sys/class/drm";
|
||||
|
||||
// card0 and card1, not their connectors (card0-eDP-2) or render nodes.
|
||||
private static readonly Regex Card = new(@"^card\d+$", RegexOptions.CultureInvariant);
|
||||
|
||||
// The connectors of a laptop's own screen, listed whether lit or not.
|
||||
private static readonly Regex Panel = new(@"^(card\d+)-(eDP|LVDS|DSI)-\d+$", RegexOptions.CultureInvariant);
|
||||
|
||||
private readonly IFileSystem _files;
|
||||
private readonly IEnvironment _environment;
|
||||
|
||||
public LinuxGpus(IFileSystem files, IEnvironment environment)
|
||||
{
|
||||
_files = files;
|
||||
_environment = environment;
|
||||
}
|
||||
|
||||
/// <summary>Every card with a PCI address and a driver; empty off Linux, or when /sys cannot be read.</summary>
|
||||
public IReadOnlyList<GpuDevice> List()
|
||||
{
|
||||
if (!_environment.IsLinux)
|
||||
return Array.Empty<GpuDevice>();
|
||||
|
||||
try
|
||||
{
|
||||
var gpus = new List<GpuDevice>();
|
||||
var entries = _files.GetDirectories(DrmClass).Select(Path.GetFileName).OfType<string>().ToList();
|
||||
var withPanel = entries.Select(e => Panel.Match(e)).Where(m => m.Success)
|
||||
.Select(m => m.Groups[1].Value).ToHashSet(StringComparer.Ordinal);
|
||||
foreach (string name in entries.Where(e => Card.IsMatch(e)))
|
||||
{
|
||||
string card = Path.Combine(DrmClass, name);
|
||||
string device = Path.Combine(card, "device");
|
||||
string uevent = Path.Combine(device, "uevent");
|
||||
if (!_files.FileExists(uevent))
|
||||
continue;
|
||||
|
||||
var fields = _files.ReadAllLines(uevent)
|
||||
.Select(line => line.Split('=', 2))
|
||||
.Where(pair => pair.Length == 2)
|
||||
.ToDictionary(pair => pair[0], pair => pair[1].Trim(), StringComparer.Ordinal);
|
||||
if (!fields.TryGetValue("PCI_SLOT_NAME", out string? slot) ||
|
||||
!fields.TryGetValue("PCI_ID", out string? id))
|
||||
continue;
|
||||
|
||||
string bootVga = Path.Combine(device, "boot_vga");
|
||||
bool boot = _files.FileExists(bootVga) && _files.ReadAllText(bootVga).Trim() == "1";
|
||||
gpus.Add(new GpuDevice(slot, id, fields.GetValueOrDefault("DRIVER", ""), boot, withPanel.Contains(name)));
|
||||
}
|
||||
|
||||
return gpus.OrderBy(g => g.Slot, StringComparer.Ordinal).ToList();
|
||||
}
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return Array.Empty<GpuDevice>();
|
||||
}
|
||||
}
|
||||
}
|
||||
47
StarterNG/Infrastructure/SerialPorts.cs
Normal file
47
StarterNG/Infrastructure/SerialPorts.cs
Normal file
@@ -0,0 +1,47 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.Versioning;
|
||||
|
||||
namespace StarterNG.Infrastructure;
|
||||
|
||||
/// <summary>The serial ports present now, named the way the simulator's uart key wants them.</summary>
|
||||
public static class SerialPorts
|
||||
{
|
||||
// USB adapters and boards; the legacy ttyS ports exist on every PC whether
|
||||
// wired or not, so they would only crowd the list.
|
||||
private static readonly string[] UnixPatterns = { "ttyUSB*", "ttyACM*", "ttyAMA*", "rfcomm*", "cu.*" };
|
||||
|
||||
public static IReadOnlyList<string> List()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (OperatingSystem.IsWindows())
|
||||
return FromRegistry();
|
||||
|
||||
return UnixPatterns
|
||||
.SelectMany(pattern => Directory.GetFiles("/dev", pattern))
|
||||
.OrderBy(p => p, StringComparer.Ordinal)
|
||||
.ToList();
|
||||
}
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException or System.Security.SecurityException)
|
||||
{
|
||||
return Array.Empty<string>();
|
||||
}
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static IReadOnlyList<string> FromRegistry()
|
||||
{
|
||||
using var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"HARDWARE\DEVICEMAP\SERIALCOMM");
|
||||
if (key is null)
|
||||
return Array.Empty<string>();
|
||||
var ports = new List<string>();
|
||||
foreach (string name in key.GetValueNames())
|
||||
if (key.GetValue(name) is string port)
|
||||
ports.Add(port);
|
||||
// COM3 before COM10.
|
||||
return ports.OrderBy(p => p.Length).ThenBy(p => p, StringComparer.OrdinalIgnoreCase).ToList();
|
||||
}
|
||||
}
|
||||
@@ -124,6 +124,9 @@ public sealed class ExecutableLocator
|
||||
if (!_files.FileExists(path))
|
||||
return ExeProblem.NotFound;
|
||||
|
||||
if (_environment.IsLinux && Format(path) == BinaryFormat.Unknown)
|
||||
return ExeProblem.NotAProgram;
|
||||
|
||||
bool foreign = !MatchesPlatform(path);
|
||||
|
||||
// Started through Wine, a Windows build needs no execute bit of its own.
|
||||
@@ -183,7 +186,8 @@ public sealed class ExecutableLocator
|
||||
return null;
|
||||
}
|
||||
|
||||
private bool RunsThroughWine(string path)
|
||||
/// <summary>Whether <paramref name="path"/> is a Windows build the starter hands to Wine.</summary>
|
||||
public bool RunsThroughWine(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -206,7 +210,8 @@ public sealed class ExecutableLocator
|
||||
{
|
||||
Unknown,
|
||||
Elf,
|
||||
PortableExecutable
|
||||
PortableExecutable,
|
||||
Script
|
||||
}
|
||||
|
||||
private BinaryFormat Format(string path)
|
||||
@@ -220,10 +225,26 @@ public sealed class ExecutableLocator
|
||||
return BinaryFormat.PortableExecutable;
|
||||
if (head[0] == 0x7F && head[1] == 0x45 && head[2] == 0x4C && head[3] == 0x46)
|
||||
return BinaryFormat.Elf;
|
||||
if (head[0] == (byte)'#' && head[1] == (byte)'!')
|
||||
return BinaryFormat.Script;
|
||||
|
||||
return BinaryFormat.Unknown;
|
||||
}
|
||||
|
||||
// Linux starts nothing else, and on a Windows partition every file has the execute
|
||||
// bit: only what is inside tells a program from a note called eu07_todo.
|
||||
private bool IsProgramOnLinux(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Format(path) != BinaryFormat.Unknown;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsExeOnLinux(string path) =>
|
||||
_environment.IsLinux && string.Equals(Path.GetExtension(path), ".exe", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
@@ -240,12 +261,34 @@ public sealed class ExecutableLocator
|
||||
// A Windows build is offered only where Wine can start it, and after any
|
||||
// native one - see the ordering in Resolve.
|
||||
if (_environment.IsLinux)
|
||||
return extension.Length == 0 || extension is ".x86_64" or ".run" or ".appimage" ||
|
||||
(IsExeOnLinux(path) && Wine() is not null);
|
||||
return (extension.Length == 0 || extension is ".x86_64" or ".run" or ".appimage" ||
|
||||
(IsExeOnLinux(path) && Wine() is not null)) && IsProgramOnLinux(path);
|
||||
|
||||
return extension.Length == 0 || extension is ".exe" or ".x86_64" or ".run" or ".appimage";
|
||||
}
|
||||
|
||||
private string FullPath(string path) =>
|
||||
/// <summary>A path as <see cref="Resolve"/> gives it, which may be relative to the installation.</summary>
|
||||
public string FullPath(string path) =>
|
||||
Path.IsPathRooted(path) ? path : Path.Combine(_paths.Root, path);
|
||||
|
||||
/// <summary>
|
||||
/// Whether the binary is a Windows build, which runs the Windows code of the
|
||||
/// simulator even under Wine. One that cannot be read is taken to suit the host.
|
||||
/// </summary>
|
||||
public bool IsWindowsBuild(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Format(FullPath(path)) switch
|
||||
{
|
||||
BinaryFormat.PortableExecutable => true,
|
||||
BinaryFormat.Elf => false,
|
||||
_ => _environment.IsWindows
|
||||
};
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return _environment.IsWindows;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@@ -17,13 +16,16 @@ public sealed class SettingsSerializer
|
||||
s.Language = s.LanguageCode;
|
||||
s.Fullscreen = c.GetBool("fullscreen", false);
|
||||
s.PauseWhenInactive = c.GetBool("inactivepause", true);
|
||||
s.NetworkServer = c.Has("network.server");
|
||||
s.FpsAverage = c.GetDouble("fpsaverage", 0);
|
||||
s.PauseOnStart = c.GetBool("pause", false);
|
||||
|
||||
var mouse = c.GetTokens("mousescale");
|
||||
if (mouse.Length >= 1 && double.TryParse(mouse[0], NumberStyles.Float, CultureInfo.InvariantCulture, out double mx))
|
||||
{
|
||||
s.InvertMouseHorizontal = mx < 0;
|
||||
s.CursorSensitivity = Clamp((int)Math.Round(Math.Abs(mx)), 1, 5);
|
||||
s.MouseScaleXMagnitude = Math.Abs(mx);
|
||||
s.CursorSensitivity = SensitivityStep(mx);
|
||||
}
|
||||
if (mouse.Length >= 2 && double.TryParse(mouse[1], NumberStyles.Float, CultureInfo.InvariantCulture, out double my))
|
||||
{
|
||||
@@ -35,20 +37,27 @@ public sealed class SettingsSerializer
|
||||
s.FeedbackMode = Clamp(c.GetInt("feedbackmode", 1), 0, 5);
|
||||
s.FeedbackPort = c.GetInt("feedbackport", 888);
|
||||
s.UartEnabled = c.Has("uart");
|
||||
s.UartPort = c.GetString("uart", "");
|
||||
s.UartTune = c.GetString("uarttune", "");
|
||||
var uart = c.GetTokens("uart");
|
||||
s.UartPort = uart.ElementAtOrDefault(0) ?? "";
|
||||
s.UartBaud = ParseInt(uart.ElementAtOrDefault(1) ?? "", 0) is > 0 and var baud ? baud : Uart.DefaultBaud;
|
||||
s.UartUpdateTime = uart.Length >= 3 &&
|
||||
double.TryParse(uart[2], NumberStyles.Float, CultureInfo.InvariantCulture, out double every) &&
|
||||
every >= 0
|
||||
? every
|
||||
: Uart.DefaultUpdateTime;
|
||||
s.UartTune = Uart.TuneInFile(c.GetString("uarttune", ""));
|
||||
s.UartDebug = c.GetBool("uartdebug", false);
|
||||
if (c.Has("uartfeature"))
|
||||
{
|
||||
var uartTokens = (c.GetRaw("uartfeature") ?? "").Split('|', StringSplitOptions.RemoveEmptyEntries);
|
||||
var uf = new HashSet<string>(uartTokens, StringComparer.OrdinalIgnoreCase);
|
||||
var uf = Uart.FeaturesOn(c.GetRaw("uartfeature"));
|
||||
s.UartMain = uf.Contains("main"); s.UartScnd = uf.Contains("scnd"); s.UartTrain = uf.Contains("train");
|
||||
s.UartLocal = uf.Contains("local"); s.UartRadioVolume = uf.Contains("radiovolume"); s.UartRadioChannel = uf.Contains("radiochannel");
|
||||
s.UartDynamicBrake = uf.Contains("dynamicbrake");
|
||||
}
|
||||
else
|
||||
{
|
||||
s.UartMain = s.UartScnd = s.UartTrain = s.UartLocal = true;
|
||||
s.UartRadioVolume = s.UartRadioChannel = false;
|
||||
s.UartRadioVolume = s.UartRadioChannel = s.UartDynamicBrake = false;
|
||||
}
|
||||
|
||||
s.SelectExeAutomatically = c.GetBool("starter.exe.auto", true);
|
||||
@@ -56,16 +65,15 @@ public sealed class SettingsSerializer
|
||||
s.DebugMode = c.GetBool("debugmode", false);
|
||||
s.VirtualShunting = c.GetBool("ai.trainman", true);
|
||||
s.LogMissingVehicleFiles = c.GetBool("starter.logmissingvehicles", false);
|
||||
s.DeveloperTools = c.GetBool("starter.developertools", false);
|
||||
|
||||
s.RenderEngine = IndexOf(SimulatorSettings.RenderEngines, c.GetString("gfxrenderer", "full"), 0);
|
||||
s.RenderEngine = SimulatorSettings.RenderEngineOf(c.GetString("gfxrenderer", "full"));
|
||||
s.Width = c.GetInt("width", 1280);
|
||||
s.Height = c.GetInt("height", 720);
|
||||
s.BufferScalePercent = Clamp(c.GetInt("starter.bufferscale", 100), 50, 200);
|
||||
s.MaxTextureSize = c.GetInt("maxtexturesize", 4096);
|
||||
s.MaxCabTextureSize = c.GetInt("maxcabtexturesize", 4096);
|
||||
s.TextureFiltering = c.GetInt("anisotropicfiltering", 8);
|
||||
s.Multisampling = Clamp(c.GetInt("multisampling", 2), 0, 3);
|
||||
s.TextureFiltering = Math.Max(1, c.GetDouble("anisotropicfiltering", 8));
|
||||
s.Multisampling = Clamp(c.GetInt("multisampling", 2), 0, 4);
|
||||
s.DynamicLights = Clamp(c.GetInt("dynamiclights", 7), 0, 7);
|
||||
s.DrawRangeFactor = c.GetDouble("gfx.drawrange.factor.max", 3.0);
|
||||
s.VSync = c.GetBool("vsync", false);
|
||||
@@ -77,21 +85,27 @@ public sealed class SettingsSerializer
|
||||
s.EnvMap = c.GetBool("gfx.envmap.enabled", true);
|
||||
s.UseVbo = c.GetBool("usevbo", true);
|
||||
s.RenderShadows = c.GetBool("shadows", true);
|
||||
s.ReflectionsFramerate = c.GetInt("gfx.reflections.framerate", 60);
|
||||
// A negative rate counts as its size; none at all, as never.
|
||||
double reflections = Math.Abs(c.GetDouble("gfx.reflections.framerate", 1 / 300.0));
|
||||
s.ReflectionsFramerate = reflections > 0 ? reflections : 1 / 300.0;
|
||||
|
||||
// map size, unread, projection range, unread
|
||||
var shadowTune = c.GetTokens("shadowtune");
|
||||
if (shadowTune.Length >= 1) s.ShadowMapResolution = ParseInt(shadowTune[0], 2048);
|
||||
if (shadowTune.Length >= 2) s.ShadowProjectionRange = ParseInt(shadowTune[1], 250);
|
||||
if (shadowTune.Length >= 4) s.ShadowTuneExtra = new[] { shadowTune[2], shadowTune[3] };
|
||||
if (shadowTune.Length >= 3) s.ShadowProjectionRange = (int)Math.Round(ParseDouble(shadowTune[2], 250));
|
||||
if (shadowTune.Length >= 2) s.ShadowTuneUnused[0] = shadowTune[1];
|
||||
if (shadowTune.Length >= 4) s.ShadowTuneUnused[1] = shadowTune[3];
|
||||
|
||||
s.CabShadowsRange = (int)Math.Round(c.GetDouble("gfx.shadows.cab.range", 0));
|
||||
s.ShadowRankCutoff = c.GetInt("gfx.shadow.rank.cutoff", 3);
|
||||
s.ReflectionsFidelity = Clamp(c.GetInt("gfx.reflections.fidelity", 0), 0, 2);
|
||||
s.FieldOfView = Clamp((int)Math.Round(c.GetDouble("fieldofview", 45)), 15, 75);
|
||||
s.FieldOfView = Clamp((int)Math.Round(c.GetDouble("fieldofview", 45)), 10, 75);
|
||||
s.PythonScreens = c.GetBool("python.enabled", true);
|
||||
s.PythonThreadedUpload = c.GetBool("python.threadedupload", true);
|
||||
s.FpsLimitEnabled = c.Has("fpslimit");
|
||||
s.FpsLimit = Clamp(c.GetInt("fpslimit", 30), 1, 100);
|
||||
// The simulator takes any rate above zero; at or below it, no limit.
|
||||
double fpsLimit = c.GetDouble("fpslimit", 0);
|
||||
s.FpsLimitEnabled = fpsLimit > 0;
|
||||
if (s.FpsLimitEnabled) s.FpsLimit = fpsLimit;
|
||||
s.ShadowAngleLimit = c.GetDouble("gfx.shadow.angle.min", 0.2);
|
||||
s.FullscreenWindowed = c.GetBool("fullscreenwindowed", false);
|
||||
s.RenderAngleVulkan = string.Equals(c.GetString("gfx.angleplatform", ""), "vulkan", StringComparison.OrdinalIgnoreCase);
|
||||
@@ -113,11 +127,11 @@ public sealed class SettingsSerializer
|
||||
s.BrakeSpeed = c.GetDouble("brakespeed", 3.0);
|
||||
|
||||
s.SoundEnabled = c.GetBool("soundenabled", true);
|
||||
s.Volume = Clamp((int)Math.Round(c.GetDouble("sound.volume", 1.0) * 50), 1, 100);
|
||||
s.RadioVolume = Clamp((int)Math.Round(c.GetDouble("sound.volume.radio", 0.75) * 100), 1, 100);
|
||||
s.VehiclesVolume = Clamp((int)Math.Round(c.GetDouble("sound.volume.vehicle", 1.0) * 100), 1, 100);
|
||||
s.PositionalVolume = Clamp((int)Math.Round(c.GetDouble("sound.volume.positional", 1.0) * 100), 1, 100);
|
||||
s.AmbientVolume = Clamp((int)Math.Round(c.GetDouble("sound.volume.ambient", 1.0) * 100), 1, 100);
|
||||
s.Volume = Clamp((int)Math.Round(c.GetDouble("sound.volume", 1.0) * 50), 0, 100);
|
||||
s.RadioVolume = Clamp((int)Math.Round(c.GetDouble("sound.volume.radio", 0.75) * 100), 0, 100);
|
||||
s.VehiclesVolume = Clamp((int)Math.Round(c.GetDouble("sound.volume.vehicle", 1.0) * 100), 0, 100);
|
||||
s.PositionalVolume = Clamp((int)Math.Round(c.GetDouble("sound.volume.positional", 1.0) * 100), 0, 100);
|
||||
s.AmbientVolume = Clamp((int)Math.Round(c.GetDouble("sound.volume.ambient", 1.0) * 100), 0, 100);
|
||||
s.SkipPipeline = c.GetBool("gfx.skippipeline", false);
|
||||
s.PythonScreenUpdateRate = c.Has("python.updatetime")
|
||||
? Clamp(c.GetInt("python.updatetime", 200), 0, 10000)
|
||||
@@ -137,6 +151,10 @@ public sealed class SettingsSerializer
|
||||
s.AutoCloseStarter = c.GetBool("starter.autoclose", false);
|
||||
s.LargeThumbnails = c.GetBool("starter.largethumbnails", false);
|
||||
s.AutoExpandSceneryTree = c.GetBool("starter.expandtree", false);
|
||||
s.CpuNotice = c.GetBool("starter.cpunotice", true);
|
||||
s.Gpu = string.Equals(c.GetString("starter.gpu", "discrete"), "system", StringComparison.OrdinalIgnoreCase)
|
||||
? GpuPreference.System
|
||||
: GpuPreference.Discrete;
|
||||
// An unrecognised value means "do not interfere" rather than the nearest
|
||||
// state: clamping upwards would silently force every consist ready.
|
||||
s.ReadyOverride = c.GetInt("starter.batterydefault", 0) switch
|
||||
@@ -151,18 +169,32 @@ public sealed class SettingsSerializer
|
||||
s.HideArchivalVehicles = c.GetBool("starter.hide.archivalvehicles", true);
|
||||
s.LastScenery = c.GetString("starter.last.scenery", "");
|
||||
s.WindowMaximized = c.GetBool("starter.window.maximized", false);
|
||||
|
||||
s.Extra.Clear();
|
||||
foreach (var key in SimulatorKeys.All)
|
||||
if (c.Has(key.Key))
|
||||
s.Extra[key.Key] = c.GetRaw(key.Key) ?? string.Empty;
|
||||
}
|
||||
|
||||
private static readonly string[] ObsoleteKeys =
|
||||
/// <summary>
|
||||
/// Keys the simulator reads a set number of words after, whatever stands there:
|
||||
/// one the file holds short takes the next keys in, so a save puts it right
|
||||
/// even where nobody changed it.
|
||||
/// </summary>
|
||||
public static readonly string[] FixedLengthKeys = { "uart", "uarttune", "uartfeature" };
|
||||
|
||||
/// <summary>Keys written only when they say something, besides those of <see cref="SimulatorKeys"/>.</summary>
|
||||
public static readonly string[] OptionalKeys = { "fpslimit", "gfx.angleplatform" };
|
||||
|
||||
/// <summary>Keys no simulator reads any more, taken out of the file on a save.</summary>
|
||||
public static readonly string[] ObsoleteKeys =
|
||||
{
|
||||
"gfx.postfx.tonemapping",
|
||||
"starter.developertools",
|
||||
};
|
||||
|
||||
public void Write(SimulatorSettings s, ConfigFile c)
|
||||
{
|
||||
foreach (string key in ObsoleteKeys)
|
||||
c.Remove(key);
|
||||
|
||||
c.Set("lang", string.IsNullOrWhiteSpace(s.LanguageCode)
|
||||
? "en"
|
||||
: s.LanguageCode.Trim().ToLowerInvariant());
|
||||
@@ -170,17 +202,25 @@ public sealed class SettingsSerializer
|
||||
c.SetBool("inactivepause", s.PauseWhenInactive);
|
||||
c.SetBool("pause", s.PauseOnStart);
|
||||
|
||||
double mx = s.CursorSensitivity * (s.InvertMouseHorizontal ? -1 : 1);
|
||||
double magnitude = SensitivityStep(s.MouseScaleXMagnitude) == s.CursorSensitivity
|
||||
? s.MouseScaleXMagnitude
|
||||
: s.CursorSensitivity;
|
||||
double mx = magnitude * (s.InvertMouseHorizontal ? -1 : 1);
|
||||
double my = s.MouseScaleYMagnitude * (s.InvertMouseVertical ? -1 : 1);
|
||||
c.Set("mousescale",
|
||||
$"{mx.ToString("0.###", CultureInfo.InvariantCulture)} " +
|
||||
$"{my.ToString("0.###", CultureInfo.InvariantCulture)}");
|
||||
$"{mx.ToString("R", CultureInfo.InvariantCulture)} " +
|
||||
$"{my.ToString("R", CultureInfo.InvariantCulture)}");
|
||||
|
||||
c.SetBool("input.gamepad", !s.IgnoreGamepad);
|
||||
c.SetInt("feedbackmode", s.FeedbackMode);
|
||||
c.SetInt("feedbackport", s.FeedbackPort);
|
||||
if (s.UartEnabled && !string.IsNullOrWhiteSpace(s.UartPort)) c.Set("uart", s.UartPort); else c.Remove("uart");
|
||||
c.Set("uarttune", s.UartTune);
|
||||
// The simulator reads three words after uart and eighteen numbers after
|
||||
// uarttune, whatever stands there - with fewer, the next keys of the file
|
||||
// go in their place.
|
||||
if (s.UartEnabled && Uart.IsPortName(s.UartPort) && s.UartBaud > 0 && s.UartUpdateTime >= 0)
|
||||
c.Set("uart", $"{s.UartPort.Trim()} {s.UartBaud.ToString(CultureInfo.InvariantCulture)} " +
|
||||
s.UartUpdateTime.ToString("0.###", CultureInfo.InvariantCulture));
|
||||
if (Uart.NormalizeTune(s.UartTune) is { } tune) c.Set("uarttune", tune);
|
||||
c.SetBool("uartdebug", s.UartDebug);
|
||||
var sb = new StringBuilder();
|
||||
if (s.UartMain) sb.Append("main|");
|
||||
@@ -189,14 +229,16 @@ public sealed class SettingsSerializer
|
||||
if (s.UartLocal) sb.Append("local|");
|
||||
if (s.UartRadioVolume) sb.Append("radiovolume|");
|
||||
if (s.UartRadioChannel) sb.Append("radiochannel|");
|
||||
c.Set("uartfeature", sb.ToString());
|
||||
if (s.UartDynamicBrake) sb.Append("dynamicbrake|");
|
||||
// Left bare, the key would have the simulator take the next four words for
|
||||
// its old yes/no form.
|
||||
c.Set("uartfeature", sb.Length > 0 ? sb.ToString() : Uart.NoFeatures);
|
||||
|
||||
c.SetBool("starter.exe.auto", s.SelectExeAutomatically);
|
||||
c.Set("starter.exe.path", s.ExecutablePath);
|
||||
c.SetBool("debugmode", s.DebugMode);
|
||||
c.SetBool("ai.trainman", s.VirtualShunting);
|
||||
c.SetBool("starter.logmissingvehicles", s.LogMissingVehicleFiles);
|
||||
c.SetBool("starter.developertools", s.DeveloperTools);
|
||||
|
||||
c.Set("gfxrenderer", SimulatorSettings.RenderEngines[Clamp(s.RenderEngine, 0, SimulatorSettings.RenderEngines.Length - 1)]);
|
||||
c.SetInt("width", s.Width);
|
||||
@@ -208,7 +250,7 @@ public sealed class SettingsSerializer
|
||||
c.SetInt("gfx.framebuffer.height", fbh);
|
||||
c.SetInt("maxtexturesize", s.MaxTextureSize);
|
||||
c.SetInt("maxcabtexturesize", s.MaxCabTextureSize);
|
||||
c.SetInt("anisotropicfiltering", s.TextureFiltering);
|
||||
c.SetDouble("anisotropicfiltering", s.TextureFiltering);
|
||||
c.SetInt("multisampling", s.Multisampling);
|
||||
c.SetInt("dynamiclights", s.DynamicLights);
|
||||
c.SetDouble("gfx.drawrange.factor.max", s.DrawRangeFactor);
|
||||
@@ -222,20 +264,20 @@ public sealed class SettingsSerializer
|
||||
c.SetBool("usevbo", s.UseVbo);
|
||||
c.SetBool("shadows", s.RenderShadows);
|
||||
c.SetBool("gfx.shadowmap.enabled", s.RenderShadows);
|
||||
c.SetInt("gfx.reflections.framerate", s.ReflectionsFramerate);
|
||||
c.Set("gfx.reflections.framerate", s.ReflectionsFramerate.ToString("0.######", CultureInfo.InvariantCulture));
|
||||
c.Set("shadowtune",
|
||||
$"{s.ShadowMapResolution} {s.ShadowProjectionRange} " +
|
||||
$"{s.ShadowTuneExtra[0]} {s.ShadowTuneExtra[1]}");
|
||||
$"{s.ShadowMapResolution} {s.ShadowTuneUnused[0]} " +
|
||||
$"{s.ShadowProjectionRange} {s.ShadowTuneUnused[1]}");
|
||||
c.SetInt("gfx.shadows.cab.range", s.CabShadowsRange);
|
||||
c.SetInt("gfx.shadow.rank.cutoff", s.ShadowRankCutoff);
|
||||
c.SetInt("gfx.reflections.fidelity", s.ReflectionsFidelity);
|
||||
c.SetInt("fieldofview", s.FieldOfView);
|
||||
c.SetBool("python.enabled", s.PythonScreens);
|
||||
c.SetBool("python.threadedupload", s.PythonThreadedUpload);
|
||||
if (s.FpsLimitEnabled) c.SetInt("fpslimit", s.FpsLimit); else c.Remove("fpslimit");
|
||||
if (s.FpsLimitEnabled) c.SetDouble("fpslimit", s.FpsLimit);
|
||||
c.SetDouble("gfx.shadow.angle.min", s.ShadowAngleLimit);
|
||||
c.SetBool("fullscreenwindowed", s.FullscreenWindowed);
|
||||
if (s.RenderAngleVulkan) c.Set("gfx.angleplatform", "vulkan"); else c.Remove("gfx.angleplatform");
|
||||
if (s.RenderAngleVulkan) c.Set("gfx.angleplatform", "vulkan");
|
||||
|
||||
c.SetInt("splinefidelity", s.SplineFidelity);
|
||||
c.SetBool("fullphysics", s.FullPhysics);
|
||||
@@ -274,6 +316,8 @@ public sealed class SettingsSerializer
|
||||
c.SetBool("starter.autoclose", s.AutoCloseStarter);
|
||||
c.SetBool("starter.largethumbnails", s.LargeThumbnails);
|
||||
c.SetBool("starter.expandtree", s.AutoExpandSceneryTree);
|
||||
c.SetBool("starter.cpunotice", s.CpuNotice);
|
||||
c.Set("starter.gpu", s.Gpu == GpuPreference.System ? "system" : "discrete");
|
||||
c.SetInt("starter.batterydefault", (int)s.ReadyOverride);
|
||||
c.SetBool("starter.show.ai", s.ShowAiVehicles);
|
||||
c.SetBool("starter.drivableonly", s.DrivableOnly);
|
||||
@@ -281,23 +325,26 @@ public sealed class SettingsSerializer
|
||||
c.SetBool("starter.hide.archivalvehicles", s.HideArchivalVehicles);
|
||||
if (!string.IsNullOrWhiteSpace(s.LastScenery))
|
||||
c.Set("starter.last.scenery", s.LastScenery);
|
||||
else
|
||||
c.Remove("starter.last.scenery");
|
||||
c.SetBool("starter.window.maximized", s.WindowMaximized);
|
||||
|
||||
// A key left bare would take the next line's key for its value, so an
|
||||
// emptied one goes.
|
||||
foreach (var key in SimulatorKeys.All)
|
||||
if (s.Extra.TryGetValue(key.Key, out string? value) && !string.IsNullOrWhiteSpace(value))
|
||||
c.Set(key.Key, value.Trim());
|
||||
}
|
||||
|
||||
private static int Clamp(int v, int lo, int hi) => v < lo ? lo : (v > hi ? hi : v);
|
||||
|
||||
private static int SensitivityStep(double mouseScale) =>
|
||||
(int)Math.Clamp(Math.Round(Math.Abs(mouseScale)), 1, 5);
|
||||
|
||||
private static double ParseDouble(string s, double fallback) =>
|
||||
double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out double d) ? d : fallback;
|
||||
|
||||
private static int ParseInt(string s, int fallback) =>
|
||||
int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n) ? n : fallback;
|
||||
|
||||
private static int IndexOf(string[] values, string token, int fallback)
|
||||
{
|
||||
for (int i = 0; i < values.Length; i++)
|
||||
if (string.Equals(values[i], token, StringComparison.OrdinalIgnoreCase))
|
||||
return i;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
private static int MapOldPyScreenPriority(string priority) =>
|
||||
priority.ToLowerInvariant() switch
|
||||
|
||||
178
StarterNG/Infrastructure/WineConfigLink.cs
Normal file
178
StarterNG/Infrastructure/WineConfigLink.cs
Normal file
@@ -0,0 +1,178 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using StarterNG.Application.Abstractions;
|
||||
using StarterNG.Infrastructure.Settings;
|
||||
|
||||
namespace StarterNG.Infrastructure;
|
||||
|
||||
/// <summary>
|
||||
/// Hands a Windows build started through Wine the settings the starter writes.
|
||||
/// eu07.exe reads eu07.ini and the input files from %APPDATA%\MaSzyna, which Wine
|
||||
/// keeps inside its prefix whatever APPDATA says - so that folder is made a link
|
||||
/// to the starter's own, and both see one set of files.
|
||||
/// </summary>
|
||||
public sealed class WineConfigLink
|
||||
{
|
||||
private const string VendorFolder = "MaSzyna";
|
||||
private const string BackupSuffix = ".before-starter";
|
||||
|
||||
private readonly IFileSystem _files;
|
||||
private readonly IEnvironment _environment;
|
||||
private readonly SettingsPaths _settingsPaths;
|
||||
private readonly IDiagnosticsLog _log;
|
||||
|
||||
public WineConfigLink(IFileSystem files, IEnvironment environment, SettingsPaths settingsPaths,
|
||||
IDiagnosticsLog log)
|
||||
{
|
||||
_files = files;
|
||||
_environment = environment;
|
||||
_settingsPaths = settingsPaths;
|
||||
_log = log;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes the prefix's MaSzyna folder a link to the folder the starter saves eu07.ini in.
|
||||
/// A folder already there is kept beside it under another name, its files the
|
||||
/// starter's folder lacks copied over; a link of the player's own to elsewhere
|
||||
/// is left alone. Failing half way, it puts all that back, so the next attempt
|
||||
/// starts from the same place. Whatever it does, or why not, goes to the log.
|
||||
/// </summary>
|
||||
public void Ensure()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (RoamingDirectory() is not { } roaming)
|
||||
{
|
||||
_log.Log("Wine: no prefix with a user profile yet; eu07.exe reads its own eu07.ini this time");
|
||||
return;
|
||||
}
|
||||
|
||||
string link = Path.Combine(roaming, VendorFolder);
|
||||
string target = Path.GetFullPath(_settingsPaths.UserConfigDirectory());
|
||||
if (_files.LinkTarget(link) is { } current)
|
||||
{
|
||||
if (!SamePath(Path.GetFullPath(current, roaming), target))
|
||||
_log.Log($"Wine: {link} links to {current}, not {target}; left as it is");
|
||||
return;
|
||||
}
|
||||
|
||||
if (_files.FileExists(link))
|
||||
{
|
||||
_log.Log($"Wine: {link} is a file; settings not linked");
|
||||
return;
|
||||
}
|
||||
|
||||
_files.CreateDirectory(target);
|
||||
string? backup = null;
|
||||
var copied = new List<string>();
|
||||
try
|
||||
{
|
||||
if (_files.DirectoryExists(link))
|
||||
{
|
||||
string moved = FreeName(link + BackupSuffix);
|
||||
_files.MoveDirectory(link, moved);
|
||||
backup = moved;
|
||||
_log.Log($"Wine: {link} moved to {backup}");
|
||||
CopyMissing(backup, target, copied);
|
||||
}
|
||||
|
||||
_files.CreateDirectoryLink(link, target);
|
||||
_log.Log($"Wine: {link} now links to {target}");
|
||||
}
|
||||
catch when (backup is not null)
|
||||
{
|
||||
PutBack(backup, link, copied);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Log("Wine: linking the settings", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void PutBack(string backup, string link, IEnumerable<string> copied)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (string copy in copied)
|
||||
_files.DeleteFile(copy);
|
||||
_files.MoveDirectory(backup, link);
|
||||
_log.Log($"Wine: {link} put back as it was");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Log($"Wine: {link} could not be put back, its files stays at {backup}", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>%APPDATA% inside the prefix the wine command uses, or null before one is made.</summary>
|
||||
private string? RoamingDirectory()
|
||||
{
|
||||
string? prefix = _environment.GetVariable("WINEPREFIX");
|
||||
if (string.IsNullOrEmpty(prefix))
|
||||
{
|
||||
string? home = _environment.GetVariable("HOME");
|
||||
if (string.IsNullOrEmpty(home))
|
||||
return null;
|
||||
prefix = Path.Combine(home, ".wine");
|
||||
}
|
||||
|
||||
if (UserProfile(Path.Combine(prefix, "drive_c", "users")) is not { } profile)
|
||||
return null;
|
||||
|
||||
// Wine 5 and later lay the profile out as Vista does; older ones as XP did.
|
||||
string roaming = Path.Combine(profile, "AppData", "Roaming");
|
||||
if (_files.DirectoryExists(roaming))
|
||||
return roaming;
|
||||
string applicationData = Path.Combine(profile, "Application Data");
|
||||
return _files.DirectoryExists(applicationData) ? applicationData : null;
|
||||
}
|
||||
|
||||
/// <summary>The profile named after the user, as Wine names it; or the only one there is.</summary>
|
||||
private string? UserProfile(string users)
|
||||
{
|
||||
if (!_files.DirectoryExists(users))
|
||||
return null;
|
||||
|
||||
foreach (string variable in new[] { "USER", "LOGNAME" })
|
||||
{
|
||||
string? name = _environment.GetVariable(variable);
|
||||
if (!string.IsNullOrEmpty(name) && _files.DirectoryExists(Path.Combine(users, name)))
|
||||
return Path.Combine(users, name);
|
||||
}
|
||||
|
||||
var profiles = _files.GetDirectories(users)
|
||||
.Where(path => !string.Equals(Path.GetFileName(path), "Public", StringComparison.OrdinalIgnoreCase))
|
||||
.ToList();
|
||||
return profiles.Count == 1 ? profiles[0] : null;
|
||||
}
|
||||
|
||||
// What eu07.exe kept in the prefix alone - eu07_input-uart.ini set up under
|
||||
// Wine, say - so it still finds it; the starter's copy wins where both have one.
|
||||
private void CopyMissing(string from, string to, List<string> copied)
|
||||
{
|
||||
foreach (string file in _files.GetFiles(from))
|
||||
{
|
||||
string copy = Path.Combine(to, Path.GetFileName(file));
|
||||
if (_files.FileExists(copy))
|
||||
continue;
|
||||
_files.CopyFile(file, copy, overwrite: false);
|
||||
copied.Add(copy);
|
||||
_log.Log($"Wine: {Path.GetFileName(file)} copied to {to}");
|
||||
}
|
||||
}
|
||||
|
||||
private string FreeName(string path)
|
||||
{
|
||||
string name = path;
|
||||
for (int n = 2; _files.DirectoryExists(name) || _files.FileExists(name) || _files.LinkTarget(name) != null; n++)
|
||||
name = $"{path}-{n}";
|
||||
return name;
|
||||
}
|
||||
|
||||
private static bool SamePath(string a, string b) =>
|
||||
string.Equals(a.TrimEnd('/', '\\'), b.TrimEnd('/', '\\'), StringComparison.Ordinal);
|
||||
}
|
||||
Reference in New Issue
Block a user