diff --git a/SemiStep/SemiStep.Core/Plc/PlcLifecycleManager.cs b/SemiStep/SemiStep.Core/Plc/PlcLifecycleManager.cs index 75ee64f..f983204 100644 --- a/SemiStep/SemiStep.Core/Plc/PlcLifecycleManager.cs +++ b/SemiStep/SemiStep.Core/Plc/PlcLifecycleManager.cs @@ -230,11 +230,6 @@ private void ReleaseOwnershipLease() lease.Dispose(); } - public async Task> ReadRecipeFromPlcAsync() - { - return await _reader.ReadRecipeFromPlcAsync(); - } - public Result ApplyRecipeFromPlc(Recipe recipe) { return _session.LoadAsCurrentValidated(recipe); diff --git a/SemiStep/SemiStep.Core/Recipes/Import/CsvFileIo.cs b/SemiStep/SemiStep.Core/Recipes/Import/CsvFileIo.cs index d272a0a..3d12ddd 100644 --- a/SemiStep/SemiStep.Core/Recipes/Import/CsvFileIo.cs +++ b/SemiStep/SemiStep.Core/Recipes/Import/CsvFileIo.cs @@ -26,12 +26,20 @@ internal static async Task WriteRecipeFileAsync( try { - await using (var stream = new FileStream( - tempPath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, useAsync: true)) - await using (var writer = new StreamWriter(stream, _fileEncoding)) + var stream = new FileStream( + tempPath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, useAsync: true); + await using (stream.ConfigureAwait(false)) { - CsvMetadata.Serialize(writer, metadata); - await writer.WriteAsync(csvBody.AsMemory()); + var writer = new StreamWriter(stream, _fileEncoding); + await using (writer.ConfigureAwait(false)) + { + CsvMetadata.Serialize(writer, metadata); + await writer.WriteAsync(csvBody.AsMemory()).ConfigureAwait(false); + await writer.FlushAsync().ConfigureAwait(false); + // An await that completes synchronously stays on the caller's thread, so the + // blocking disk flush is moved off it explicitly. + await Task.Run(() => stream.Flush(flushToDisk: true)).ConfigureAwait(false); + } } File.Move(tempPath, filePath, overwrite: true); diff --git a/SemiStep/SemiStep.Core/Recipes/RecipeSession.cs b/SemiStep/SemiStep.Core/Recipes/RecipeSession.cs index 9ef9607..db53468 100644 --- a/SemiStep/SemiStep.Core/Recipes/RecipeSession.cs +++ b/SemiStep/SemiStep.Core/Recipes/RecipeSession.cs @@ -12,7 +12,7 @@ namespace SemiStep.Core.Recipes; /// -/// Owns the live recipe, its dirty flag and the mutations that produce new revisions; runs analyzer and +/// Owns the live recipe, its saved point and the mutations that produce new revisions; runs analyzer and /// formula passes and notifies PLC sync. History lives in , input checks in /// . /// @@ -33,11 +33,14 @@ public sealed class RecipeSession( private readonly StepMutationValidator _stepMutationValidator = new(recipeMetadataRegistry); private readonly IPlcSyncService _syncService = syncService; + // Compared by identity, not equality: a retyped old value stays unsaved, as in text editors. + private Recipe _savedRecipe = Recipe.Empty; + public Recipe Current => Snapshot.IsSuccess ? Snapshot.Value.Recipe : Recipe.Empty; - public bool IsDirty { get; private set; } + public bool IsDirty => !ReferenceEquals(Current, _savedRecipe); public bool IsValid => Snapshot.IsSuccess && !Snapshot.Reasons.OfType().Any(); @@ -59,7 +62,7 @@ public Result Apply(Recipe newRecipe) } _history.Push(Current); - UpdateSnapshot(snapshot); + Snapshot = snapshot; NotifySyncIfEnabled(); return Result.Ok().WithReasons(snapshot.Reasons); @@ -104,10 +107,10 @@ public Result Redo() public Result Reset() { _history.Clear(); - ResetSnapshotToEmpty(); var snapshot = _analyzer.Analyze(Recipe.Empty); - UpdateSnapshot(snapshot, markDirty: false); + Snapshot = snapshot; + _savedRecipe = Current; if (snapshot.IsFailed) { @@ -124,8 +127,14 @@ public Result Reset() public void MarkSaved() { - IsDirty = false; - _logger.LogInformation("Recipe marked as saved"); + MarkSaved(Current); + } + + /// Marks the given revision as the one on disk; a later revision stays unsaved. + public void MarkSaved(Recipe savedRecipe) + { + _savedRecipe = savedRecipe; + _logger.LogInformation("Recipe marked as saved: unsaved changes remain={IsDirty}", IsDirty); } /// @@ -145,7 +154,7 @@ public Result LoadAsCurrent(Recipe recipe) } _history.Clear(); - UpdateSnapshot(snapshot); + Snapshot = snapshot; NotifySyncIfEnabled(); _logger.LogInformation("Recipe loaded as current: {StepCount} steps", recipe.StepCount); @@ -435,27 +444,6 @@ private Result TryApplyFormulaRecalc(Step step, ActionDefinition action, s return recalcResult; } - private void UpdateSnapshot(Result snapshot) - { - UpdateSnapshot(snapshot, markDirty: true); - } - - private void UpdateSnapshot(Result snapshot, bool markDirty) - { - Snapshot = snapshot; - - if (markDirty) - { - IsDirty = true; - } - } - - private void ResetSnapshotToEmpty() - { - Snapshot = RecipeSnapshot.Empty; - IsDirty = false; - } - private Result RestoreFromHistory(Recipe target, Action commitMove) { var snapshot = _analyzer.Analyze(target); @@ -465,7 +453,7 @@ private Result RestoreFromHistory(Recipe target, Action commitMove) } commitMove(Current); - UpdateSnapshot(snapshot); + Snapshot = snapshot; NotifySyncIfEnabled(); return Result.Ok().WithReasons(snapshot.Reasons); diff --git a/SemiStep/SemiStep.Tests/Core/RecipeSessionBehaviourCharacterizationTests.cs b/SemiStep/SemiStep.Tests/Core/RecipeSessionBehaviourCharacterizationTests.cs index a6e652e..90018fd 100644 --- a/SemiStep/SemiStep.Tests/Core/RecipeSessionBehaviourCharacterizationTests.cs +++ b/SemiStep/SemiStep.Tests/Core/RecipeSessionBehaviourCharacterizationTests.cs @@ -133,7 +133,40 @@ public async Task MarkSaved_ClearsDirtyButPreservesHistory() harness.Session.IsDirty.Should().BeFalse("MarkSaved is the persistence-confirmation signal"); harness.Session.CanUndo.Should().BeTrue("MarkSaved must not erase the undo stack"); - harness.Session.Current.StepCount.Should().Be(2, "MarkSaved is a flag flip; the recipe stays put"); + harness.Session.Current.StepCount.Should().Be(2, "MarkSaved moves the saved point"); + } + + [Fact] + public async Task UndoBackToSavedState_ClearsDirty_AndRedoAwaySetsItAgain() + { + var harness = await BuildHarnessAsync(); + AppendWait(harness, 10f); + harness.Session.MarkSaved(); + harness.Session.AppendStep(WaitActionId).IsSuccess.Should().BeTrue(); + + harness.Session.Undo().IsSuccess.Should().BeTrue(); + harness.Session.IsDirty.Should().BeFalse("undo returned to the saved state"); + + harness.Session.Redo().IsSuccess.Should().BeTrue(); + harness.Session.IsDirty.Should().BeTrue("redo stepped away from the saved state"); + } + + [Fact] + public async Task RedoBackToSavedState_ClearsDirty_AndUndoAwaySetsItAgain() + { + var harness = await BuildHarnessAsync(); + AppendWait(harness, 10f); + harness.Session.AppendStep(WaitActionId).IsSuccess.Should().BeTrue(); + harness.Session.MarkSaved(); + + harness.Session.Undo().IsSuccess.Should().BeTrue(); + harness.Session.IsDirty.Should().BeTrue("undo stepped away from the saved state"); + + harness.Session.Redo().IsSuccess.Should().BeTrue(); + harness.Session.IsDirty.Should().BeFalse("redo returned to the saved state"); + + harness.Session.Undo().IsSuccess.Should().BeTrue(); + harness.Session.IsDirty.Should().BeTrue("undo stepped away from the saved state again"); } #endregion diff --git a/SemiStep/SemiStep.Tests/Helpers/HeldCsvService.cs b/SemiStep/SemiStep.Tests/Helpers/HeldCsvService.cs new file mode 100644 index 0000000..3f7b90a --- /dev/null +++ b/SemiStep/SemiStep.Tests/Helpers/HeldCsvService.cs @@ -0,0 +1,31 @@ +using FluentResults; + +using Microsoft.Extensions.Logging.Abstractions; + +using SemiStep.Core.Recipes; +using SemiStep.Core.Recipes.Import; + +namespace SemiStep.Tests.Helpers; + +/// Holds every save until , then writes the file through the real service. +internal sealed class HeldCsvService(CsvFileSerializer csvFileSerializer) + : CsvService(csvFileSerializer, NullLogger.Instance) +{ + private readonly TaskCompletionSource _saveEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public Task SaveEntered => _saveEntered.Task; + + public void Release() + { + _release.TrySetResult(); + } + + public override async Task SaveAsync(Recipe recipe, string filePath) + { + _saveEntered.TrySetResult(); + await _release.Task; + + return await base.SaveAsync(recipe, filePath); + } +} diff --git a/SemiStep/SemiStep.Tests/UI/Helpers/UIFixture.cs b/SemiStep/SemiStep.Tests/UI/Helpers/UIFixture.cs index 2b3ed7d..1153dfc 100644 --- a/SemiStep/SemiStep.Tests/UI/Helpers/UIFixture.cs +++ b/SemiStep/SemiStep.Tests/UI/Helpers/UIFixture.cs @@ -32,7 +32,8 @@ namespace SemiStep.Tests.UI.Helpers; -public sealed class UIFixture : IAsyncLifetime +/// Replaces the real CSV service, for example with one that holds saves. +public sealed class UIFixture(Func? createCsvService = null) : IAsyncLifetime { private readonly List _ownedDisposables = []; @@ -74,7 +75,8 @@ public async ValueTask InitializeAsync(string configName) MessagePanel = new MessagePanelViewModel(); StubS7 = services.GetRequiredService(); SyncOwnership = (StubPlcSyncOwnership)services.GetRequiredService(); - CsvService = services.GetRequiredService(); + CsvService = createCsvService?.Invoke(services.GetRequiredService()) + ?? services.GetRequiredService(); Coordinator = new RecipeCoordinator( Session, Plc, diff --git a/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorLoadRecipeTests.cs b/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorLoadRecipeTests.cs index ee66dd9..7c514c5 100644 --- a/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorLoadRecipeTests.cs +++ b/SemiStep/SemiStep.Tests/UI/RecipeCoordinatorLoadRecipeTests.cs @@ -234,6 +234,41 @@ public async Task SaveRecipeAsync_Failure_ReturnsFailed() } } + [AvaloniaFact] + public async Task SaveRecipeAsync_EditWhileWriting_KeepsTheEditUnsaved() + { + HeldCsvService? heldCsvService = null; + var (coordinator, panel) = await BuildCoordinatorAsync(services => + { + services.AddCsv(); + services.AddSingleton(sp => + heldCsvService = new HeldCsvService(sp.GetRequiredService())); + }); + var tempFilePath = Path.Combine(Path.GetTempPath(), $"{TempFilePrefix}.{Guid.NewGuid():N}.csv"); + coordinator.AppendStep(RecipeTestDriver.WaitActionId); + + try + { + var saveTask = coordinator.SaveRecipeAsync(tempFilePath); + await heldCsvService!.SaveEntered; + + coordinator.AppendStep(RecipeTestDriver.WaitActionId).IsSuccess.Should().BeTrue(); + heldCsvService.Release(); + (await saveTask).IsSuccess.Should().BeTrue(); + + coordinator.IsDirty.Should().BeTrue("the edit made during the write is not in the file"); + coordinator.Undo().IsSuccess.Should().BeTrue(); + coordinator.IsDirty.Should().BeFalse("undo returned to the state the save wrote"); + } + finally + { + heldCsvService?.Release(); + coordinator.Dispose(); + panel.Dispose(); + File.Delete(tempFilePath); + } + } + [AvaloniaFact] public async Task SaveRecipeAsync_IoException_ConvertsToFailedResult() { diff --git a/SemiStep/SemiStep.Tests/UI/RecipeFile/RecipeFileSaveInFlightTests.cs b/SemiStep/SemiStep.Tests/UI/RecipeFile/RecipeFileSaveInFlightTests.cs new file mode 100644 index 0000000..ac16388 --- /dev/null +++ b/SemiStep/SemiStep.Tests/UI/RecipeFile/RecipeFileSaveInFlightTests.cs @@ -0,0 +1,128 @@ +using System.Reactive; +using System.Reactive.Linq; +using System.Reactive.Threading.Tasks; +using System.Windows.Input; + +using Avalonia.Headless.XUnit; +using Avalonia.Threading; + +using AwesomeAssertions; + +using SemiStep.Tests.Core.Helpers; +using SemiStep.Tests.Helpers; +using SemiStep.Tests.UI.Helpers; + +using SemiStep.UI.MainWindow; +using SemiStep.UI.RecipeFile; + +using Xunit; + +using MainWindowView = SemiStep.UI.MainWindow.MainWindow; + +namespace SemiStep.Tests.UI.RecipeFile; + +[Trait("Component", "UI")] +[Trait("Area", "RecipeFile")] +[Trait("Category", "Integration")] +public sealed class RecipeFileSaveInFlightTests : IAsyncLifetime +{ + private const int DirtyStepCount = 2; + + private readonly UIFixture _fixture; + private readonly string _savePath = + Path.Combine(Path.GetTempPath(), $"SemiStep.SaveInFlight.{Guid.NewGuid():N}.csv"); + private HeldCsvService _heldCsvService = null!; + private MainWindowViewModel _viewModel = null!; + private MainWindowView _window = null!; + + public RecipeFileSaveInFlightTests() + { + _fixture = new UIFixture(serializer => _heldCsvService = new HeldCsvService(serializer)); + } + + private RecipeFileViewModel RecipeFile => _viewModel.RecipeFile; + + public async ValueTask InitializeAsync() + { + await _fixture.InitializeAsync(); + _fixture.SeedRecipe(DirtyStepCount); + _viewModel = _fixture.CreateMainWindowViewModel(); + _window = new MainWindowView { ViewModel = _viewModel }; + _window.Show(); + // The window registers its own handlers first, so the test handlers below win (LIFO). + Dispatcher.UIThread.RunJobs(); + RecipeFile.SaveFileInteraction.RegisterHandler(context => context.SetOutput(_savePath)); + RecipeFile.UnsavedChangesInteraction.RegisterHandler(context => context.SetOutput(UnsavedChangesChoice.Save)); + } + + public async ValueTask DisposeAsync() + { + _heldCsvService.Release(); + _fixture.Session.MarkSaved(); + _window.Close(); + _viewModel.Dispose(); + await _fixture.DisposeAsync(); + File.Delete(_savePath); + } + + [AvaloniaFact] + public async Task ExitSave_EditDuringWrite_KeepsWindowOpen() + { + var exit = _window.HandleExitChoiceAsync(UnsavedChangesChoice.Save); + await _heldCsvService.SaveEntered; + + EditRecipe(); + _heldCsvService.Release(); + await exit; + + _window.IsVisible.Should().BeTrue("the edit made during the write is not in the file"); + _fixture.Coordinator.IsDirty.Should().BeTrue(); + } + + [AvaloniaFact] + public async Task NewSave_EditDuringWrite_KeepsTheEditedRecipe() + { + var newRecipe = RecipeFile.NewRecipeCommand.Execute().ToTask(); + await _heldCsvService.SaveEntered; + + EditRecipe(); + var editedRecipe = _fixture.Coordinator.CurrentRecipe; + _heldCsvService.Release(); + await newRecipe; + + _fixture.Coordinator.CurrentRecipe.Should().BeSameAs( + editedRecipe, "the edit made during the write is not in the file"); + _fixture.Coordinator.IsDirty.Should().BeTrue(); + } + + [AvaloniaTheory] + [InlineData(false)] + [InlineData(true)] + public async Task SaveInFlight_DisablesNewAndOpen_UntilTheSaveEnds(bool saveAs) + { + var command = saveAs ? RecipeFile.SaveAsRecipeCommand : RecipeFile.SaveRecipeCommand; + var save = command.Execute(Unit.Default).ToTask(); + await _heldCsvService.SaveEntered; + Dispatcher.UIThread.RunJobs(); + + CanExecute(RecipeFile.NewRecipeCommand).Should().BeFalse("a late save would repoint the file name"); + CanExecute(RecipeFile.LoadRecipeCommand).Should().BeFalse("a late save would repoint the file name"); + + _heldCsvService.Release(); + (await save).Should().BeTrue(); + Dispatcher.UIThread.RunJobs(); + + CanExecute(RecipeFile.NewRecipeCommand).Should().BeTrue(); + CanExecute(RecipeFile.LoadRecipeCommand).Should().BeTrue(); + } + + private static bool CanExecute(ICommand command) + { + return command.CanExecute(null); + } + + private void EditRecipe() + { + _fixture.Coordinator.AppendStep(RecipeTestDriver.WaitActionId).IsSuccess.Should().BeTrue(); + } +} diff --git a/SemiStep/SemiStep.Tests/UI/RecipeFile/RecipeFileUnsavedChangesTests.cs b/SemiStep/SemiStep.Tests/UI/RecipeFile/RecipeFileUnsavedChangesTests.cs index 981c6c6..09f0914 100644 --- a/SemiStep/SemiStep.Tests/UI/RecipeFile/RecipeFileUnsavedChangesTests.cs +++ b/SemiStep/SemiStep.Tests/UI/RecipeFile/RecipeFileUnsavedChangesTests.cs @@ -9,6 +9,7 @@ using SemiStep.Tests.Core.Helpers; using SemiStep.Tests.UI.Helpers; +using SemiStep.UI.MessageService; using SemiStep.UI.RecipeFile; using Xunit; @@ -162,11 +163,15 @@ public async Task New_Dirty_RunStartsDuringPrompt_KeepsRecipe() _promptAction = () => _fixture.SetRecipeActive(true); _answer = UnsavedChangesChoice.DontSave; + var recipeBefore = _fixture.Coordinator.CurrentRecipe; + await _recipeFile.NewRecipeCommand.Execute(); _promptCount.Should().Be(1); - StepCount.Should().Be(DirtyStepCount, "a run that started during the prompt blocks the replacement"); + _fixture.Coordinator.CurrentRecipe.Should().BeSameAs( + recipeBefore, "a run that started during the prompt blocks the replacement"); _fixture.Coordinator.IsDirty.Should().BeTrue(); + ShouldReportOneRunBlockedWarning(); } [AvaloniaFact] @@ -273,11 +278,17 @@ public async Task Open_Dirty_RunStartsDuringPrompt_KeepsRecipe() _promptAction = () => _fixture.SetRecipeActive(true); _answer = UnsavedChangesChoice.DontSave; + var recipeBefore = _fixture.Coordinator.CurrentRecipe; + await _recipeFile.LoadRecipeCommand.Execute(); _promptCount.Should().Be(1); - StepCount.Should().Be(DirtyStepCount, "a run that started during the prompt blocks the open"); + _openPickerCount.Should().Be(0, "a run that started during the prompt stops before the file picker"); + _fixture.Coordinator.CurrentRecipe.Should().BeSameAs( + recipeBefore, "a run that started during the prompt blocks the open"); _fixture.Coordinator.IsDirty.Should().BeTrue(); + _recipeFile.CurrentFilePath.Should().BeNull(); + ShouldReportOneRunBlockedWarning(); } [AvaloniaFact] @@ -285,12 +296,15 @@ public async Task Open_Dirty_RunStartsDuringPicker_KeepsRecipe() { _pickerAction = () => _fixture.SetRecipeActive(true); _answer = UnsavedChangesChoice.DontSave; + var recipeBefore = _fixture.Coordinator.CurrentRecipe; await _recipeFile.LoadRecipeCommand.Execute(); _openPickerCount.Should().Be(1); - StepCount.Should().Be(DirtyStepCount, "a run that started during the picker blocks the open"); + _fixture.Coordinator.CurrentRecipe.Should().BeSameAs( + recipeBefore, "a run that started during the picker blocks the open"); _recipeFile.CurrentFilePath.Should().BeNull(); + ShouldReportOneRunBlockedWarning(); } [AvaloniaFact] @@ -310,6 +324,12 @@ public async Task Open_Clean_OpensPickedFileWithoutPrompt() /// A path below an existing file, so the file system rejects the write. private string UnwritableSavePath => Path.Combine(_openPath, "recipe.csv"); + private void ShouldReportOneRunBlockedWarning() + { + _fixture.MessagePanel.Entries.Should().ContainSingle("the blocked action reports once") + .Which.Severity.Should().Be(MessageSeverity.Warning); + } + private async Task SavedStepCountAsync(string path) { File.Exists(path).Should().BeTrue(); diff --git a/SemiStep/SemiStep.Tests/UI/RecipeGrid/ChangeMarkUndoTests.cs b/SemiStep/SemiStep.Tests/UI/RecipeGrid/ChangeMarkUndoTests.cs index 0048282..17295fb 100644 --- a/SemiStep/SemiStep.Tests/UI/RecipeGrid/ChangeMarkUndoTests.cs +++ b/SemiStep/SemiStep.Tests/UI/RecipeGrid/ChangeMarkUndoTests.cs @@ -154,17 +154,6 @@ public async Task CsvLoad_StartsWithoutMarks() } } - [AvaloniaFact] - public async Task PlcLoad_StartsWithoutMarks() - { - _fixture.S7Service.RecipeToReturn = new Recipe([.. CurrentRecipe.Steps]); - ChangeAction(0, RecipeTestDriver.ForLoopActionId); - - (await _fixture.Coordinator.LoadRecipeFromPlcAsync()).IsSuccess.Should().BeTrue(); - - ShouldShowNoMarks(); - } - [AvaloniaFact] public void NewRecipe_StartsWithoutMarks() { diff --git a/SemiStep/SemiStep.UI/Coordinator/RecipeCoordinator.cs b/SemiStep/SemiStep.UI/Coordinator/RecipeCoordinator.cs index 010fd7f..ea0bfec 100644 --- a/SemiStep/SemiStep.UI/Coordinator/RecipeCoordinator.cs +++ b/SemiStep/SemiStep.UI/Coordinator/RecipeCoordinator.cs @@ -193,35 +193,6 @@ public async Task DisableSync() _logger.LogInformation("PLC sync disabled"); } - public async Task LoadRecipeFromPlcAsync() - { - _logger.LogInformation("Loading recipe from PLC"); - - var readResult = await _plc.ReadRecipeFromPlcAsync(); - var result = readResult.IsFailed - ? readResult.ToResult() - : await Dispatcher.UIThread.InvokeAsync(() => _plc.ApplyRecipeFromPlc(readResult.Value)); - - if (result.IsFailed) - { - RebuildMessagePanel(); - _logger.LogWarning( - "Failed to load recipe from PLC: {Errors}", - result.FormatErrors()); - return result; - } - - _session.MarkSaved(); - _logger.LogInformation( - "Loaded recipe from PLC: {StepCount} steps", - _session.Current.StepCount); - - DispatchMutation(new MutationSignal.RecipeReplaced()); - RebuildMessagePanel(); - - return result; - } - public Result ResolveConflict(bool keepLocal) { _logger.LogInformation("PLC recipe conflict resolution: KeepLocal={KeepLocal}", keepLocal); @@ -364,12 +335,13 @@ public async Task LoadRecipeAsync(string filePath) public async Task SaveRecipeAsync(string filePath) { + var recipe = _session.Current; _logger.LogInformation( "Saving recipe to file: {FilePath}, StepCount={StepCount}", filePath, - _session.Current.StepCount); + recipe.StepCount); - var result = await _csvService.SaveAsync(_session.Current, filePath); + var result = await _csvService.SaveAsync(recipe, filePath); if (result.IsFailed) { @@ -379,7 +351,7 @@ public async Task SaveRecipeAsync(string filePath) } else { - await Dispatcher.UIThread.InvokeAsync(_session.MarkSaved); + await Dispatcher.UIThread.InvokeAsync(() => _session.MarkSaved(recipe)); _logger.LogInformation("Saved recipe to {FilePath}", filePath); // Not a step-graph mutation; subscribers refresh window-title / IsDirty / status. DispatchMutation(new MutationSignal.StateRefreshed()); diff --git a/SemiStep/SemiStep.UI/Localization/Resources.resx b/SemiStep/SemiStep.UI/Localization/Resources.resx index e2b850d..5afe00b 100644 --- a/SemiStep/SemiStep.UI/Localization/Resources.resx +++ b/SemiStep/SemiStep.UI/Localization/Resources.resx @@ -472,6 +472,9 @@ Loaded: {0} + + A recipe is running: a recipe cannot be opened or created. + PLC reconnect diff --git a/SemiStep/SemiStep.UI/Localization/Resources.ru.resx b/SemiStep/SemiStep.UI/Localization/Resources.ru.resx index 1012bca..2d83020 100644 --- a/SemiStep/SemiStep.UI/Localization/Resources.ru.resx +++ b/SemiStep/SemiStep.UI/Localization/Resources.ru.resx @@ -472,6 +472,9 @@ Загружено: {0} + + Идёт выполнение рецепта: открыть или создать рецепт нельзя. + Переподключение ПЛК diff --git a/SemiStep/SemiStep.UI/RecipeFile/RecipeFileViewModel.cs b/SemiStep/SemiStep.UI/RecipeFile/RecipeFileViewModel.cs index c009b6d..b320880 100644 --- a/SemiStep/SemiStep.UI/RecipeFile/RecipeFileViewModel.cs +++ b/SemiStep/SemiStep.UI/RecipeFile/RecipeFileViewModel.cs @@ -41,8 +41,12 @@ public RecipeFileViewModel( SaveRecipeCommand = ReactiveCommand.CreateFromTask(SaveRecipeAsync); SaveAsRecipeCommand = ReactiveCommand.CreateFromTask(SaveAsRecipeAsync); - LoadRecipeCommand = ReactiveCommand.CreateFromTask(LoadRecipeAsync, canEdit); - NewRecipeCommand = ReactiveCommand.CreateFromTask(NewRecipeAsync, canEdit); + var canReplace = canEdit.CombineLatest( + SaveRecipeCommand.IsExecuting, + SaveAsRecipeCommand.IsExecuting, + (editable, saving, savingAs) => editable && !saving && !savingAs); + LoadRecipeCommand = ReactiveCommand.CreateFromTask(LoadRecipeAsync, canReplace); + NewRecipeCommand = ReactiveCommand.CreateFromTask(NewRecipeAsync, canReplace); SaveRecipeCommand.ReportThrownExceptions(_messagePanel, _logger, new LocalizedText(nameof(Resources.SaveFailed))) .DisposeWith(_disposables); @@ -88,7 +92,7 @@ public async Task ResolveUnsavedChangesAsync(UnsavedChangesChoice choice) { return choice switch { - UnsavedChangesChoice.Save => await SaveBeforeDiscardAsync(), + UnsavedChangesChoice.Save => await SaveBeforeDiscardAsync() && !_coordinator.IsDirty, UnsavedChangesChoice.DontSave => true, _ => false }; @@ -160,13 +164,13 @@ private async Task SaveToFileAsync(string filePath) private async Task LoadRecipeAsync() { - if (!await ConfirmDiscardAsync()) + if (!await ConfirmDiscardAsync() || IsBlockedByRunningRecipe()) { return; } var filePath = await OpenFileInteraction.Handle(Unit.Default); - if (filePath is null || _coordinator.IsRecipeActive) + if (filePath is null || IsBlockedByRunningRecipe()) { return; } @@ -194,7 +198,7 @@ private async Task LoadRecipeAsync() private async Task NewRecipeAsync() { - if (!await ConfirmDiscardAsync() || _coordinator.IsRecipeActive) + if (!await ConfirmDiscardAsync() || IsBlockedByRunningRecipe()) { return; } @@ -210,4 +214,18 @@ private async Task NewRecipeAsync() CurrentFilePath = null; } + + /// Reports a run that started while a New or Open dialog was open; true stops the action. + private bool IsBlockedByRunningRecipe() + { + if (!_coordinator.IsRecipeActive) + { + return false; + } + + _logger.LogInformation("New or Open stopped: a recipe run started while its dialog was open"); + _messagePanel.ReportWarning(Resources.RunBlocksOpenOrNew); + + return true; + } } diff --git a/docs/architecture/dialogs-and-interactions.md b/docs/architecture/dialogs-and-interactions.md index ac30f2c..29eef7a 100644 --- a/docs/architecture/dialogs-and-interactions.md +++ b/docs/architecture/dialogs-and-interactions.md @@ -61,10 +61,16 @@ On a clean recipe nothing is asked. - `RecipeFileViewModel.ResolveUnsavedChangesAsync` is the one home of the answers. Save runs `SaveRecipeCommand`, which goes through save-as when the recipe has no file, and returns `true` only - after a successful save. A cancelled save-as, a failed save, an exception and a save already in - flight return `false`. Don't save returns `true`. Cancel and a dismissed dialog return `false`. + after a successful save that leaves the recipe clean. An edit or a PLC apply during the write makes + it return `false`, so the window stays and New or Open does not replace the recipe. A cancelled + save-as, a failed save, an exception and a save already in flight return `false`. Don't save returns `true`. Cancel and a dismissed dialog return `false`. - New and Open call it through `UnsavedChangesInteraction` before they act, so Open asks before the file picker. `false` leaves the recipe untouched. +- A run that starts while the prompt or the Open picker is open blocks the action: + `RecipeFileViewModel` checks `IsRecipeActive` after each dialog and reports one warning + (`RunBlocksOpenOrNew`). A cancelled dialog reports nothing. +- New and Open are disabled while `SaveRecipeCommand` or `SaveAsRecipeCommand` runs, so a save that + ends late cannot point `CurrentFilePath` at a different recipe. - The close path calls it from `MainWindow.HandleExitChoiceAsync` and closes on `true`. It keeps its own dirty check, because `OnWindowClosing` must set `e.Cancel` before the first `await`. - `MainWindow.ShowUnsavedChangesDialogAsync` is the one place that news the dialog. Both the close diff --git a/docs/readme.md b/docs/readme.md index 2085ccc..0fe3fe3 100644 --- a/docs/readme.md +++ b/docs/readme.md @@ -110,6 +110,10 @@ _Окна разных установок (MBE, MOCVD, RIE) используют Тот же диалог появляется, если в рецепте есть несохранённые изменения и выбрано создание рецепта (меню «Файл» → «Создать рецепт» или `Ctrl+Shift+N`) или открытие файла (меню «Файл» → «Открыть рецепт…», кнопка «Открыть» на панели инструментов или `Ctrl+O`). «Сохранить» сначала записывает текущий рецепт; если у рецепта ещё нет файла, сначала открывается диалог выбора файла для сохранения, как при «Сохранить рецепт как…». Если сохранение не удалось или диалог выбора файла отменён, новый рецепт не создаётся и файл не открывается. «Не сохранять» создаёт или открывает рецепт без записи. «Отмена» оставляет рецепт без изменений. При открытии файла диалог выбора файла появляется только после ответа. Если несохранённых изменений нет, диалог не появляется. +Если ПЛК начал выполнять рецепт, пока открыт этот диалог или диалог выбора файла, рецепт не создаётся и файл не открывается, а в панели сообщений появляется предупреждение «Идёт выполнение рецепта: открыть или создать рецепт нельзя.» + +Отмена и повтор (`Ctrl+Z`, `Ctrl+Y`) до состояния, в котором рецепт был сохранён или открыт, снимают признак несохранённых изменений; любой шаг от этого состояния, в том числе правка, снова его ставит. Правка, сделанная во время записи файла, остаётся несохранённой. + --- ### 2.2. Общий вид окон