using System.Windows;
using System.Windows.Threading;
using Chronos.App.DesignTime;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.App.Shell;
using Chronos.Core.Diagnostics;
using Chronos.Ui.Mvvm;
using Chronos.Ui.Theming;
namespace Chronos.App;
///
/// Chronos desktop client. Local mode starts here: settings and language before the first window, then the window,
/// then the index and the job engine () off the UI thread. --capture <dir>
/// renders every screen with synthetic data in a throw-away data folder and exits. A file argument is a
/// .chronos project file (Explorer passes it on a double-click) opened once the index is open. One Chronos runs
/// per data folder: a second launch hands its file to the running one and exits, or, when the running one is closing,
/// waits for it to exit and starts with the file ().
///
public partial class App : Application
{
/// How long a launch waits for a Chronos that is closing (it gives its services up to 10 s to stop).
private static readonly TimeSpan ClosingWait = TimeSpan.FromSeconds(30);
private readonly TaskCompletionSource _started = new(TaskCreationOptions.RunContinuationsAsynchronously);
private FileLogSink? _log;
private SingleInstance? _instance;
private bool _windowClosed;
public AppEnvironment Environment { get; private set; } = null!;
public AppSettings Settings { get; private set; } = null!;
public AppServices Services { get; private set; } = null!;
public static new App Current => (App)Application.Current;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var captureIndex = Array.IndexOf(e.Args, "--capture");
var capture = captureIndex >= 0;
// Capture never reads or writes the user's data folder.
Environment = capture ? AppEnvironment.ForCapture() : AppEnvironment.Detect();
// Settings › Advanced › Logs from the first line, which prunes the folder: also a launch that only hands over. The
// settings are read again once this launch owns the data folder, since a Chronos that was closing saves them on exit.
_log = AppLogging.Open(Environment.LogDirectory, capture ? new AppSettings() : AppSettings.Load(Environment.SettingsPath));
// Capture runs in CI: mirror the log to stderr so failures are visible in the job output.
Log.SetSink(capture ? new TeeLogSink(_log, new StderrLogSink()) : _log);
Log.Info("app", $"Chronos {AppServices.VersionText} starting; data at {Environment.DataDirectory}");
// Settings tells the user once the window is up.
if (Environment.PortableSyncRoot is { } portableIn) Log.Warning("app", $"This portable copy runs in the OneDrive folder {portableIn}: its data is kept outside it");
if (Environment.EarlierPortableData is { } earlier) Log.Warning("app", $"The data this portable copy kept in {earlier} before is left there and no longer used");
if (Environment.SyncedFolder is { } synced) Log.Warning("app", $"The data folder lies in the OneDrive folder {synced}: synchronisation may damage the index");
var projectFile = capture ? null : ProjectFileArgument(e.Args);
if (!capture)
{
_instance = SingleInstance.TryAcquire(Environment.DataDirectory);
if (_instance is null)
{
if (SingleInstance.HandOver(Environment.DataDirectory, projectFile is null ? [] : [projectFile]))
{
Log.Info("app", "Chronos already runs on this data folder; arguments handed over");
Shutdown();
return;
}
// No answer: the running Chronos is closing (it stops listening first). Start once it has exited.
_instance = SingleInstance.WaitForTurn(Environment.DataDirectory, ClosingWait);
if (_instance is null)
{
Log.Info("app", "Chronos already runs on this data folder and did not answer");
Shutdown();
return;
}
Log.Info("app", "The previous Chronos on this data folder has exited");
}
// From now on: a launch while the window and the index open is kept until the shell can take it.
_instance.Listen();
}
Settings = capture ? new AppSettings { Language = "en" } : AppSettings.Load(Environment.SettingsPath);
ApplyLogSettings();
UiLanguage.Apply(Settings.Language);
ThemeManager.Initialize(this, capture ? AppTheme.Dark : Settings.Theme);
AppResources.Merge(this);
DispatcherUnhandledException += OnUnhandledException;
AppDomain.CurrentDomain.UnhandledException += (_, args) => Log.Error("app", "Unhandled exception", args.ExceptionObject as Exception);
TaskScheduler.UnobservedTaskException += (_, args) =>
{
Log.Error("app", "Unobserved task exception", args.Exception);
args.SetObserved();
};
var dialogs = new AppDialogs();
Services = new AppServices(Environment, Settings, SaveSettings, dialogs);
SampleData? sample = capture ? SampleData.Configure(Services) : null;
var shell = new ShellViewModel(Services);
AsyncRelayCommand.Failed += ex => shell.ReportError(ex);
var window = new MainWindow(shell);
dialogs.Owner = window;
MainWindow = window;
if (capture)
{
var dir = captureIndex + 1 < e.Args.Length ? e.Args[captureIndex + 1] : "screenshots";
_ = ScreenCapture.RunAsync(window, shell, sample!, dir);
return;
}
// Closing the main window ends Chronos: later launches wait for it instead of handing over a file it cannot open.
window.Closed += (_, _) =>
{
_windowClosed = true;
_instance?.StopListening();
};
window.Show();
_instance?.Receive(args => Dispatcher.BeginInvoke(() => OnHandOver(shell, args)));
_ = StartAsync(shell, projectFile);
}
/// Opens the index and the job engine after the window is visible, fills the screens, then opens the project file given.
private async Task StartAsync(ShellViewModel shell, string? projectFile)
{
try
{
await Services.OpenAsync(Environment.DatabasePath);
await shell.StartAsync();
}
catch (Exception ex)
{
shell.ReportError(ex);
}
finally
{
_started.TrySetResult();
}
if (projectFile is not null) await OpenProjectFileAsync(shell, projectFile);
}
/// A later launch: its window comes to the front here, and its project file opens.
private void OnHandOver(ShellViewModel shell, IReadOnlyList args)
{
if (_windowClosed)
{
Log.Warning("app", "A launch arrived while Chronos was closing; its arguments are ignored");
return;
}
if (MainWindow is { } window)
{
window.Show();
if (window.WindowState == WindowState.Minimized) window.WindowState = WindowState.Normal;
window.Activate();
}
if (ProjectFileArgument(args) is { } projectFile) _ = OpenProjectFileAsync(shell, projectFile);
}
/// Opens a project file once the index is open; failures become the usual one-sentence toast.
private async Task OpenProjectFileAsync(ShellViewModel shell, string path)
{
await _started.Task;
try
{
await new ProjectFiles(shell).OpenAsync(path);
}
catch (Exception ex)
{
shell.ReportError(ex);
}
}
/// The first argument that is not an option, as a full path (the hand-over crosses working folders).
private static string? ProjectFileArgument(IReadOnlyList args)
{
if (args.FirstOrDefault(a => !a.StartsWith("--", StringComparison.Ordinal) && a.Length > 0) is not { } file) return null;
try
{
return System.IO.Path.GetFullPath(file);
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or System.IO.PathTooLongException)
{
Log.Warning("app", $"Ignoring argument '{file}'", ex);
return null;
}
}
public void SaveSettings()
{
// A launch that handed over to the running Chronos reads the settings only for its log and never sets Settings.
if (Settings is null) return;
try
{
Settings.Save(Environment.SettingsPath);
}
catch (Exception ex) when (ex is System.IO.IOException or UnauthorizedAccessException)
{
Log.Warning("app", "Settings not saved", ex);
}
// Every settings change passes here, Settings › Advanced › Logs, its Reset and an imported file included.
ApplyLogSettings();
}
/// Settings › Advanced › Logs to the log files, from the next line on (owner review 2, R11).
private void ApplyLogSettings()
{
if (_log is not null) AppLogging.Apply(_log, Settings);
}
protected override void OnExit(ExitEventArgs e)
{
// The mutex stays until the services have stopped, so a launch now waits for this one to exit.
_instance?.StopListening();
SaveSettings();
if (MainWindow?.DataContext is ShellViewModel shell) shell.Dispose();
try
{
// Data and engine code continue on the thread pool, so waiting here cannot deadlock the dispatcher.
if (Services is not null && !Services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(10)))
Log.Warning("app", "Services did not stop within 10 s");
}
catch (AggregateException ex)
{
Log.Warning("app", "Services stopped with an error", ex);
}
_instance?.Dispose();
Log.Info("app", "Chronos exiting");
_log?.Dispose();
if (Environment.IsCapture) Environment.DeleteCaptureData();
base.OnExit(e);
}
private void OnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
Log.Error("app", "Unhandled UI exception", e.Exception);
if (MainWindow?.DataContext is ShellViewModel shell)
{
shell.ReportError(e.Exception);
e.Handled = true;
}
}
}