mirror of
https://github.com/MaSzyna-EU07/StarterNG.git
synced 2026-11-01 20:34:57 +01:00
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.
82 lines
2.2 KiB
C#
82 lines
2.2 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using StarterNG.Application.Abstractions;
|
|
using StarterNG.Domain.Sceneries;
|
|
|
|
namespace StarterNG.Application;
|
|
|
|
/// <summary>
|
|
/// The sceneries starred in the list, by file name, one per line in a file of the
|
|
/// starter's own - eu07.ini is the simulator's as much as ours.
|
|
/// </summary>
|
|
public sealed class FavoriteSceneries
|
|
{
|
|
private readonly IFileSystem _files;
|
|
private readonly IDiagnosticsLog _log;
|
|
private readonly string _path;
|
|
private readonly HashSet<string> _names = new(StringComparer.OrdinalIgnoreCase);
|
|
|
|
// The file holds more than _names does: it goes aside before anything replaces it.
|
|
private bool _unread;
|
|
|
|
public FavoriteSceneries(IFileSystem files, IDiagnosticsLog log, string path)
|
|
{
|
|
_files = files;
|
|
_log = log;
|
|
_path = path;
|
|
Load();
|
|
}
|
|
|
|
public bool Contains(Scenery scenery) => _names.Contains(Key(scenery));
|
|
|
|
public void Toggle(Scenery scenery)
|
|
{
|
|
string key = Key(scenery);
|
|
if (!_names.Remove(key))
|
|
_names.Add(key);
|
|
Save();
|
|
}
|
|
|
|
private static string Key(Scenery scenery) => Path.GetFileName(scenery.Path);
|
|
|
|
private void Load()
|
|
{
|
|
try
|
|
{
|
|
if (!_files.FileExists(_path))
|
|
return;
|
|
|
|
foreach (string line in _files.ReadAllText(_path).Split('\n'))
|
|
if (line.Trim() is { Length: > 0 } name)
|
|
_names.Add(name);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_log.Log($"reading {_path}", ex);
|
|
_unread = true;
|
|
}
|
|
}
|
|
|
|
private void Save()
|
|
{
|
|
try
|
|
{
|
|
if (Path.GetDirectoryName(_path) is { Length: > 0 } directory)
|
|
_files.CreateDirectory(directory);
|
|
|
|
if (_unread)
|
|
{
|
|
_files.KeepAside(_path, _log);
|
|
_unread = false;
|
|
}
|
|
_files.WriteAllTextAtomic(_path, string.Join('\n', _names.Order(StringComparer.OrdinalIgnoreCase)));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_log.Log($"writing {_path}", ex);
|
|
}
|
|
}
|
|
}
|