Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions SemiStep/SemiStep.Core/Plc/PlcLifecycleManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -230,11 +230,6 @@ private void ReleaseOwnershipLease()
lease.Dispose();
}

public async Task<Result<Recipe>> ReadRecipeFromPlcAsync()
{
return await _reader.ReadRecipeFromPlcAsync();
}

public Result ApplyRecipeFromPlc(Recipe recipe)
{
return _session.LoadAsCurrentValidated(recipe);
Expand Down
18 changes: 13 additions & 5 deletions SemiStep/SemiStep.Core/Recipes/Import/CsvFileIo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
48 changes: 18 additions & 30 deletions SemiStep/SemiStep.Core/Recipes/RecipeSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
namespace SemiStep.Core.Recipes;

/// <summary>
/// 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 <see cref="RecipeHistory"/>, input checks in
/// <see cref="StepMutationValidator"/>.
/// </summary>
Expand All @@ -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<Warning>().Any();
Expand All @@ -59,7 +62,7 @@ public Result Apply(Recipe newRecipe)
}

_history.Push(Current);
UpdateSnapshot(snapshot);
Snapshot = snapshot;
NotifySyncIfEnabled();

return Result.Ok().WithReasons(snapshot.Reasons);
Expand Down Expand Up @@ -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)
{
Expand All @@ -124,8 +127,14 @@ public Result Reset()

public void MarkSaved()
{
IsDirty = false;
_logger.LogInformation("Recipe marked as saved");
MarkSaved(Current);
}

/// <summary>Marks the given revision as the one on disk; a later revision stays unsaved.</summary>
public void MarkSaved(Recipe savedRecipe)
{
_savedRecipe = savedRecipe;
_logger.LogInformation("Recipe marked as saved: unsaved changes remain={IsDirty}", IsDirty);
}

/// <summary>
Expand All @@ -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);
Expand Down Expand Up @@ -435,27 +444,6 @@ private Result<Step> TryApplyFormulaRecalc(Step step, ActionDefinition action, s
return recalcResult;
}

private void UpdateSnapshot(Result<RecipeSnapshot> snapshot)
{
UpdateSnapshot(snapshot, markDirty: true);
}

private void UpdateSnapshot(Result<RecipeSnapshot> snapshot, bool markDirty)
{
Snapshot = snapshot;

if (markDirty)
{
IsDirty = true;
}
}

private void ResetSnapshotToEmpty()
{
Snapshot = RecipeSnapshot.Empty;
IsDirty = false;
}

private Result RestoreFromHistory(Recipe target, Action<Recipe> commitMove)
{
var snapshot = _analyzer.Analyze(target);
Expand All @@ -465,7 +453,7 @@ private Result RestoreFromHistory(Recipe target, Action<Recipe> commitMove)
}

commitMove(Current);
UpdateSnapshot(snapshot);
Snapshot = snapshot;
NotifySyncIfEnabled();

return Result.Ok().WithReasons(snapshot.Reasons);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 31 additions & 0 deletions SemiStep/SemiStep.Tests/Helpers/HeldCsvService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using FluentResults;

using Microsoft.Extensions.Logging.Abstractions;

using SemiStep.Core.Recipes;
using SemiStep.Core.Recipes.Import;

namespace SemiStep.Tests.Helpers;

/// <summary>Holds every save until <see cref="Release"/>, then writes the file through the real service.</summary>
internal sealed class HeldCsvService(CsvFileSerializer csvFileSerializer)
: CsvService(csvFileSerializer, NullLogger<CsvService>.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<Result> SaveAsync(Recipe recipe, string filePath)
{
_saveEntered.TrySetResult();
await _release.Task;

return await base.SaveAsync(recipe, filePath);
}
}
6 changes: 4 additions & 2 deletions SemiStep/SemiStep.Tests/UI/Helpers/UIFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@

namespace SemiStep.Tests.UI.Helpers;

public sealed class UIFixture : IAsyncLifetime
/// <param name="createCsvService">Replaces the real CSV service, for example with one that holds saves.</param>
public sealed class UIFixture(Func<CsvFileSerializer, CsvService>? createCsvService = null) : IAsyncLifetime
{
private readonly List<IDisposable> _ownedDisposables = [];

Expand Down Expand Up @@ -74,7 +75,8 @@ public async ValueTask InitializeAsync(string configName)
MessagePanel = new MessagePanelViewModel();
StubS7 = services.GetRequiredService<StubS7Service>();
SyncOwnership = (StubPlcSyncOwnership)services.GetRequiredService<IPlcSyncOwnership>();
CsvService = services.GetRequiredService<CsvService>();
CsvService = createCsvService?.Invoke(services.GetRequiredService<CsvFileSerializer>())
?? services.GetRequiredService<CsvService>();
Coordinator = new RecipeCoordinator(
Session,
Plc,
Expand Down
35 changes: 35 additions & 0 deletions SemiStep/SemiStep.Tests/UI/RecipeCoordinatorLoadRecipeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<CsvService>(sp =>
heldCsvService = new HeldCsvService(sp.GetRequiredService<CsvFileSerializer>()));
});
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()
{
Expand Down
Loading