using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Titano.App.Archiving;
using Titano.App.DesignTime;
using Titano.App.Import;
using Titano.App.Settings;
using Titano.Core.Diagnostics;
using Titano.Ui.Theming;
namespace Titano.App.Shell;
///
/// Titano.exe --capture <dir>: renders every client screen at 1440×900 in the dark and light themes to
/// <screen>-<theme>.png from (first run on an empty index, then a populated
/// one), for visual review and phase reports (BRIEF §20.2), then exits.
///
public static class ScreenCapture
{
private static readonly AppTheme[] Themes = [AppTheme.Dark, AppTheme.Light];
public static async Task RunAsync(MainWindow window, ShellViewModel shell, SampleData sample, string directory)
{
var written = 0;
try
{
Directory.CreateDirectory(directory);
window.WindowStartupLocation = WindowStartupLocation.Manual;
window.Left = -20000;
window.Top = -20000;
window.Width = 1440;
window.Height = 900;
window.ShowActivated = false;
window.ShowInTaskbar = false;
window.Show();
// First run: empty index, nothing connected, the welcome dialog over the empty Library.
await sample.OpenEmptyAsync();
await shell.StartAsync();
foreach (var theme in Themes)
{
ThemeManager.Apply(theme);
shell.Navigate(SectionKey.Library);
shell.ShowWelcome();
shell.Welcome!.ShowDiscovered(new Server.DiscoveredServer("Studio NAS", "https://nas.local:8443"));
written += await SaveAsync(window, directory, "welcome", theme);
shell.CompleteWelcome();
written += await SaveAsync(window, directory, "library-empty", theme);
shell.Navigate(SectionKey.Server);
written += await SaveAsync(window, directory, "server-signedout", theme);
}
// A populated archive, jobs in every state and a signed-in server.
await sample.FillAsync();
await shell.Library.RefreshAsync();
await shell.Jobs.ReloadAsync();
await shell.Services.Server.RestoreAsync();
shell.About.SetResult(null);
await shell.Settings.DetectEncodersAsync();
await shell.Settings.SelfTestAsync();
foreach (var theme in Themes)
{
ThemeManager.Apply(theme);
shell.Library.LayoutIndex = 0;
shell.Library.ClearSelectionCommand.Execute(null);
shell.Navigate(SectionKey.Library);
written += await SaveAsync(window, directory, "library", theme, waitForThumbnails: shell);
if (shell.Library.Items.Count > 0) shell.Library.Items[0].IsSelected = true;
written += await SaveAsync(window, directory, "library-selection", theme, waitForThumbnails: shell);
shell.Library.LayoutIndex = 1;
written += await SaveAsync(window, directory, "library-list", theme, waitForThumbnails: shell);
shell.Library.LayoutIndex = 0;
shell.Library.ClearSelectionCommand.Execute(null);
shell.Navigate(SectionKey.Jobs);
if (shell.Jobs.Rows.Count > 0) shell.Jobs.Rows[0].IsExpanded = true;
written += await SaveAsync(window, directory, "jobs", theme);
shell.Navigate(SectionKey.Server);
written += await SaveAsync(window, directory, "server", theme);
shell.Navigate(SectionKey.Settings);
foreach (var page in Enum.GetValues())
{
shell.Settings.Page = page;
written += await SaveAsync(window, directory, "settings-" + page.ToString().ToLowerInvariant(), theme);
}
shell.Navigate(SectionKey.About);
written += await SaveAsync(window, directory, "about", theme);
shell.Navigate(SectionKey.Sequence);
written += await SaveAsync(window, directory, "sequence", theme);
foreach (var state in ImportScenes.States)
{
DismissToasts(window);
await ImportScenes.ShowAsync(shell, state);
if (!ImportScenes.ShowsToast(state)) DismissToasts(window);
written += await SaveAsync(window, directory, "import-" + state, theme);
}
DismissToasts(window);
foreach (var view in ArchiveScenes.Views)
{
await ArchiveScenes.ShowAsync(shell, view);
written += await SaveAsync(window, directory, "archive-" + view, theme);
}
}
Log.Info("capture", $"{written} screenshot(s) written to {Path.GetFullPath(directory)}");
if (written == 0) Environment.ExitCode = 1;
}
catch (Exception ex)
{
Log.Error("capture", "Capture failed", ex);
Environment.ExitCode = 1;
}
finally
{
Application.Current.Shutdown();
}
}
/// Toasts of one screen's scene stay out of the next screen's picture.
private static void DismissToasts(MainWindow window)
{
foreach (var toast in window.Toasts.Toasts.ToList()) window.Toasts.Dismiss(toast);
}
private static async Task SaveAsync(Window window, string directory, string screen, AppTheme theme, ShellViewModel? waitForThumbnails = null)
{
await Settle(window);
if (waitForThumbnails?.Services.Thumbnails is { } thumbnails)
{
// Thumbnails decode on the thread pool; give them a moment, then settle again.
for (var i = 0; i < 40 && thumbnails.PendingLoads > 0; i++) await Task.Delay(50);
await Task.Delay(100);
await Settle(window);
}
return Save(window, Path.Combine(directory, $"{screen}-{theme.ToString().ToLowerInvariant()}.png")) ? 1 : 0;
}
private static async Task Settle(Window window)
{
window.UpdateLayout();
// Let bindings, templates, async continuations and deferred renders complete.
await window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
await Task.Delay(30);
await window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
window.UpdateLayout();
}
private static bool Save(Window window, string path)
{
if (VisualTreeHelper.GetChildrenCount(window) == 0) window.ApplyTemplate();
if (VisualTreeHelper.GetChildrenCount(window) == 0)
{
Log.Warning("capture", "Window has no visual tree; nothing to render");
return false;
}
var root = (FrameworkElement)VisualTreeHelper.GetChild(window, 0);
var dpi = VisualTreeHelper.GetDpi(window);
var width = (int)Math.Ceiling(root.ActualWidth * dpi.DpiScaleX);
var height = (int)Math.Ceiling(root.ActualHeight * dpi.DpiScaleY);
if (width <= 0 || height <= 0)
{
Log.Warning("capture", $"Root element has no size ({root.ActualWidth}×{root.ActualHeight}); skipped {Path.GetFileName(path)}");
return false;
}
var bitmap = new RenderTargetBitmap(width, height, dpi.PixelsPerInchX, dpi.PixelsPerInchY, PixelFormats.Pbgra32);
bitmap.Render(root);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
using var stream = File.Create(path);
encoder.Save(stream);
return true;
}
}