diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml.cs index 6e5ba83..762cc8e 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml.cs +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml.cs @@ -24,16 +24,16 @@ public partial class RecipeEditor : UserControl if (_host is not null) _host.Closing -= Closing; _host = null; UnbindRecording(); - if (_model is not null) { _model.PropertyChanged -= ModelChanged; _model.AgentChatMessages.CollectionChanged -= ChatChanged; _ = _model.ShutdownAsync(); } + if (_model is not null) { _model.PropertyChanged -= ModelChanged; _model.AgentChatMessages.CollectionChanged -= ChatChanged; _model.ConfirmCloseAsync = null; _ = _model.ShutdownAsync(); } }; } private void BindModel() { if (!ReferenceEquals(_model, DataContext)) { - if (_model is not null) { _model.PropertyChanged -= ModelChanged; _model.AgentChatMessages.CollectionChanged -= ChatChanged; } + if (_model is not null) { _model.PropertyChanged -= ModelChanged; _model.AgentChatMessages.CollectionChanged -= ChatChanged; _model.ConfirmCloseAsync = null; } _model = DataContext as RecipeEditorViewModel; - if (_model is not null) { _model.PropertyChanged += ModelChanged; _model.AgentChatMessages.CollectionChanged += ChatChanged; } + if (_model is not null) { _model.PropertyChanged += ModelChanged; _model.AgentChatMessages.CollectionChanged += ChatChanged; _model.ConfirmCloseAsync ??= ConfirmSaveOnCloseAsync; } } BindRecording(); } @@ -96,15 +96,36 @@ public partial class RecipeEditor : UserControl } private async void Closing(object? sender, WindowClosingEventArgs e) { - if (_closedSafely || _model?.SopRecording is null) return; - if (_closing) { e.Cancel = true; return; } - _closing = true; _dialog?.Close(false); - var shutdown = _model.ShutdownAsync(); - // The Close command already awaited shutdown. Let Prism finish that close in one pass. - if (shutdown.IsCompleted) { _closedSafely = true; return; } + if (_closedSafely || _model is null) return; + if (_model.CanCloseDialog()) { _closedSafely = true; return; } e.Cancel = true; - await shutdown; - _closedSafely = true; - if (sender is Window host) Dispatcher.UIThread.Post(host.Close); + if (_closing) { e.Cancel = true; return; } + _closing = true; + try + { + if (!await _model.PrepareCloseAsync()) return; + _closedSafely = true; + if (sender is Window host) Dispatcher.UIThread.Post(host.Close); + } + finally { _closing = false; } + } + + private async Task ConfirmSaveOnCloseAsync() + { + if (_dialog is not null || TopLevel.GetTopLevel(this) is not Window owner) return RecipeCloseChoice.Cancel; + var dialog = new Window { Title = "保存配方", Width = 440, SizeToContent = SizeToContent.Height, CanResize = false, + WindowStartupLocation = WindowStartupLocation.CenterOwner }; + var actions = new StackPanel { Orientation = Avalonia.Layout.Orientation.Horizontal, + HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right, Spacing = 8 }; + var save = new Button { Name = "SaveRecipeAndCloseButton", Content = "保存并关闭", IsDefault = true }; + var discard = new Button { Name = "DiscardRecipeAndCloseButton", Content = "不保存" }; + save.Click += (_, _) => dialog.Close(RecipeCloseChoice.Save); + discard.Click += (_, _) => dialog.Close(RecipeCloseChoice.Discard); + actions.Children.Add(save); actions.Children.Add(discard); + dialog.Content = new StackPanel { Margin = new Avalonia.Thickness(20), Spacing = 18, + Children = { new TextBlock { Text = "关闭编辑窗口前,是否保存当前配方修改?", TextWrapping = Avalonia.Media.TextWrapping.Wrap }, actions } }; + _dialog = dialog; + try { return await dialog.ShowDialog(owner); } + finally { _dialog = null; } } } diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs index 022d33e..5e69a68 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs @@ -28,6 +28,8 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware private readonly HashSet _observedStepNodes = []; private string _saveStatus = ""; private bool _closingDialog; + private bool _closeApproved; + public Func>? ConfirmCloseAsync { get; set; } public string SaveStatus { get => _saveStatus; private set => SetProperty(ref _saveStatus, value); } public string NameValidationMessage => RecipeWorkspace.GetNameError(Recipe.Name) ?? ""; private BitmapSource? _previewImage; @@ -103,7 +105,7 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware /// 保存 public DelegateCommand SaveCommand { get; private set; } = null!; - /// 关闭编辑器,未保存的修改不写入文件 + /// 确认保存后关闭编辑器 public DelegateCommand CloseCommand { get; private set; } = null!; /// @@ -114,8 +116,7 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware SaveCommand = new DelegateCommand(Save, () => !IsCapturing && !IsAgentBusy && NameValidationMessage.Length == 0); CloseCommand = new DelegateCommand(async () => { - _closingDialog = true; CloseCommand.RaiseCanExecuteChanged(); - await ShutdownAsync(); RequestClose.Invoke(ButtonResult.Cancel); + if (await PrepareCloseAsync()) RequestClose.Invoke(ButtonResult.Cancel); }, () => !IsCapturing && !_closingDialog); CaptureStepKeyFrameCommand = new DelegateCommand(CaptureStepKeyFrame); TestStepDecisionCommand = new DelegateCommand(async () => await (_stepTestTask = TestStepDecisionAsync()), @@ -165,7 +166,29 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware } /// - public bool CanCloseDialog() => !IsCapturing; + public bool CanCloseDialog() => _closeApproved; + + public async Task PrepareCloseAsync() + { + if (_closeApproved) return true; + if (_closingDialog || IsCapturing) return false; + _closingDialog = true; + CloseCommand.RaiseCanExecuteChanged(); + try + { + var choice = ConfirmCloseAsync is { } confirm ? await confirm() : RecipeCloseChoice.Cancel; + if (choice == RecipeCloseChoice.Cancel) return false; + if (choice == RecipeCloseChoice.Save && !TrySave()) return false; + await ShutdownAsync(); + _closeApproved = true; + return true; + } + finally + { + _closingDialog = false; + CloseCommand.RaiseCanExecuteChanged(); + } + } /// public void OnDialogClosed() @@ -281,18 +304,20 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware } } - private void Save() + private void Save() => TrySave(); + + private bool TrySave() { SaveStatus = ""; if (RecipeWorkspace.GetNameError(Recipe.Name) is { } nameError) { SaveStatus = nameError; - return; + return false; } var fileName = Recipe.Name; if (!_isNew && fileName != Path.GetFileNameWithoutExtension(_path)) - { SaveStatus = "已有配方名与文件名一致,不可在编辑器中改名"; return; } + { SaveStatus = "已有配方名与文件名一致,不可在编辑器中改名"; return false; } var path = string.IsNullOrEmpty(_path) ? Path.Combine(_directory, fileName, fileName + ".yaml") : _path; @@ -318,12 +343,15 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware SaveStatus = $"已保存 {Path.GetFileName(_path)}"; StepTransferStatus = ""; _onSaved?.Invoke(Path.GetFileName(_path)); + return true; } catch (Exception ex) { // 写盘失败(文件被占用/只读)留给用户看,别让整个编辑器跟着炸 Warnings.Clear(); Warnings.Add("保存失败:" + ex.Message); + SaveStatus = "保存失败:" + ex.Message; + return false; } } @@ -361,3 +389,5 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware private void StepChanged(object? sender, PropertyChangedEventArgs e) => RefreshWarnings(); } + +public enum RecipeCloseChoice { Cancel, Save, Discard } diff --git a/tests/Avalonia.Smoke/Program.cs b/tests/Avalonia.Smoke/Program.cs index d340f35..f0d2230 100644 --- a/tests/Avalonia.Smoke/Program.cs +++ b/tests/Avalonia.Smoke/Program.cs @@ -86,6 +86,8 @@ internal static class Smoke var userCameraBefore=File.Exists(userCameraPath)?File.ReadAllBytes(userCameraPath):null; await Task.Delay(150); var app=(App)Application.Current!;var window=lifetime.MainWindow!; + if(Environment.GetCommandLineArgs().Contains("--recipe-close-only")) + { await CheckRecipeClose(app,lifetime);_exit=0;return; } if(Environment.GetCommandLineArgs().Contains("--runtime-settings-only")) { var model=app.Container.Resolve(); @@ -206,10 +208,12 @@ internal static class Smoke Check(modal.Width==1180&&modal.Height==880&&modal.DataContext is RecipeEditorViewModel,"Edit command opens a recipe dialog sized for embedded annotation and training"); Check(ReferenceEquals(((RecipeEditorViewModel)modal.DataContext!).SopRecording!.SelectedCamera,sop.SelectedCamera),"SOP recording inherits the runtime settings camera"); ((RecipeEditorViewModel)modal.DataContext!).CloseCommand.Execute(); + await ChooseRecipeClose(modal,"SaveRecipeAndCloseButton"); for(var i=0;i<100&&lifetime.Windows.Contains(modal);i++)await Task.Delay(20); Check(!lifetime.Windows.Contains(modal),"Recipe close command respects the Prism dialog lifecycle"); sop.EditRecipeCommand.Execute();await Task.Delay(150); var titlebarModal=lifetime.Windows.OfType().Single();titlebarModal.Close(); + await ChooseRecipeClose(titlebarModal,"DiscardRecipeAndCloseButton"); for(var i=0;i<100&&lifetime.Windows.Contains(titlebarModal);i++)await Task.Delay(20); Check(!lifetime.Windows.Contains(titlebarModal),"Titlebar close awaits SOP camera shutdown and closes the Prism dialog"); var recorder=new CameraWindow(new CameraViewModel(new FakeCamera(),Path.Combine(Path.GetTempPath(),"sophelper-avalonia-smoke"))); @@ -1047,6 +1051,42 @@ internal static class Smoke window.UpdateLayout(); using var image=new RenderTargetBitmap(new PixelSize((int)window.Bounds.Width,(int)window.Bounds.Height));image.Render(window);image.Save(Path.Combine(Output,name+".png")); } + private static async Task ChooseRecipeClose(Window owner,string buttonName) + { + for(var i=0;i<100&&!owner.OwnedWindows.Any();i++)await Task.Delay(20); + var prompt=owner.OwnedWindows.Single(); + var buttons=prompt.GetVisualDescendants().OfType