using AstroFrame.Engine;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Platform.Storage;
using Avalonia.Threading;
using Avalonia.Styling;
using Avalonia.VisualTree;
using System.Security.Cryptography;
using System.Text;
namespace AstroFrame.Desktop;
public sealed class MainWindow:Window
{
Project? project;string projectDirectory="";CancellationTokenSource? cancellation;bool busy,refreshing,saving;
readonly SemaphoreSlim saveGate=new(1);
readonly ComboBox sessions=new(){Width=380,MinWidth=290,HorizontalAlignment=HorizontalAlignment.Left};
readonly ListBox frames=new();
readonly ComboBox filter=new(){ItemsSource=new[]{"All decisions","REVIEW","REJECT","KEEP","Manual decisions"},SelectedIndex=0,MinWidth=135};
readonly ComboBox sort=new(){ItemsSource=new[]{"Capture time","Most concerning","Lowest star count","Lowest stellar flux","Highest FWHM"},SelectedIndex=0,MinWidth=155};
readonly ComboBox metric=new(){ItemsSource=QualityChart.Metrics.Select(x=>x.Name).ToArray(),SelectedIndex=0,MinWidth=145};
readonly QualityChart chart=new();
readonly ExposureView preview=new(),comparison=new();
readonly Border previewPanel,comparisonBorder,previewControls;
readonly ComboBox previewMode=new(){ItemsSource=new[]{"Frame view","Nebula view"},SelectedIndex=0,MinWidth=150};
readonly Slider displayStretch=new(){Minimum=.08,Maximum=.40,Value=.18};
readonly StackPanel inspector=new(){Spacing=9};
readonly Grid previewWorkspace=new(){ColumnDefinitions=new("*,0"),Margin=new(0,8,0,6)};
readonly Border details=new();
readonly TextBlock queueTitle=Palette.Label("Exposures",14),position=Palette.Label("",11,Palette.Muted),stretchValue=Palette.Label("0.18",11,Palette.Muted);
readonly TextBlock exposureName=Palette.Label("",11,Palette.Muted),exposureStatus=Palette.Label("",12);
readonly TextBlock title=Palette.Label("Light frames",18),subtitle=Palette.Label("Choose a folder to begin",11,Palette.Muted);
readonly TextBlock status=Palette.Label("",11,Palette.Muted);
readonly TextBlock keep=Palette.Label("—",22,Palette.Keep),review=Palette.Label("—",22,Palette.Review),reject=Palette.Label("—",22,Palette.Reject),integration=Palette.Label("—",22);
readonly TextBlock keepTime=Palette.Label("",11,Palette.Muted),reviewTime=Palette.Label("",11,Palette.Muted),rejectTime=Palette.Label("",11,Palette.Muted),totalTime=Palette.Label("",11,Palette.Muted);
readonly ProgressBar progress=new(){Height=3,Minimum=0,Maximum=100,IsVisible=false};
readonly Button analyze=Button("Analyze lights",true),export=Button("Export accepted"),stop=Button("Cancel");
readonly CheckBox spatial=new(){Content="Spatial overlay",FontSize=12},compare=new(){Content="Compare nearby",FontSize=12};
Frame? selected;List visible=[];
readonly Stack<(Frame Frame,Verdict? Verdict,string Note,DateTime? At)> undo=[];
public MainWindow()
{
previewPanel=Panel(preview);comparisonBorder=Panel(comparison);
var displayPanel=new Grid{RowDefinitions=new("Auto,48")};var stretchHeading=new Grid{ColumnDefinitions=new("*,Auto")};stretchHeading.Children.Add(Palette.Label("Preview stretch",11,Palette.Muted));Grid.SetColumn(stretchValue,1);stretchHeading.Children.Add(stretchValue);displayPanel.Children.Add(stretchHeading);
var stretchRow=new Grid{ColumnDefinitions=new("*,Auto")};displayStretch.MinHeight=44;displayStretch.VerticalAlignment=VerticalAlignment.Center;displayStretch.Margin=new(0,0,12,0);stretchRow.Children.Add(displayStretch);
var resetStretch=Button("Reset");resetStretch.Padding=new(9,5);resetStretch.FontSize=11;resetStretch.VerticalAlignment=VerticalAlignment.Center;resetStretch.Click+=(_,_)=>displayStretch.Value=.18;Grid.SetColumn(resetStretch,1);stretchRow.Children.Add(resetStretch);Grid.SetRow(stretchRow,1);displayPanel.Children.Add(stretchRow);previewControls=new(){Child=displayPanel};
// Keep the native slider's input behavior; give its thumb a visible silver face and room for the full circle.
Styles.Add(new Style(x=>x.OfType().Template().OfType()){Setters={new Setter(Avalonia.Controls.Primitives.TemplatedControl.TemplateProperty,new FuncControlTemplate((_,_)=>new Border{Width=20,Height=20,CornerRadius=new(10),Background=Palette.Accent,BorderBrush=Palette.Panel,BorderThickness=new(3),HorizontalAlignment=HorizontalAlignment.Center,VerticalAlignment=VerticalAlignment.Center}))}});
previewMode.SelectionChanged+=(_,_)=>{preview.Nebula=comparison.Nebula=previewMode.SelectedIndex==1;preview.RefreshDisplay();comparison.RefreshDisplay();};
displayStretch.PropertyChanged+=(_,e)=>{if(e.Property==Slider.ValueProperty){stretchValue.Text=displayStretch.Value.ToString("0.00");preview.Stretch=comparison.Stretch=displayStretch.Value;preview.RefreshDisplay();comparison.RefreshDisplay();}};
Title="AstroFrame";Width=1450;Height=940;MinWidth=1120;MinHeight=740;Background=Palette.Background;FontFamily="Inter";FontSize=13;
ExtendClientAreaToDecorationsHint=true;ExtendClientAreaChromeHints=Avalonia.Platform.ExtendClientAreaChromeHints.PreferSystemChrome;ExtendClientAreaTitleBarHeightHint=36;
Icon=new WindowIcon(Avalonia.Platform.AssetLoader.Open(new Uri("avares://AstroFrame.Desktop/Assets/astroframe.ico")));
var root=new Grid{RowDefinitions=new("Auto,Auto,*,Auto")};
var headerSurface=new Grid{RowDefinitions=new("36,38"),Background=Palette.Background};root.Children.Add(headerSurface);
var titlebar=new Grid{ColumnDefinitions=new("Auto,*"),Background=Brushes.Transparent,Margin=new(18,0,145,0)};
Win32Properties.SetNonClientHitTestResult(titlebar,Win32Properties.Win32HitTestValue.Caption);
titlebar.Children.Add(new Image{Source=new Avalonia.Media.Imaging.Bitmap(Avalonia.Platform.AssetLoader.Open(new Uri("avares://AstroFrame.Desktop/Assets/astroframe.png"))),Width=24,Height=24});
var brand=Palette.Label("AstroFrame",13);brand.FontWeight=FontWeight.SemiBold;brand.Margin=new(9,0,0,0);brand.VerticalAlignment=VerticalAlignment.Center;Grid.SetColumn(brand,1);titlebar.Children.Add(brand);
titlebar.PointerPressed+=(_,e)=>{if(e.GetCurrentPoint(this).Properties.IsLeftButtonPressed){if(e.ClickCount==2)WindowState=WindowState==WindowState.Maximized?WindowState.Normal:WindowState.Maximized;else BeginMoveDrag(e);e.Handled=true;}};
headerSurface.Children.Add(titlebar);
var header=new Grid{ColumnDefinitions=new("*,Auto"),Margin=new(22,0,22,2)};Grid.SetRow(header,1);
var heading=new StackPanel{Orientation=Orientation.Horizontal,Spacing=12,VerticalAlignment=VerticalAlignment.Center};title.MinWidth=140;title.MaxWidth=330;title.TextTrimming=TextTrimming.CharacterEllipsis;title.VerticalAlignment=subtitle.VerticalAlignment=VerticalAlignment.Center;heading.Children.Add(title);heading.Children.Add(subtitle);header.Children.Add(heading);
var toolbar=new WrapPanel{Orientation=Orientation.Horizontal,HorizontalAlignment=HorizontalAlignment.Right,VerticalAlignment=VerticalAlignment.Center};
foreach(var b in new[]{analyze,export}){b.Margin=new(8,1,0,1);toolbar.Children.Add(b);}Grid.SetColumn(toolbar,1);header.Children.Add(toolbar);headerSurface.Children.Add(header);
var scope=new Grid{ColumnDefinitions=new("*,Auto"),Margin=new(20,7,20,7)};
sessions.ItemTemplate=new FuncDataTemplate((text,_)=>SessionRow(text??""));sessions.SelectionChanged+=(_,_)=>{if(!refreshing)RefreshFrames();};scope.Children.Add(sessions);
var stats=new StackPanel{Orientation=Orientation.Horizontal,Spacing=28,VerticalAlignment=VerticalAlignment.Center};
foreach(var item in new[]{Summary("KEEP",keep,keepTime),Summary("REVIEW",review,reviewTime),Summary("REJECT",reject,rejectTime),Summary("ACCEPTED TIME",integration,totalTime)})stats.Children.Add(item);
Grid.SetColumn(stats,1);scope.Children.Add(stats);var scopeBorder=new Border{BorderBrush=Palette.Line,BorderThickness=new(0,1,0,1),Child=scope};Grid.SetRow(scopeBorder,1);root.Children.Add(scopeBorder);
var body=new Grid{ColumnDefinitions=new("280,1.27*,1*"),Margin=new(18,16,18,0)};Grid.SetRow(body,2);
var queue=new Grid{RowDefinitions=new("Auto,Auto,Auto,*")};
queueTitle.Margin=new(12,12,12,10);queue.Children.Add(queueTitle);
var listControls=new StackPanel{Spacing=6,Margin=new(12,0,12,8)};filter.MinWidth=128;filter.FontSize=11;filter.HorizontalAlignment=HorizontalAlignment.Stretch;listControls.Children.Add(filter);
sort.HorizontalAlignment=HorizontalAlignment.Stretch;sort.FontSize=11;listControls.Children.Add(sort);Grid.SetRow(listControls,1);queue.Children.Add(listControls);
var columns=new Grid{ColumnDefinitions=new("*,61,48,44"),Margin=new(14,8,14,8)};int ci=0;foreach(string label in new[]{"Time (UTC)","Decision","Stars","FWHM"}){var text=Palette.Label(label,10,Palette.Muted);if(ci>1)text.HorizontalAlignment=HorizontalAlignment.Right;Grid.SetColumn(text,ci++);columns.Children.Add(text);}Grid.SetRow(columns,2);queue.Children.Add(columns);
frames.Background=Brushes.Transparent;frames.Padding=new(0);frames.ItemTemplate=new FuncDataTemplate((f,_)=>f==null?new Border():FrameRow(f));frames.SelectionChanged+=(_,_)=>{if(!refreshing&&frames.SelectedItem is Frame f)Select(f);};Grid.SetRow(frames,3);queue.Children.Add(frames);var queuePanel=Panel(queue);queuePanel.Margin=new(0,0,16,0);body.Children.Add(queuePanel);
var center=new Grid{RowDefinitions=new("Auto,Auto,*,Auto,Auto,Auto"),Margin=new(0,0,16,0),MinWidth=310};Grid.SetColumn(center,1);body.Children.Add(center);
var previewHeading=new Grid{ColumnDefinitions=new("*,Auto"),Margin=new(0,6,0,8)};previewHeading.Children.Add(Palette.Label("Exposure preview",14));position.HorizontalAlignment=HorizontalAlignment.Right;position.VerticalAlignment=VerticalAlignment.Center;Grid.SetColumn(position,1);previewHeading.Children.Add(position);center.Children.Add(previewHeading);
var viewRow=new Grid{ColumnDefinitions=new("Auto,*,Auto")};previewMode.MinWidth=125;previewMode.FontSize=11;viewRow.Children.Add(previewMode);var switches=new StackPanel{Orientation=Orientation.Horizontal,VerticalAlignment=VerticalAlignment.Center};spatial.Content="Overlay";compare.Content="Compare";spatial.Margin=new(0,0,12,0);switches.Children.Add(spatial);switches.Children.Add(compare);Grid.SetColumn(switches,2);viewRow.Children.Add(switches);Grid.SetRow(viewRow,1);center.Children.Add(viewRow);
previewWorkspace.Children.Add(previewPanel);Grid.SetColumn(comparisonBorder,1);previewWorkspace.Children.Add(comparisonBorder);comparisonBorder.IsVisible=false;Grid.SetRow(previewWorkspace,2);center.Children.Add(previewWorkspace);
Grid.SetRow(previewControls,3);center.Children.Add(previewControls);
var caption=new StackPanel{Spacing=4,Margin=new(0,0,0,12)};exposureName.TextTrimming=TextTrimming.CharacterEllipsis;caption.Children.Add(exposureName);caption.Children.Add(exposureStatus);Grid.SetRow(caption,4);center.Children.Add(caption);
var decisions=new Grid{ColumnDefinitions=new("*,*,*,Auto")};int decisionColumn=0;
foreach(var verdict in new[]{Verdict.Keep,Verdict.Review,Verdict.Reject}){var b=Button(verdict.ToString());b.Foreground=Palette.Verdict(verdict);b.Margin=new(0,0,6,0);b.HorizontalAlignment=HorizontalAlignment.Stretch;ToolTip.SetTip(b,$"{verdict} · {(int)verdict+1}");b.Click+=async(_,_)=>await Override(verdict);Grid.SetColumn(b,decisionColumn++);decisions.Children.Add(b);}var resetDecision=Button("Reset");resetDecision.Click+=async(_,_)=>await Override(null,false);Grid.SetColumn(resetDecision,3);decisions.Children.Add(resetDecision);Grid.SetRow(decisions,5);center.Children.Add(decisions);
var right=new Grid{RowDefinitions=new("2*,3*"),MinWidth=320};Grid.SetColumn(right,2);body.Children.Add(right);
var graphs=new Grid{RowDefinitions=new("Auto,*"),Margin=new(12)};var graphHeader=new Grid{ColumnDefinitions=new("*,Auto"),Margin=new(0,0,0,8)};var graphTitle=Palette.Label("Quality",14);graphTitle.VerticalAlignment=VerticalAlignment.Center;graphHeader.Children.Add(graphTitle);metric.MaxWidth=205;metric.FontSize=11;Grid.SetColumn(metric,1);graphHeader.Children.Add(metric);graphs.Children.Add(graphHeader);Grid.SetRow(chart,1);graphs.Children.Add(chart);var graphPanel=Panel(graphs);graphPanel.Margin=new(0,0,0,14);right.Children.Add(graphPanel);
inspector.Margin=new(14);details.Child=new ScrollViewer{Content=inspector,HorizontalScrollBarVisibility=Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled};details.Background=Palette.Panel;details.BorderBrush=Palette.Line;details.BorderThickness=new(.5);details.CornerRadius=new(2);Grid.SetRow(details,1);right.Children.Add(details);root.Children.Add(body);
var footer=new Grid{RowDefinitions=new("Auto,Auto"),Margin=new(20,7,20,7)};footer.Children.Add(progress);var footerLine=new Grid{ColumnDefinitions=new("*,Auto")};footerLine.Children.Add(status);stop.IsVisible=false;Grid.SetColumn(stop,1);footerLine.Children.Add(stop);Grid.SetRow(footerLine,1);footer.Children.Add(footerLine);Grid.SetRow(footer,3);root.Children.Add(footer);Content=root;
analyze.Click+=async(_,_)=>await Analyze();export.Click+=async(_,_)=>await ExportAccepted();stop.Click+=(_,_)=>cancellation?.Cancel();
filter.SelectionChanged+=(_,_)=>{if(!refreshing)RefreshFrames();};sort.SelectionChanged+=(_,_)=>{if(!refreshing)RefreshFrames();};metric.SelectionChanged+=(_,_)=>{chart.Metric=QualityChart.Metrics[Math.Max(0,metric.SelectedIndex)];chart.InvalidateVisual();};
chart.FrameClicked+=f=>{if(!visible.Contains(f))filter.SelectedIndex=0;frames.SelectedItem=f;frames.ScrollIntoView(f);Select(f);};
spatial.IsCheckedChanged+=(_,_)=>{preview.Spatial=spatial.IsChecked==true;preview.InvalidateVisual();};compare.IsCheckedChanged+=(_,_)=>UpdateComparison();
KeyDown+=async(_,e)=>
{
if(busy||e.Source is TextBox)return;
if(e.Key==Key.J){Move(-1);e.Handled=true;}if(e.Key==Key.K){Move(1);e.Handled=true;}
if(e.Key is Key.D1 or Key.NumPad1){await Override(Verdict.Keep);e.Handled=true;}if(e.Key is Key.D2 or Key.NumPad2){await Override(Verdict.Review);e.Handled=true;}if(e.Key is Key.D3 or Key.NumPad3){await Override(Verdict.Reject);e.Handled=true;}
if(e.Key==Key.Z&&e.KeyModifiers.HasFlag(KeyModifiers.Control)&&undo.Count>0){var item=undo.Pop();item.Frame.Override=item.Verdict;item.Frame.Note=item.Note;item.Frame.ReviewedAt=item.At;await Save();RefreshFrames(item.Frame);e.Handled=true;}
};
Closing+=(_,e)=>{if(busy){e.Cancel=true;cancellation?.Cancel();status.Text="Stopping safely; close again when finished";}};
Closed+=(_,_)=>{preview.Dispose();comparison.Dispose();};ShowEmpty();
}
static Button Button(string text,bool primary=false)=>new(){Content=text,Padding=new(12,7),CornerRadius=new(2),Background=primary?Palette.Accent:Palette.Raised,Foreground=primary?Palette.Background:Palette.Text};
static Border Panel(Control child)=>new(){Background=Palette.Panel,BorderBrush=Palette.Line,BorderThickness=new(.5),CornerRadius=new(2),ClipToBounds=true,Child=child};
static Control Summary(string label,TextBlock value,TextBlock detail)
{var s=new StackPanel{Spacing=2};var line=new StackPanel{Orientation=Orientation.Horizontal,Spacing=7};line.Children.Add(value);var caption=Palette.Label(label,9,Palette.Muted);caption.VerticalAlignment=VerticalAlignment.Bottom;caption.Margin=new(0,0,0,4);line.Children.Add(caption);s.Children.Add(line);s.Children.Add(detail);return s;}
Control SessionRow(string text)
{
var parts=text.Split('·',StringSplitOptions.TrimEntries);var s=new StackPanel{Spacing=3,Margin=new(2,2)};s.Children.Add(Palette.Label(parts[0],14));
if(project!=null){var scoped=project.Frames.Where(f=>text=="All sessions"||f.Session==text).ToArray();string date=parts.Length>1?parts[1]+" UTC · ":"";s.Children.Add(Palette.Label(date+$"{scoped.Length:N0} lights"+(parts.Length>3?" · "+parts[3]:""),10,Palette.Muted));}return s;
}
static Control FrameRow(Frame f)
{
var g=new Grid{ColumnDefinitions=new("*,61,48,44"),Margin=new(8,13)};var time=new StackPanel{Spacing=3};time.Children.Add(Palette.Label(f.Time.Length>=8?f.Time[^8..]:f.Time,11));time.Children.Add(Palette.Label(f.Time.Length>8?f.Time[..^9]:"",9,Palette.Muted));g.Children.Add(time);
var badge=Palette.Label(f.Status,10,Palette.Verdict(f.Effective));badge.FontWeight=FontWeight.SemiBold;badge.VerticalAlignment=VerticalAlignment.Center;Grid.SetColumn(badge,1);g.Children.Add(badge);
var stars=Palette.Label(f.StarCount.ToString("N0"),11);stars.VerticalAlignment=VerticalAlignment.Center;stars.HorizontalAlignment=HorizontalAlignment.Right;Grid.SetColumn(stars,2);g.Children.Add(stars);var width=Palette.Label(f.Fwhm.ToString("0.00"),11,Palette.Muted);width.VerticalAlignment=VerticalAlignment.Center;width.HorizontalAlignment=HorizontalAlignment.Right;Grid.SetColumn(width,3);g.Children.Add(width);ToolTip.SetTip(g,f.Name+(f.Override.HasValue?" · Manual decision":"")+" · "+f.Exposure+" s");return g;
}
void ShowEmpty()
{
inspector.Children.Clear();inspector.Children.Add(Palette.Label("Analyze a folder of FITS lights to begin.",12,Palette.Muted));
export.IsEnabled=false;details.IsVisible=false;
}
public void LoadProject(string directory)
{
project=ProjectStore.Load(directory);projectDirectory=directory;undo.Clear();
foreach(var f in project.Frames.Where(f=>f.Error==""))
{var info=new FileInfo(f.Path);if(!info.Exists||info.Length!=f.Length||info.LastWriteTimeUtc.Ticks!=f.Modified){project.Complete=false;f.Warning="Source is missing or changed; reanalyze before export";}}
int sessionCount=project.Frames.Select(f=>f.Session).Distinct().Count();title.Text=project.Name;subtitle.Text=$"{project.Frames.Count:N0} lights · {sessionCount} "+(sessionCount==1?"session":"sessions");
refreshing=true;sessions.ItemsSource=new[]{"All sessions"}.Concat(project.Frames.Select(f=>f.Session).Distinct().Order()).ToArray();sessions.SelectedIndex=0;refreshing=false;
RefreshFrames();status.Text=project.Complete?"":"Incomplete or changed project · reanalyze before exporting";export.IsEnabled=project.Complete;
DesktopState.Remember(directory);
}
void RefreshFrames(Frame? prefer=null)
{
if(project==null)return;refreshing=true;
var scoped=project.Frames.Where(f=>sessions.SelectedIndex<=0||f.Session==(string?)sessions.SelectedItem).OrderBy(f=>f.Timestamp).ToList();
keep.Text=scoped.Count(f=>f.Effective==Verdict.Keep).ToString("N0");review.Text=scoped.Count(f=>f.Effective==Verdict.Review).ToString("N0");reject.Text=scoped.Count(f=>f.Effective==Verdict.Reject).ToString("N0");
string Duration(double seconds)=>TimeSpan.FromSeconds(seconds).TotalHours>=1?$"{seconds/3600:0.0} h":$"{seconds/60:0.0} min";
keepTime.Text=Duration(scoped.Where(f=>f.Effective==Verdict.Keep).Sum(f=>f.Exposure));reviewTime.Text=Duration(scoped.Where(f=>f.Effective==Verdict.Review).Sum(f=>f.Exposure));rejectTime.Text=Duration(scoped.Where(f=>f.Effective==Verdict.Reject).Sum(f=>f.Exposure));integration.Text=keepTime.Text;totalTime.Text=Duration(scoped.Sum(f=>f.Exposure))+" total";
chart.Frames=scoped;
var query=scoped.Where(f=>filter.SelectedIndex switch{1=>f.Effective==Verdict.Review,2=>f.Effective==Verdict.Reject,3=>f.Effective==Verdict.Keep,4=>f.Override!=null,_=>true});
visible=(sort.SelectedIndex switch{1=>query.OrderBy(f=>f.Score),2=>query.OrderBy(f=>f.StarCount),3=>query.OrderBy(f=>f.Transparency),4=>query.OrderByDescending(f=>f.Fwhm),_=>query.OrderBy(f=>f.Timestamp)}).ToList();
queueTitle.Text=$"Exposures · {visible.Count:N0}";
frames.ItemsSource=null;frames.ItemsSource=visible;frames.SelectedItem=prefer!=null&&visible.Contains(prefer)?prefer:visible.FirstOrDefault();refreshing=false;
if(frames.SelectedItem is Frame f)Select(f);else{selected=null;ShowNoSelection();}
chart.InvalidateVisual();
}
public void CaptureSelection(bool rejected=false)
{
if(project==null)return;
var f=rejected?project.Frames.FirstOrDefault(x=>x.Effective==Verdict.Reject):project.Frames.FirstOrDefault(x=>x.Target.Contains("1432"));
if(f==null)return;sessions.SelectedItem=f.Session;filter.SelectedIndex=rejected?2:0;spatial.IsChecked=rejected;compare.IsChecked=rejected;frames.SelectedItem=f;Select(f);
}
public void CaptureExposure(string filename,bool nebula=false)
{
if(project==null)return;var f=project.Frames.First(x=>x.Name.Contains(filename,StringComparison.OrdinalIgnoreCase));sessions.SelectedItem=f.Session;filter.SelectedIndex=0;spatial.IsChecked=false;compare.IsChecked=false;previewMode.SelectedIndex=nebula?1:0;frames.SelectedItem=f;Select(f);
}
public Task WaitForPreviews()=>Task.WhenAll(preview.Loading,comparison.Loading);
public void CaptureMetric(string name)
{
int index=Array.FindIndex(QualityChart.Metrics,m=>m.Name==name);
if(index<0)throw new ArgumentException("Unknown quality metric",nameof(name));metric.SelectedIndex=index;
}
public async Task SmokeTest(string report)
{
if(project==null)throw new InvalidOperationException("Project not loaded");
var results=new List();void Check(bool value,string text){if(!value)throw new Exception(text);results.Add("PASS "+text);}
Width=1120;Height=740;await Task.Delay(150);
var countText=new FormattedText(queueTitle.Text??"",System.Globalization.CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface(queueTitle.FontFamily),queueTitle.FontSize,queueTitle.Foreground);
Check(queueTitle.Bounds.Width>=countText.WidthIncludingTrailingWhitespace,"full project exposure count fits at minimum window size");
string original=projectDirectory;projectDirectory=System.IO.Path.Combine(System.IO.Path.GetDirectoryName(report)!,"smoke-project");Directory.CreateDirectory(System.IO.Path.Combine(projectDirectory,"previews"));
project.Frames=project.Frames.Take(40).ToList();
foreach(var f in project.Frames){var input=ProjectStore.PreviewPath(original,f);if(File.Exists(input))File.Copy(input,ProjectStore.PreviewPath(projectDirectory,f),true);}
RefreshFrames();Check(visible.Count==40,"all-frame filter");
foreach(var f in visible.ToArray())Select(f);Check(preview.Parent==previewPanel,"switching 40 exposures retains preview parent");
compare.IsChecked=true;spatial.IsChecked=true;Select(visible[0]);Select(visible[1]);Check(comparison.Parent==comparisonBorder,"comparison can switch exposures repeatedly");
var reviewed=visible[1];selected=reviewed;reviewed.Note="Existing label";await Override(Verdict.Reject,false);Check(reviewed.Override==Verdict.Reject,"manual override updates verdict");
filter.SelectedIndex=2;Check(visible.Contains(reviewed),"reject filter includes manual override");
var restored=ProjectStore.Load(projectDirectory);Check(restored.Frames.First(f=>f.Id==reviewed.Id).Note=="Existing label","existing notes survive decisions without a note editor");
selected=reviewed;await Override(null,false);Check(reviewed.Override==null,"reset restores automatic verdict");
filter.SelectedIndex=0;sort.SelectedIndex=2;Check(visible[0].StarCount==visible.Min(f=>f.StarCount),"metric sorting");
metric.SelectedIndex=Array.FindIndex(QualityChart.Metrics,m=>m.Name=="Background");Check(chart.Metric.Name=="Background","graph metric switching");
await WaitForPreviews();Check(preview.HasImage,"latest preview loads after rapid exposure switching");
previewMode.SelectedIndex=1;displayStretch.Value=.26;Check(preview.Nebula&&Math.Abs(preview.Stretch-.26)<.001,"nebula view and adjustable stretch render without changing classification");
Width=1120;Height=740;await Task.Delay(100);Check(Bounds.Width>=1120,"minimum window size");
compare.IsChecked=false;await Task.Delay(100);
Check(this.GetVisualDescendants().OfType().Count()==1,"one selectable quality graph");
Check(preview.Bounds.Height>330,"preview grows into available window height");
Check(!this.GetVisualDescendants().OfType