using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Chronos.App.Settings;
using Chronos.Core.Diagnostics;
using Chronos.Core.Export;
using Chronos.Core.Model;
using Chronos.Core.Windows.Codecs;
using Chronos.Data;
using Chronos.Data.Sqlite;
namespace Chronos.App.Infrastructure;
///
/// The diagnostics bundle of About and Settings › Advanced (BRIEF §12.9, §22 Phase 8): an environment report, the codec
/// and encoder inventory, the settings, the latest failed jobs and the log files, zipped into a folder the user chose.
/// Everything passes through (the saved server token, passwords and keys never leave the
/// PC) and no photo or archive file is ever included.
///
public static class DiagnosticsBundle
{
/// Failed jobs included, newest first.
public const int FailedJobs = 50;
///
/// Writes "Chronos diagnostics yyyy-MM-dd HHmm.zip" (" (2)", " (3)"… when that name is taken) into
/// and returns its path; a bundle that fails half-way leaves no file behind. Call on the UI
/// thread: the settings are captured there; detection and writing run in the background.
///
public static Task CreateAsync(AppServices services, string folder, IEnumerable? extraLines = null, CancellationToken ct = default)
{
var settings = services.Settings.ToJson();
var report = Report(services.Environment, extraLines) + DatabaseLine(services.Database);
return Task.Run(async () =>
{
var failures = services.Database is { } db ? (await db.Jobs.ListAsync(JobState.Failed, FailedJobs, null, ct).ConfigureAwait(false)).Items : [];
var codecs = Codecs(services.Encoders);
var path = ExportNaming.Unique(folder, $"Chronos diagnostics {DateTime.Now.ToString("yyyy-MM-dd HHmm", CultureInfo.InvariantCulture)}", ".zip");
var temp = path + ".tmp";
try
{
await using (var file = new FileStream(temp, FileMode.Create, FileAccess.Write, FileShare.None))
using (var bundle = new DiagnosticsArchive(file))
{
bundle.AddText("environment.txt", report);
bundle.AddText("codecs.txt", codecs);
bundle.AddJson("settings.json", settings);
bundle.AddJobs("jobs-failed.json", failures);
bundle.AddLogs(services.Environment.LogDirectory, cancellationToken: ct);
}
File.Move(temp, path);
return path;
}
finally
{
// Gone after a successful move; after a failure a half-written zip helps nobody.
if (File.Exists(temp)) File.Delete(temp);
}
}, ct);
}
/// Plain-text environment report.
public static string Report(AppEnvironment environment, IEnumerable? extraLines = null)
{
var sb = new StringBuilder();
sb.AppendLine(CultureInfo.InvariantCulture, $"Chronos {AppServices.VersionText}");
sb.Append(DiagnosticsArchive.SystemReport());
sb.AppendLine(CultureInfo.InvariantCulture, $"Data {environment.DataDirectory} (portable: {environment.IsPortable})");
if (extraLines is not null)
{
foreach (var line in extraLines) sb.AppendLine(line);
}
return sb.ToString();
}
private static string DatabaseLine(ChronosDatabase? database)
{
if (database is null) return "Index not open\n";
var line = string.Create(CultureInfo.InvariantCulture, $"Index schema {database.SchemaVersion}\n");
// The SQLite build's options (BRIEF §6.2) explain behaviour differences between Windows versions.
return database.Database is SqliteDatabase
? line + $"SQLite {SqliteDatabase.LibraryVersion}; compile options: {string.Join(' ', SqliteDatabase.CompileOptions)}\n"
: line;
}
/// Graphics adapter, video encoders, WIC decoders per format and missing Store extensions.
private static string Codecs(IEncoderInventory encoders)
{
var sb = new StringBuilder();
sb.AppendLine(CultureInfo.InvariantCulture, $"Graphics adapter: {encoders.Adapter() ?? "none"}");
sb.AppendLine("Encoders:");
foreach (var e in encoders.Detect())
{
var size = e.MaxWidth > 0 ? string.Create(CultureInfo.InvariantCulture, $" max {e.MaxWidth}x{e.MaxHeight}") : string.Empty;
sb.AppendLine(CultureInfo.InvariantCulture, $" {e.Codec} · {e.DisplayName} ({(e.Hardware ? "hardware" : "software")}{(e.TenBit ? ", 10-bit" : string.Empty)}{size})");
}
try
{
var inventory = CodecInventory.Detect();
sb.AppendLine(CultureInfo.InvariantCulture, $"HEVC decoder: {inventory.HasHevcDecoder}; AV1 decoder: {inventory.HasAv1Decoder}");
sb.AppendLine("Image formats (WIC):");
foreach (var f in inventory.Formats)
{
var missing = f.MissingExtensions.Count == 0 ? string.Empty : "; missing " + string.Join(", ", f.MissingExtensions.Select(x => x.ProductName));
sb.AppendLine(CultureInfo.InvariantCulture, $" {f.Format}: {(f.IsNative ? "native" : f.Decoder is null ? "no decoder" : "preview only")}{(f.Decoder is { } d ? $" ({d.FriendlyName} {d.Version})" : string.Empty)}{missing}");
}
}
catch (Exception ex) when (ex is COMException or DllNotFoundException or EntryPointNotFoundException or InvalidOperationException)
{
sb.AppendLine("WIC decoders could not be listed: " + ex.Message);
}
return sb.ToString();
}
}
///
/// The disk cache (spilled frames, thumbnails): its folder, its size and clearing it. Only a folder Chronos created
/// (it carries a marker file) is ever emptied, so pointing the cache at a folder with user files cannot delete them.
///
public static class CacheStore
{
public const string MarkerFile = ".chronos-cache";
/// The cache folder in effect.
public static string Folder(AppEnvironment environment, AppSettings settings) =>
string.IsNullOrWhiteSpace(settings.CacheFolder) ? environment.CacheDirectory : settings.CacheFolder!;
/// Creates the folder (if needed) and marks it as Chronos's.
public static void Prepare(string folder)
{
Directory.CreateDirectory(folder);
var marker = Path.Combine(folder, MarkerFile);
if (!File.Exists(marker)) File.WriteAllText(marker, "Chronos cache folder. Its contents can be deleted at any time.");
}
/// True when is a Chronos cache folder (safe to empty).
public static bool IsOwned(string folder) => File.Exists(Path.Combine(folder, MarkerFile));
/// Total bytes of the files in the cache (0 when missing).
public static long Size(string folder)
{
if (!Directory.Exists(folder)) return 0;
long total = 0;
var options = new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint };
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", options)) total += file.Length;
return total;
}
/// Deletes everything inside an owned cache folder except the marker; returns the bytes freed.
/// The folder is not a Chronos cache folder.
public static long Clear(string folder)
{
if (!Directory.Exists(folder)) return 0;
if (!IsOwned(folder)) throw new InvalidOperationException("Not a Chronos cache folder: " + folder);
long freed = 0;
var root = new DirectoryInfo(folder);
foreach (var file in root.EnumerateFiles())
{
if (file.Name == MarkerFile) continue;
freed += TryDelete(file);
}
foreach (var directory in root.EnumerateDirectories())
{
if ((directory.Attributes & FileAttributes.ReparsePoint) != 0) continue;
var options = new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint };
foreach (var file in directory.EnumerateFiles("*", options)) freed += TryDelete(file);
try
{
directory.Delete(recursive: true);
}
catch (IOException)
{
}
catch (UnauthorizedAccessException)
{
}
}
return freed;
}
private static long TryDelete(FileInfo file)
{
try
{
var length = file.Length;
file.Delete();
return length;
}
catch (IOException)
{
return 0; // in use (a render spilling right now)
}
catch (UnauthorizedAccessException)
{
return 0;
}
}
}