mirror of
https://github.com/MaSzyna-EU07/StarterNG.git
synced 2026-11-19 06:55:59 +01:00
Write settings, presets and favourites whole or not at all
A failed write leaves the old file in place. Settings that could not be read are not saved over. UI exceptions reach the log. Started from a shortcut set up elsewhere, the starter moves to its own folder when only that one holds a game.
This commit is contained in:
@@ -17,6 +17,7 @@ public sealed class FileDiagnosticsLog : IDiagnosticsLog
|
||||
|
||||
private StreamWriter? _writer;
|
||||
private bool _writerFailed;
|
||||
private bool _previousKept;
|
||||
|
||||
public FileDiagnosticsLog(IFileSystem files, IClock clock, IGamePaths paths)
|
||||
{
|
||||
@@ -91,7 +92,8 @@ public sealed class FileDiagnosticsLog : IDiagnosticsLog
|
||||
try
|
||||
{
|
||||
_files.CreateDirectory(Path.GetDirectoryName(_logPath)!);
|
||||
_files.WriteAllLines(_logPath, _lines);
|
||||
if (KeepPreviousSession())
|
||||
_files.WriteAllLines(_logPath, _lines);
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -99,6 +101,26 @@ public sealed class FileDiagnosticsLog : IDiagnosticsLog
|
||||
}
|
||||
}
|
||||
|
||||
// What the last session left, a crash's traces above all, is what this log is
|
||||
// read for: one copy of it goes aside before the first entry of this one. False
|
||||
// when it could not, and the log is then added to instead of started over.
|
||||
private bool KeepPreviousSession()
|
||||
{
|
||||
if (_previousKept)
|
||||
return true;
|
||||
|
||||
try
|
||||
{
|
||||
if (_files.FileExists(_logPath))
|
||||
_files.CopyFile(_logPath, _logPath + ".1", overwrite: true);
|
||||
return _previousKept = true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void Append(string line)
|
||||
{
|
||||
if (_writerFailed)
|
||||
@@ -109,7 +131,7 @@ public sealed class FileDiagnosticsLog : IDiagnosticsLog
|
||||
if (_writer is null)
|
||||
{
|
||||
_files.CreateDirectory(Path.GetDirectoryName(_logPath)!);
|
||||
_writer = new StreamWriter(_logPath, append: false) { AutoFlush = true };
|
||||
_writer = new StreamWriter(_logPath, append: !KeepPreviousSession()) { AutoFlush = true };
|
||||
}
|
||||
_writer.WriteLine(line);
|
||||
}
|
||||
|
||||
@@ -10,7 +10,24 @@ public sealed class GamePaths : IGamePaths
|
||||
Root = root;
|
||||
}
|
||||
|
||||
public static GamePaths ForCurrentDirectory() => new(Directory.GetCurrentDirectory());
|
||||
/// <summary>
|
||||
/// The working directory, which is how the game's own shortcuts point at it - or
|
||||
/// the starter's folder where only that one holds a game, as when started from a
|
||||
/// shortcut set up elsewhere. Moved there too: more than these paths go by it.
|
||||
/// </summary>
|
||||
public static GamePaths ForCurrentDirectory()
|
||||
{
|
||||
string current = Directory.GetCurrentDirectory();
|
||||
string own = System.AppContext.BaseDirectory;
|
||||
if (HoldsGame(current) || !HoldsGame(own))
|
||||
return new GamePaths(current);
|
||||
|
||||
Directory.SetCurrentDirectory(own);
|
||||
return new GamePaths(Directory.GetCurrentDirectory());
|
||||
}
|
||||
|
||||
private static bool HoldsGame(string folder) =>
|
||||
Directory.Exists(Path.Combine(folder, "scenery")) && Directory.Exists(Path.Combine(folder, "dynamic"));
|
||||
|
||||
public string Root { get; }
|
||||
|
||||
|
||||
@@ -32,14 +32,26 @@ public static class LegacyText
|
||||
/// </summary>
|
||||
public static string Decode(byte[] bytes)
|
||||
{
|
||||
ReadOnlySpan<byte> text = bytes;
|
||||
if (text.StartsWith(Utf8Bom))
|
||||
text = text[Utf8Bom.Length..];
|
||||
|
||||
return Utf8.IsValid(text) ? Encoding.UTF8.GetString(text) : CodePage1250.GetString(text);
|
||||
var (encoding, bom) = Detect(bytes);
|
||||
return encoding.GetString(bytes, bom.Length, bytes.Length - bom.Length);
|
||||
}
|
||||
|
||||
private static ReadOnlySpan<byte> Utf8Bom => [0xEF, 0xBB, 0xBF];
|
||||
/// <summary>
|
||||
/// What a game file is written in, so it is written back the way it was read:
|
||||
/// UTF-8 only for a file that is UTF-8 and says so with its mark or a letter
|
||||
/// outside ASCII, code page 1250 - the game's own - else. That one gives every
|
||||
/// byte back as it was, also behind a mark that lied; UTF-8 would turn what is
|
||||
/// not UTF-8 into replacement characters.
|
||||
/// </summary>
|
||||
public static (Encoding Encoding, byte[] Bom) Detect(byte[] bytes)
|
||||
{
|
||||
byte[] bom = bytes.AsSpan().StartsWith(Utf8Bom) ? Utf8Bom : Array.Empty<byte>();
|
||||
var body = bytes.AsSpan(bom.Length);
|
||||
bool utf8 = Utf8.IsValid(body) && (bom.Length > 0 || body.ContainsAnyInRange((byte)0x80, (byte)0xFF));
|
||||
return (utf8 ? new UTF8Encoding(false) : CodePage1250, bom);
|
||||
}
|
||||
|
||||
private static readonly byte[] Utf8Bom = { 0xEF, 0xBB, 0xBF };
|
||||
|
||||
private static Encoding Resolve()
|
||||
{
|
||||
|
||||
@@ -8,6 +8,8 @@ namespace StarterNG.Infrastructure.Adapters;
|
||||
|
||||
public sealed class PhysicalFileSystem : IFileSystem
|
||||
{
|
||||
public const string TempSuffix = ".starter.tmp";
|
||||
|
||||
public bool FileExists(string path) => File.Exists(path);
|
||||
|
||||
public bool DirectoryExists(string path) => Directory.Exists(path);
|
||||
@@ -20,13 +22,61 @@ public sealed class PhysicalFileSystem : IFileSystem
|
||||
|
||||
public byte[] ReadAllBytes(string path) => File.ReadAllBytes(path);
|
||||
|
||||
public Stream OpenRead(string path) => File.OpenRead(path);
|
||||
// Shared for writing too, so a file the simulator still holds open - a physics log of
|
||||
// a running trip - can be read.
|
||||
public Stream OpenRead(string path) =>
|
||||
new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
|
||||
public void WriteAllText(string path, string contents) => File.WriteAllText(path, contents);
|
||||
|
||||
public void WriteAllText(string path, string contents, Encoding encoding) =>
|
||||
File.WriteAllText(path, contents, encoding);
|
||||
|
||||
public void WriteAllTextAtomic(string path, string contents) =>
|
||||
WriteAllBytesAtomic(path, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(contents));
|
||||
|
||||
/// <summary>
|
||||
/// Written beside the file and moved over it. A crash at any moment leaves the old
|
||||
/// file or the new one whole - at worst with the temporary one beside it, which
|
||||
/// the next save writes over, under a name nothing in the game reads.
|
||||
/// </summary>
|
||||
public void WriteAllBytesAtomic(string path, byte[] bytes)
|
||||
{
|
||||
// Through a link, to its file: moved over the link, the text would take its place.
|
||||
if (File.Exists(path) && File.ResolveLinkTarget(path, returnFinalTarget: true) is { } linked)
|
||||
path = linked.FullName;
|
||||
|
||||
string temporary = path + TempSuffix;
|
||||
try
|
||||
{
|
||||
using (var stream = new FileStream(temporary, FileMode.Create, FileAccess.Write, FileShare.None))
|
||||
{
|
||||
stream.Write(bytes);
|
||||
// On the disk itself first, or a power cut could leave the new name with no text under it.
|
||||
stream.Flush(flushToDisk: true);
|
||||
}
|
||||
|
||||
// A new file gets the default mode; a write in place kept the old one.
|
||||
if (!OperatingSystem.IsWindows() && File.Exists(path) &&
|
||||
File.GetUnixFileMode(path) is var mode && mode != File.GetUnixFileMode(temporary))
|
||||
File.SetUnixFileMode(temporary, mode);
|
||||
|
||||
File.Move(temporary, path, overwrite: true);
|
||||
}
|
||||
catch
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(temporary);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// The failure to tell is the one that brought us here.
|
||||
}
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void WriteAllLines(string path, IEnumerable<string> lines) => File.WriteAllLines(path, lines);
|
||||
|
||||
public void WriteAllBytes(string path, byte[] bytes) => File.WriteAllBytes(path, bytes);
|
||||
@@ -41,9 +91,16 @@ public sealed class PhysicalFileSystem : IFileSystem
|
||||
public IReadOnlyList<string> GetFiles(string path, string searchPattern = "*") =>
|
||||
Directory.Exists(path) ? Directory.GetFiles(path, searchPattern) : Array.Empty<string>();
|
||||
|
||||
// A folder it may not enter costs what is in it, not the whole listing.
|
||||
public IReadOnlyList<string> GetFilesRecursive(string path, string searchPattern) =>
|
||||
Directory.Exists(path)
|
||||
? Directory.GetFiles(path, searchPattern, SearchOption.AllDirectories)
|
||||
? Directory.GetFiles(path, searchPattern, new EnumerationOptions
|
||||
{
|
||||
RecurseSubdirectories = true,
|
||||
IgnoreInaccessible = true,
|
||||
AttributesToSkip = 0,
|
||||
MatchType = MatchType.Win32
|
||||
})
|
||||
: Array.Empty<string>();
|
||||
|
||||
public IReadOnlyList<string> GetDirectories(string path) =>
|
||||
@@ -62,4 +119,11 @@ public sealed class PhysicalFileSystem : IFileSystem
|
||||
UnixFileMode.UserExecute | UnixFileMode.GroupExecute | UnixFileMode.OtherExecute;
|
||||
return (File.GetUnixFileMode(path) & anyExecute) != 0;
|
||||
}
|
||||
|
||||
public string? LinkTarget(string path) => new FileInfo(path).LinkTarget;
|
||||
|
||||
public void CreateDirectoryLink(string path, string target) => Directory.CreateSymbolicLink(path, target);
|
||||
|
||||
public void MoveDirectory(string sourcePath, string destinationPath) =>
|
||||
Directory.Move(sourcePath, destinationPath);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
@@ -53,6 +55,25 @@ public static class Diagnostics
|
||||
Dispatcher.UIThread.Post(() => _ = ReportAsync(message, title));
|
||||
}
|
||||
|
||||
/// <summary>Opens a file or folder the way the system does; a dialog says if it is not there or will not open.</summary>
|
||||
public static void OpenOrReport(string path)
|
||||
{
|
||||
if (!File.Exists(path) && !Directory.Exists(path))
|
||||
{
|
||||
ReportOnUiThread(string.Format(App.Loc["FaultFileNotFound"], path));
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Process.Start(new ProcessStartInfo(path) { UseShellExecute = true });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_ = ReportAsync(path, ex);
|
||||
}
|
||||
}
|
||||
|
||||
public static InstallationCheck InstallationCheck() =>
|
||||
new(AppServices.Current.Paths,
|
||||
AppServices.Current.Files,
|
||||
|
||||
Reference in New Issue
Block a user