From 8ac0c1a267640c606710fbe03bbb8b8dadd790d9 Mon Sep 17 00:00:00 2001 From: Oleg <18466855+EvaTheSalmon@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:24:27 +0300 Subject: [PATCH] feat(chart): add recipe markers and the marker lock (#160) The SCADA now inserts a marker at each recipe's start, end and interruption into semiplot_markers, and SemiBase v0.7.0 gives the table a kind and a locked column. The chart read neither: a recipe marker looked like the operator's own, and a double click or a stray drag could delete or move a recipe boundary that the CSV export is to be cut by. The marker read now carries the kind and the lock, and one new write stores the lock. A locked marker ignores the drag and the double click, since its press region routes to pan-or-pick; the marker menu still renames and deletes it and gains Lock / Unlock. A recipe marker draws in its own palette colour and a locked one draws solid. View -> Recipe markers hides the recipe markers in one window: MarkerSet keeps every marker and a cached shown subset, which the lines, the readings, the minimap ticks and the hit test read. The database does not enforce the lock, so only the chart's gestures honour it. SemiBase v0.7.0 is now the minimum: against v0.6.0 every marker read fails as ShapeUnexpected. The docs record the new columns, the five marker writes, the gesture routing and the scada_writer INSERT grant. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 12 +- SemiPlot/SemiPlot.Core/Data/IMarkerStore.cs | 18 +- SemiPlot/SemiPlot.Core/Trends/MarkerSet.cs | 113 ++++-- .../ArchiveExceptionMapper.cs | 8 +- .../ArchiveStatements.cs | 6 +- .../PostgresMarkerStore.cs | 27 +- .../Journeys/NoMarkers.cs | 5 + .../MarkerStoreTests.cs | 101 ++++++ .../Core/Trends/MarkerSetTests.cs | 100 +++++- .../Postgres/ArchiveExceptionMapperTests.cs | 12 + .../UI/Chart/ChartMarkerViewTests.cs | 233 ++++++++++++- .../UI/Chart/ChartMarkersTests.cs | 155 +++++++-- .../UI/Chart/ChartPaletteTests.cs | 3 +- .../UI/Chart/ChartPressRouterTests.cs | 18 + .../UI/MainWindow/AppMenuBarTests.cs | 6 +- .../UI/MainWindow/MainWindowViewModelTests.cs | 20 ++ .../UI/MainWindow/TrendWindowTests.cs | 2 +- .../UI/Markers/FakeMarkerWriter.cs | 9 +- .../UI/Markers/MarkerSyncTests.cs | 38 ++- .../UI/Minimap/MinimapViewModelTests.cs | 19 ++ .../SemiPlot.UI/Chart/ChartMarkerLines.cs | 22 +- SemiPlot/SemiPlot.UI/Chart/ChartMarkers.cs | 40 ++- SemiPlot/SemiPlot.UI/Chart/ChartPalette.cs | 2 + .../SemiPlot.UI/Chart/ChartPressRouter.cs | 8 +- SemiPlot/SemiPlot.UI/Chart/IMarkerChannel.cs | 4 +- SemiPlot/SemiPlot.UI/Chart/MarkerPalette.cs | 2 +- .../Chart/TrendChartView.Markers.cs | 29 +- .../SemiPlot.UI/Chart/TrendChartView.axaml | 2 + .../SemiPlot.UI/Chart/TrendChartView.axaml.cs | 13 +- .../SemiPlot.UI/Localization/Resources.resx | 9 + .../Localization/Resources.ru.resx | 9 + .../SemiPlot.UI/MainWindow/AppMenuBar.axaml | 5 + .../MainWindow/MainWindowViewModel.cs | 12 + SemiPlot/SemiPlot.UI/Markers/MarkerSync.cs | 5 + .../SemiPlot.UI/Minimap/MinimapViewModel.cs | 2 +- SemiPlot/SemiPlot.UI/Styles/Palette.axaml | 2 + docs/architecture/data-integration.md | 47 ++- docs/architecture/overview.md | 25 +- docs/architecture/postgres-instance.md | 16 +- docs/architecture/postgres-topology.md | 1 + docs/architecture/trend-interaction.md | 62 ++-- docs/architecture/ui-text.md | 7 +- docs/architecture/ui-theme.md | 31 +- .../20261028-recipe-markers-on-chart.md | 322 ++++++++++++++++++ readme.md | 22 +- 45 files changed, 1401 insertions(+), 203 deletions(-) create mode 100644 docs/plans/completed/20261028-recipe-markers-on-chart.md diff --git a/AGENTS.md b/AGENTS.md index 418fc08..affc8d3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -334,11 +334,13 @@ No abbreviations in names. (`ChartPressAction.ShiftActivePen`), and Ctrl is a held key, not a `LeftButtonTool` value. A press on the time axis band is the last pre-branch, after Ctrl and ahead of the tool (`ChartPressAction.PanOrEditTimeWindow`): a drag pans, and a release inside the slop opens the time - window panel (`docs/architecture/trend-interaction.md#the-time-window-panel`). A press on a time - marker is the last branch, read after the tool (`ChartPressAction.DragMarker`). A second click where - a single one would pan or pick adds a marker (`ChartPressAction.AddMarker`), and one where it would - drag a marker deletes it (`ChartPressAction.DeleteMarker`, - `docs/architecture/trend-interaction.md#the-time-markers`). The bar's `IsSticky` has a single writer + window panel (`docs/architecture/trend-interaction.md#the-time-window-panel`). A press on a locked + marker (`ChartPressRegion.LockedMarker`) is read after the tool and pans or picks for any click + count (`ChartPressAction.PanOrPickPen`). A press on any other time marker is the last branch, read + after it (`ChartPressAction.DragMarker`). A second click in the data area away from any marker adds a + marker (`ChartPressAction.AddMarker`); on an unlocked marker it deletes it + (`ChartPressAction.DeleteMarker`); on a locked marker it pans or picks like one click + (`docs/architecture/trend-interaction.md#the-time-markers`). The bar's `IsSticky` has a single writer after the constructor seeds it (the `WindowChanged` handler refreshing from `Navigation.IsSticky`) — do not reintroduce imperative `IsSticky =` assignments. - A checkable menu item reads its flag `Mode=OneWay` and writes it only through the command it diff --git a/SemiPlot/SemiPlot.Core/Data/IMarkerStore.cs b/SemiPlot/SemiPlot.Core/Data/IMarkerStore.cs index 6517cdb..fd11970 100644 --- a/SemiPlot/SemiPlot.Core/Data/IMarkerStore.cs +++ b/SemiPlot/SemiPlot.Core/Data/IMarkerStore.cs @@ -13,8 +13,24 @@ public interface IMarkerStore Task RenameAsync(StoredMarker marker, string? label); + Task SetLockedAsync(StoredMarker marker, bool isLocked); + Task DeleteAsync(StoredMarker marker); } /// One semiplot_markers row as stored; a null label is a stored NULL. -public sealed record StoredMarker(long Id, DateTime TimeUtc, string? Label); +public sealed record StoredMarker( + long Id, + DateTime TimeUtc, + string? Label, + MarkerKind Kind = MarkerKind.User, + bool IsLocked = false); + +/// The semiplot_markers.kind values; the SCADA writes the recipe kinds. +public enum MarkerKind +{ + User = 0, + RecipeStart = 1, + RecipeEnd = 2, + RecipeInterrupted = 3 +} diff --git a/SemiPlot/SemiPlot.Core/Trends/MarkerSet.cs b/SemiPlot/SemiPlot.Core/Trends/MarkerSet.cs index 8e5d915..76c606f 100644 --- a/SemiPlot/SemiPlot.Core/Trends/MarkerSet.cs +++ b/SemiPlot/SemiPlot.Core/Trends/MarkerSet.cs @@ -2,22 +2,38 @@ namespace SemiPlot.Core.Trends; -/// The markers a window shows, sorted by time then id; a held marker keeps its local state. +/// +/// The markers a window holds, sorted by time then id, and the ones it shows; a held marker keeps its local state. +/// public sealed class MarkerSet { private static readonly Comparer _byTimeThenId = Comparer.Create(CompareByTimeThenId); private readonly Dictionary _holdCounts = []; - private StoredMarker[] _markers = []; + private StoredMarker[] _all = []; + private StoredMarker[] _shownMarkers = []; - /// A snapshot: every change replaces the array, so a reader never sees it mutate. - public IReadOnlyList Markers => _markers; + /// Every marker, shown or hidden; a snapshot like . + public IReadOnlyList All => _all; + + /// + /// The shown markers as a snapshot: every change replaces the array, so a reader never sees it mutate. + /// + public IReadOnlyList ShownMarkers => _shownMarkers; + + public bool ShowsRecipeMarkers { get; private set; } = true; + + public void ToggleRecipeMarkers() + { + ShowsRecipeMarkers = !ShowsRecipeMarkers; + RebuildShown(); + } public bool Apply(IReadOnlyList read) { var heldLocally = new Dictionary(); - foreach (var marker in _markers) + foreach (var marker in _all) { if (_holdCounts.ContainsKey(marker.Id)) { @@ -41,12 +57,13 @@ public bool Apply(IReadOnlyList read) next.AddRange(heldLocally.Values); next.Sort(_byTimeThenId); - if (next.SequenceEqual(_markers)) + if (next.SequenceEqual(_all)) { return false; } - _markers = [.. next]; + _all = [.. next]; + RebuildShown(); return true; } @@ -76,40 +93,24 @@ public bool Release(long id) return true; } - /// An upsert by id in one copy pass; it runs on every pointer move of a marker drag. + /// An upsert by id, one copy pass per list the marker is in; it runs on every move of a drag. public void Place(StoredMarker marker) { - var isReplacing = Array.Exists(_markers, existing => existing.Id == marker.Id); - var next = new StoredMarker[isReplacing ? _markers.Length : _markers.Length + 1]; - var written = 0; - var isPlaced = false; - foreach (var existing in _markers) + _all = Upsert(_all, marker); + if (ShowsRecipeMarkers) { - if (existing.Id == marker.Id) - { - continue; - } - - if (!isPlaced && _byTimeThenId.Compare(marker, existing) < 0) - { - next[written++] = marker; - isPlaced = true; - } - - next[written++] = existing; + _shownMarkers = _all; } - - if (!isPlaced) + else if (IsShownWhileRecipesHidden(marker)) { - next[written] = marker; + _shownMarkers = Upsert(_shownMarkers, marker); } - - _markers = next; } public void Remove(long id) { - _markers = Array.FindAll(_markers, marker => marker.Id != id); + _all = Array.FindAll(_all, marker => marker.Id != id); + RebuildShown(); } /// The marker closest to within the tolerance; the lower id wins a tie. @@ -117,7 +118,7 @@ public void Remove(long id) { var right = FirstAtOrAfter(time); var left = right - 1; - while (left > 0 && _markers[left - 1].TimeUtc == _markers[left].TimeUtc) + while (left > 0 && _shownMarkers[left - 1].TimeUtc == _shownMarkers[left].TimeUtc) { left--; } @@ -126,12 +127,12 @@ public void Remove(long id) var nearestDistance = TimeSpan.MaxValue; foreach (var index in (ReadOnlySpan)[left, right]) { - if (index < 0 || index >= _markers.Length) + if (index < 0 || index >= _shownMarkers.Length) { continue; } - var candidate = _markers[index]; + var candidate = _shownMarkers[index]; var distance = (candidate.TimeUtc - time).Duration(); if (distance > tolerance) { @@ -156,14 +157,54 @@ private static int CompareByTimeThenId(StoredMarker first, StoredMarker second) return byTime != 0 ? byTime : first.Id.CompareTo(second.Id); } + private static bool IsShownWhileRecipesHidden(StoredMarker marker) + { + return marker.Kind == MarkerKind.User; + } + + private static StoredMarker[] Upsert(StoredMarker[] sorted, StoredMarker marker) + { + var isReplacing = Array.Exists(sorted, existing => existing.Id == marker.Id); + var next = new StoredMarker[isReplacing ? sorted.Length : sorted.Length + 1]; + var written = 0; + var isPlaced = false; + foreach (var existing in sorted) + { + if (existing.Id == marker.Id) + { + continue; + } + + if (!isPlaced && _byTimeThenId.Compare(marker, existing) < 0) + { + next[written++] = marker; + isPlaced = true; + } + + next[written++] = existing; + } + + if (!isPlaced) + { + next[written] = marker; + } + + return next; + } + + private void RebuildShown() + { + _shownMarkers = ShowsRecipeMarkers ? _all : Array.FindAll(_all, IsShownWhileRecipesHidden); + } + private int FirstAtOrAfter(DateTime time) { var low = 0; - var high = _markers.Length; + var high = _shownMarkers.Length; while (low < high) { var middle = low + ((high - low) / 2); - if (_markers[middle].TimeUtc < time) + if (_shownMarkers[middle].TimeUtc < time) { low = middle + 1; } diff --git a/SemiPlot/SemiPlot.DataSource.Postgres/ArchiveExceptionMapper.cs b/SemiPlot/SemiPlot.DataSource.Postgres/ArchiveExceptionMapper.cs index a6ef558..6851b54 100644 --- a/SemiPlot/SemiPlot.DataSource.Postgres/ArchiveExceptionMapper.cs +++ b/SemiPlot/SemiPlot.DataSource.Postgres/ArchiveExceptionMapper.cs @@ -52,12 +52,18 @@ public ArchiveError RowGone(string subject) return Fault(ArchiveFault.RowGone, subject); } - /// A move or rename that touched no row: the marker it names is gone. + /// A move, rename or lock that touched no row: the marker it names is gone. public ArchiveError MarkerGone(string subject) { return Fault(ArchiveFault.MarkerGone, subject); } + /// A value read back that this code cannot represent; names it. + public ArchiveError ShapeUnexpected(string detail) + { + return Fault(ArchiveFault.ShapeUnexpected, detail); + } + private static ArchiveFault? WriteFaultOf(string sqlState) { return sqlState switch diff --git a/SemiPlot/SemiPlot.DataSource.Postgres/ArchiveStatements.cs b/SemiPlot/SemiPlot.DataSource.Postgres/ArchiveStatements.cs index 0653d2d..36b3ba0 100644 --- a/SemiPlot/SemiPlot.DataSource.Postgres/ArchiveStatements.cs +++ b/SemiPlot/SemiPlot.DataSource.Postgres/ArchiveStatements.cs @@ -35,6 +35,8 @@ internal static class StoredMarkerColumn public const int Id = 0; public const int Time = 1; public const int Label = 2; + public const int Kind = 3; + public const int Locked = 4; } /// Every statement this project issues; parameters are bound, never interpolated. @@ -140,7 +142,7 @@ DELETE FROM semiplot_pen_groups WHERE pen_id = @pen_id AND group_id = @group_id; """; - public const string StoredMarkers = "SELECT id, t, label FROM semiplot_markers ORDER BY t, id;"; + public const string StoredMarkers = "SELECT id, t, label, kind, locked FROM semiplot_markers ORDER BY t, id;"; public const string AddMarker = "INSERT INTO semiplot_markers (t, label) VALUES (@t, @label) RETURNING id;"; @@ -148,6 +150,8 @@ DELETE FROM semiplot_pen_groups public const string RenameMarker = "UPDATE semiplot_markers SET label = @label WHERE id = @id;"; + public const string SetMarkerLocked = "UPDATE semiplot_markers SET locked = @locked WHERE id = @id;"; + public const string DeleteMarker = "DELETE FROM semiplot_markers WHERE id = @id;"; /// The name PostgreSQL gives the membership's foreign key to the pen SemiBase declares unnamed. diff --git a/SemiPlot/SemiPlot.DataSource.Postgres/PostgresMarkerStore.cs b/SemiPlot/SemiPlot.DataSource.Postgres/PostgresMarkerStore.cs index a6e3fef..52c69fe 100644 --- a/SemiPlot/SemiPlot.DataSource.Postgres/PostgresMarkerStore.cs +++ b/SemiPlot/SemiPlot.DataSource.Postgres/PostgresMarkerStore.cs @@ -14,8 +14,8 @@ namespace SemiPlot.DataSource.Postgres; /// -/// Reads and writes semiplot_markers over the provider's and role. A move or -/// rename touching no row is ; a delete touching none succeeds. +/// Reads and writes semiplot_markers over the provider's and role. A move, +/// rename or lock touching no row is ; a delete touching none succeeds. /// public sealed class PostgresMarkerStore : IMarkerStore { @@ -46,10 +46,20 @@ public async Task>> ReadAsync(CancellationTok while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) { + var kind = (MarkerKind)reader.GetInt16(StoredMarkerColumn.Kind); + + if (!Enum.IsDefined(kind)) + { + return Result.Fail>(_exceptionMapper.ShapeUnexpected( + FormattableString.Invariant($"semiplot_markers.kind holds {(int)kind}, which MarkerKind does not define."))); + } + markers.Add(new StoredMarker( reader.GetInt64(StoredMarkerColumn.Id), reader.GetFieldValue(StoredMarkerColumn.Time), - reader.IsDBNull(StoredMarkerColumn.Label) ? null : reader.GetString(StoredMarkerColumn.Label))); + reader.IsDBNull(StoredMarkerColumn.Label) ? null : reader.GetString(StoredMarkerColumn.Label), + kind, + reader.GetBoolean(StoredMarkerColumn.Locked))); } return Result.Ok>(markers); @@ -106,6 +116,17 @@ public Task RenameAsync(StoredMarker marker, string? label) goneSubject: SubjectOf(marker.TimeUtc, marker.Label)); } + public Task SetLockedAsync(StoredMarker marker, bool isLocked) + { + var subject = SubjectOf(marker.TimeUtc, marker.Label); + + return UpdateOneRowAsync( + ArchiveStatements.SetMarkerLocked, + [IdParameter(marker.Id), new NpgsqlParameter("locked", NpgsqlDbType.Boolean) { Value = isLocked }], + refusedSubject: subject, + goneSubject: subject); + } + /// Idempotent: deleting a marker another window already removed succeeds. public async Task DeleteAsync(StoredMarker marker) { diff --git a/SemiPlot/SemiPlot.Tests.Integration/Journeys/NoMarkers.cs b/SemiPlot/SemiPlot.Tests.Integration/Journeys/NoMarkers.cs index 77ca460..3a5a4e5 100644 --- a/SemiPlot/SemiPlot.Tests.Integration/Journeys/NoMarkers.cs +++ b/SemiPlot/SemiPlot.Tests.Integration/Journeys/NoMarkers.cs @@ -26,6 +26,11 @@ public Task RenameAsync(StoredMarker marker, string? label) throw new NotSupportedException(); } + public Task SetLockedAsync(StoredMarker marker, bool isLocked) + { + throw new NotSupportedException(); + } + public Task DeleteAsync(StoredMarker marker) { throw new NotSupportedException(); diff --git a/SemiPlot/SemiPlot.Tests.Integration/MarkerStoreTests.cs b/SemiPlot/SemiPlot.Tests.Integration/MarkerStoreTests.cs index 27ab2d2..efc199f 100644 --- a/SemiPlot/SemiPlot.Tests.Integration/MarkerStoreTests.cs +++ b/SemiPlot/SemiPlot.Tests.Integration/MarkerStoreTests.cs @@ -24,6 +24,33 @@ public sealed class MarkerStoreTests(PostgresContainerFixture postgresContainerF { private const string DropMarkersCommand = "DROP TABLE public.semiplot_markers;"; + private const string InsertRecipeStartCommand = """ + INSERT INTO public.semiplot_markers (t, label, kind, locked) + VALUES ('2026-03-02 08:15:00+00', 'Etch.csv', 1, true); + """; + + private const string DropKindCheckCommand = """ + DO $$ + DECLARE check_name text; + BEGIN + FOR check_name IN + SELECT conname FROM pg_constraint + WHERE conrelid = 'public.semiplot_markers'::regclass + AND contype = 'c' + AND pg_get_constraintdef(oid) LIKE '%kind%' + LOOP + EXECUTE format( + 'ALTER TABLE public.semiplot_markers DROP CONSTRAINT %I', + check_name); + END LOOP; + END $$; + """; + + private const string InsertKindSevenCommand = """ + INSERT INTO public.semiplot_markers (t, label, kind, locked) + VALUES ('2026-03-02 08:15:00+00', 'Etch.csv', 7, true); + """; + private const int MaxLabelLength = 80; private static readonly DateTime _etchStart = new(2026, 3, 2, 8, 15, 0, DateTimeKind.Utc); @@ -91,9 +118,80 @@ public async Task ARenameWritesThatMarkerOnly(string? label) (await ReadAsync(store)).Should().Equal(renamed with { Label = label }, kept); } + [Fact] + public async Task ARowTheScadaInsertedReadsBackWithItsKindAndLock() + { + await AdminAsync(InsertRecipeStartCommand); + + using var services = Build(); + + var marker = (await ReadAsync(Store(services))).Should().ContainSingle().Which; + + marker.Should().Be(new StoredMarker(marker.Id, _etchStart, "Etch.csv", MarkerKind.RecipeStart, IsLocked: true)); + } + + [Fact] + public async Task AnAddedMarkerReadsAsAnUnlockedUserMarker() + { + using var services = Build(); + + var store = Store(services); + + await AddAsync(store, _etchStart, "Etch start"); + + var marker = (await ReadAsync(store)).Should().ContainSingle().Which; + + marker.Kind.Should().Be(MarkerKind.User); + marker.IsLocked.Should().BeFalse(); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task ALockWritesThatMarkerOnly(bool isLocked) + { + await AdminAsync(InsertRecipeStartCommand); + + using var services = Build(); + + var store = Store(services); + var recipe = (await ReadAsync(store)).Should().ContainSingle().Which; + var written = await AddMarkerAsync(store, _etchStart.AddHours(1), "Etch end"); + var kept = await AddMarkerAsync(store, _etchStart.AddHours(2), "Purge") with { IsLocked = !isLocked }; + await AdminAsync(string.Create( + CultureInfo.InvariantCulture, + $"UPDATE public.semiplot_markers SET locked = {kept.IsLocked} WHERE id = {kept.Id};")); + + var first = await store.SetLockedAsync(written, isLocked); + var second = await store.SetLockedAsync(recipe, isLocked); + + first.IsSuccess.Should().BeTrue(ArchiveReadSupport.Describe(first)); + second.IsSuccess.Should().BeTrue(ArchiveReadSupport.Describe(second)); + (await ReadAsync(store)).Should().Equal( + recipe with { IsLocked = isLocked }, + written with { IsLocked = isLocked }, + kept); + } + + [Fact] + public async Task AKindOutsideTheEnumIsShapeUnexpectedNamingTheValue() + { + await AdminAsync(DropKindCheckCommand); + await AdminAsync(InsertKindSevenCommand); + + using var services = Build(); + + var result = await Store(services).ReadAsync(TestContext.Current.CancellationToken); + + var (kind, detail) = FailureOf(result); + kind.Should().Be(ArchiveFault.ShapeUnexpected); + detail.Should().Contain("7"); + } + [Theory] [InlineData("Move")] [InlineData("Rename")] + [InlineData("Lock")] public async Task AWriteToADeletedMarkerIsMarkerGoneNamingIt(string write) { using var services = Build(); @@ -107,6 +205,7 @@ public async Task AWriteToADeletedMarkerIsMarkerGoneNamingIt(string write) { "Move" => await store.MoveAsync(marker, _etchStart.AddMinutes(10)), "Rename" => await store.RenameAsync(marker, "Etch end"), + "Lock" => await store.SetLockedAsync(marker, true), _ => throw new ArgumentOutOfRangeException(nameof(write), write, "Unknown write.") }; @@ -198,6 +297,7 @@ public async Task AMomentWrittenAsUtcReadsBackEqualThroughTheRepeatedHour() [InlineData("Add")] [InlineData("Move")] [InlineData("Rename")] + [InlineData("Lock")] [InlineData("Delete")] public async Task AStatementAgainstADroppedTableIsTableMissingNamingTheMarkers(string statement) { @@ -214,6 +314,7 @@ public async Task AStatementAgainstADroppedTableIsTableMissingNamingTheMarkers(s "Add" => await store.AddAsync(_etchStart, "Etch start"), "Move" => await store.MoveAsync(marker, _etchStart.AddMinutes(10)), "Rename" => await store.RenameAsync(marker, "Etch end"), + "Lock" => await store.SetLockedAsync(marker, true), "Delete" => await store.DeleteAsync(marker), _ => throw new ArgumentOutOfRangeException(nameof(statement), statement, "Unknown statement.") }; diff --git a/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MarkerSetTests.cs b/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MarkerSetTests.cs index f598441..29ecf28 100644 --- a/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MarkerSetTests.cs +++ b/SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MarkerSetTests.cs @@ -28,7 +28,7 @@ public void Apply_OfAnUnchangedRead_ReturnsFalse() var changed = set.Apply([_etchStart with { }, _unlabelled with { }]); changed.Should().BeFalse(); - set.Markers.Should().Equal(_etchStart, _unlabelled); + set.ShownMarkers.Should().Equal(_etchStart, _unlabelled); } [Fact] @@ -40,7 +40,7 @@ public void Apply_OfAMovedMarker_ReturnsTrueAndSortsByTheNewMoment() var changed = set.Apply([moved, _unlabelled]); changed.Should().BeTrue(); - set.Markers.Should().Equal(_unlabelled, moved); + set.ShownMarkers.Should().Equal(_unlabelled, moved); } [Fact] @@ -51,7 +51,7 @@ public void Apply_OfARelabelledMarker_ReturnsTrueWithTheNewLabel() set.Apply([relabelled]).Should().BeTrue(); - set.Markers.Should().Equal(relabelled); + set.ShownMarkers.Should().Equal(relabelled); } [Fact] @@ -61,7 +61,7 @@ public void Apply_OfAnAddedMarker_ReturnsTrueWithTheMarkerInTimeOrder() set.Apply([_etchEnd, _unlabelled, _etchStart]).Should().BeTrue(); - set.Markers.Should().Equal(_etchStart, _unlabelled, _etchEnd); + set.ShownMarkers.Should().Equal(_etchStart, _unlabelled, _etchEnd); } [Fact] @@ -71,7 +71,7 @@ public void Apply_OfARemovedMarker_ReturnsTrueWithoutIt() set.Apply([_unlabelled]).Should().BeTrue(); - set.Markers.Should().Equal(_unlabelled); + set.ShownMarkers.Should().Equal(_unlabelled); } [Fact] @@ -82,7 +82,7 @@ public void Apply_OrdersMarkersOfOneMomentById() set.Apply([later, _etchStart]); - set.Markers.Should().Equal(_etchStart, later); + set.ShownMarkers.Should().Equal(_etchStart, later); } [Fact] @@ -95,7 +95,7 @@ public void AHeldMarker_KeepsItsLocalMomentAndLabelThroughApply() set.Apply([_etchStart, _etchEnd]).Should().BeTrue(); - set.Markers.Should().Equal(dragged, _etchEnd); + set.ShownMarkers.Should().Equal(dragged, _etchEnd); } [Fact] @@ -106,7 +106,7 @@ public void AHeldMarker_StaysWhenAReadOmitsIt() set.Apply([_unlabelled]).Should().BeFalse(); - set.Markers.Should().Equal(_etchStart, _unlabelled); + set.ShownMarkers.Should().Equal(_etchStart, _unlabelled); } [Fact] @@ -119,7 +119,7 @@ public void TwoHoldsAndOneRelease_KeepTheMarkerHeld() set.Release(_etchStart.Id).Should().BeFalse(); set.Apply([]); - set.Markers.Should().Equal(_etchStart); + set.ShownMarkers.Should().Equal(_etchStart); } [Fact] @@ -133,7 +133,7 @@ public void TheSecondRelease_ReportsZeroAndLetsTheNextReadRemoveTheMarker() set.Release(_etchStart.Id).Should().BeTrue(); set.Apply([]).Should().BeTrue(); - set.Markers.Should().BeEmpty(); + set.ShownMarkers.Should().BeEmpty(); } [Fact] @@ -143,7 +143,7 @@ public void Place_OfAnIdApplyAlreadyAdded_LeavesOneMarker() set.Place(_unlabelled); - set.Markers.Should().Equal(_etchStart, _unlabelled); + set.ShownMarkers.Should().Equal(_etchStart, _unlabelled); } [Fact] @@ -154,7 +154,7 @@ public void Place_OfAMovedMarker_ReplacesItAtItsNewPosition() set.Place(moved); - set.Markers.Should().Equal(_unlabelled, _etchEnd, moved); + set.ShownMarkers.Should().Equal(_unlabelled, _etchEnd, moved); } [Fact] @@ -167,7 +167,7 @@ public void Place_AtAnotherMarkersMoment_OrdersTheTwoById() set.Place(lowerId); set.Place(higherId); - set.Markers.Should().Equal(_etchStart, higherId, lowerId, _etchEnd); + set.ShownMarkers.Should().Equal(_etchStart, higherId, lowerId, _etchEnd); } [Fact] @@ -177,14 +177,14 @@ public void Remove_DropsTheMarker() set.Remove(_etchStart.Id); - set.Markers.Should().Equal(_unlabelled); + set.ShownMarkers.Should().Equal(_unlabelled); } [Fact] - public void Markers_IsASnapshotThatAChangeDoesNotMutate() + public void ShownMarkers_IsASnapshotThatAChangeDoesNotMutate() { var set = SetOf(_etchStart); - var snapshot = set.Markers; + var snapshot = set.ShownMarkers; set.Place(_etchEnd); @@ -244,6 +244,74 @@ public void NearestWithin_OfAnEmptySet_ReturnsNothing() new MarkerSet().NearestWithin(_origin, TimeSpan.FromHours(1)).Should().BeNull(); } + [Fact] + public void HiddenRecipeMarkers_LeaveTheShownMarkersAndTheHitTest_AndStayInAll() + { + var recipeStart = new StoredMarker(4, _origin.AddMinutes(5), "Etch.csv", MarkerKind.RecipeStart, true); + var recipeEnd = new StoredMarker(5, _origin.AddMinutes(25), "Etch.csv", MarkerKind.RecipeEnd, true); + var set = SetOf(_etchStart, recipeStart, _etchEnd, recipeEnd); + + set.ToggleRecipeMarkers(); + + set.ShowsRecipeMarkers.Should().BeFalse(); + set.ShownMarkers.Should().Equal(_etchStart, _etchEnd); + set.All.Should().Equal(_etchStart, recipeStart, _etchEnd, recipeEnd); + set.NearestWithin(recipeStart.TimeUtc, TimeSpan.FromMinutes(1)).Should().BeNull(); + set.NearestWithin(recipeEnd.TimeUtc, TimeSpan.FromMinutes(6)).Should().Be(_etchEnd); + } + + [Fact] + public void ShowingRecipeMarkersAgain_BringsThemBack() + { + var recipeStart = new StoredMarker(4, _origin.AddMinutes(5), "Etch.csv", MarkerKind.RecipeStart, true); + var set = SetOf(_etchStart, recipeStart); + set.ToggleRecipeMarkers(); + + set.ToggleRecipeMarkers(); + + set.ShownMarkers.Should().Equal(_etchStart, recipeStart); + set.NearestWithin(recipeStart.TimeUtc, TimeSpan.FromMinutes(1)).Should().Be(recipeStart); + } + + [Fact] + public void WhileRecipeMarkersAreHidden_AReadAndAPlaceKeepThemOutOfTheShownMarkers() + { + var recipeStart = new StoredMarker(4, _origin.AddMinutes(5), "Etch.csv", MarkerKind.RecipeStart, true); + var recipeEnd = new StoredMarker(5, _origin.AddMinutes(25), "Etch.csv", MarkerKind.RecipeEnd, true); + var set = SetOf(_etchStart); + set.ToggleRecipeMarkers(); + + set.Apply([_etchStart, recipeStart]).Should().BeTrue(); + set.Place(recipeEnd); + + set.ShownMarkers.Should().Equal(_etchStart); + set.All.Should().Equal(_etchStart, recipeStart, recipeEnd); + } + + [Fact] + public void WhileRecipeMarkersAreHidden_APlaceOfAUserMarker_MovesItAmongTheShownMarkers() + { + var recipeStart = new StoredMarker(4, _origin.AddMinutes(5), "Etch.csv", MarkerKind.RecipeStart, true); + var set = SetOf(_etchStart, recipeStart, _etchEnd); + set.ToggleRecipeMarkers(); + var moved = _etchStart with { TimeUtc = _origin.AddMinutes(30) }; + + set.Place(moved); + + set.ShownMarkers.Should().Equal(_etchEnd, moved); + set.All.Should().Equal(recipeStart, _etchEnd, moved); + } + + [Fact] + public void ShownMarkers_ReturnsTheSameArrayBetweenTwoChanges() + { + var recipeStart = new StoredMarker(4, _origin.AddMinutes(5), "Etch.csv", MarkerKind.RecipeStart, true); + var set = SetOf(_etchStart, recipeStart); + set.ToggleRecipeMarkers(); + + set.ShownMarkers.Should().BeSameAs(set.ShownMarkers); + } + private static MarkerSet SetOf(params StoredMarker[] markers) { var set = new MarkerSet(); diff --git a/SemiPlot/SemiPlot.Tests.Unit/Postgres/ArchiveExceptionMapperTests.cs b/SemiPlot/SemiPlot.Tests.Unit/Postgres/ArchiveExceptionMapperTests.cs index 84bef41..5ccfbf6 100644 --- a/SemiPlot/SemiPlot.Tests.Unit/Postgres/ArchiveExceptionMapperTests.cs +++ b/SemiPlot/SemiPlot.Tests.Unit/Postgres/ArchiveExceptionMapperTests.cs @@ -277,6 +277,18 @@ public void MarkerGoneCarriesTheSubjectAndTheEndpoint() AssertEndpoint(error); } + [Fact] + public void ShapeUnexpectedCarriesTheDetailAndTheEndpoint() + { + const string Detail = "semiplot_markers.kind holds 7, which MarkerKind does not define."; + + var error = Mapper().ShapeUnexpected(Detail); + + error.Kind.Should().Be(ArchiveFault.ShapeUnexpected); + error.Detail.Should().Be(Detail); + AssertEndpoint(error); + } + private static PostgresException Postgres(string sqlState) { return new PostgresException("the server said so", "ERROR", "ERROR", sqlState); diff --git a/SemiPlot/SemiPlot.Tests.Unit/UI/Chart/ChartMarkerViewTests.cs b/SemiPlot/SemiPlot.Tests.Unit/UI/Chart/ChartMarkerViewTests.cs index 3004dd5..57ede3f 100644 --- a/SemiPlot/SemiPlot.Tests.Unit/UI/Chart/ChartMarkerViewTests.cs +++ b/SemiPlot/SemiPlot.Tests.Unit/UI/Chart/ChartMarkerViewTests.cs @@ -12,10 +12,13 @@ using AwesomeAssertions; +using FluentResults; + using ScottPlot; using ScottPlot.Plottables; using SemiPlot.Core.Data; +using SemiPlot.Tests.Unit.UI.Bridge; using SemiPlot.Tests.Unit.UI.Markers; using SemiPlot.UI.Chart; using SemiPlot.UI.Localization; @@ -196,6 +199,61 @@ public void AfterAThemeVariantSwitch_EveryMarkerDrawsInTheNewVariant() } } + [AvaloniaFact] + public void ARecipeMarker_DrawsInTheRecipeColourAndAUserMarkerInTheMarkerColour() + { + using var scope = ThemeProbe.ApplyVariant(ThemeVariant.Light); + Dispatcher.UIThread.RunJobs(); + + _channel.Push( + new StoredMarker(1, MomentAt(0.25), "Etch.csv", MarkerKind.RecipeStart, IsLocked: true), + new StoredMarker(2, MomentAt(0.75), "#1")); + + Layer.Lines[1].LineColor.Should().Be(ThemeProbe.PlotColour("AppRecipeMarkerLineBrush", ThemeVariant.Light)); + Layer.Lines[2].LineColor.Should().Be(ThemeProbe.PlotColour("AppMarkerLineBrush", ThemeVariant.Light)); + } + + [AvaloniaFact] + public void ALockedMarker_DrawsSolidAndAnUnlockedOneDashed() + { + _channel.Push( + new StoredMarker(1, MomentAt(0.25), "Etch.csv", MarkerKind.RecipeEnd, IsLocked: true), + new StoredMarker(2, MomentAt(0.75), "#1")); + + Layer.Lines[1].LinePattern.Should().Be(LinePattern.Solid); + Layer.Lines[2].LinePattern.Should().Be(LinePattern.Dashed); + } + + [AvaloniaFact] + public void ALockChangeBetweenTwoReads_ChangesTheLinePattern() + { + var marker = new StoredMarker(1, MomentAt(0.25), "#1"); + _channel.Push(marker); + Layer.Lines[1].LinePattern.Should().Be(LinePattern.Dashed); + + _channel.Push(marker with { IsLocked = true }); + Layer.Lines[1].LinePattern.Should().Be(LinePattern.Solid); + + _channel.Push(marker); + Layer.Lines[1].LinePattern.Should().Be(LinePattern.Dashed); + } + + [AvaloniaFact] + public void AfterAThemeVariantSwitch_ARecipeLineKeepsTheRecipeColour() + { + using var scope = ThemeProbe.ApplyVariant(ThemeVariant.Light); + Dispatcher.UIThread.RunJobs(); + _channel.Push( + new StoredMarker(1, MomentAt(0.25), "Etch.csv", MarkerKind.RecipeInterrupted, IsLocked: true), + new StoredMarker(2, MomentAt(0.75), "#1")); + + Application.Current!.RequestedThemeVariant = ThemeVariant.Dark; + Dispatcher.UIThread.RunJobs(); + + Layer.Lines[1].LineColor.Should().Be(ThemeProbe.PlotColour("AppRecipeMarkerLineBrush", ThemeVariant.Dark)); + Layer.Lines[2].LineColor.Should().Be(ThemeProbe.PlotColour("AppMarkerLineBrush", ThemeVariant.Dark)); + } + [AvaloniaFact] public void ADragPastTheSlop_IssuesOneMoveWithTheDroppedMoment() { @@ -216,7 +274,7 @@ public void ADragPastTheSlop_IssuesOneMoveWithTheDroppedMoment() .Which.Should().BeOfType().Subject; move.TimeUtc.Should().BeCloseTo(droppedMoment, _pixelMomentTolerance); move.TimeUtc.Kind.Should().Be(DateTimeKind.Utc, "Npgsql binds only a UTC moment to timestamptz"); - _viewModel.Markers.Markers.Should().ContainSingle() + _viewModel.Markers.ShownMarkers.Should().ContainSingle() .Which.TimeUtc.Should().BeCloseTo( droppedMoment, _pixelMomentTolerance, @@ -366,7 +424,7 @@ public void AMarkerDragAcrossADataContextChange_EndsOnTheViewModelItBeganOn() .Which.TimeUtc.Should().BeCloseTo(droppedMoment, _pixelMomentTolerance); _viewModel.IsDragging.Should().BeFalse(); _channel.Push(marker); - _viewModel.Markers.Markers.Should().Equal([marker], "the landed move released its hold"); + _viewModel.Markers.ShownMarkers.Should().Equal([marker], "the landed move released its hold"); } [AvaloniaFact] @@ -420,7 +478,7 @@ public void ARightPressWithTheLeftHeldDuringAMarkerDrag_KeepsTheDragAndReleasesT _viewModel.IsDragging.Should().BeFalse(); var movedElsewhere = marker with { TimeUtc = MomentAt(0.75) }; _channel.Push(movedElsewhere); - _viewModel.Markers.Markers.Should().Equal([movedElsewhere], "the drag released its hold on the marker"); + _viewModel.Markers.ShownMarkers.Should().Equal([movedElsewhere], "the drag released its hold on the marker"); } [AvaloniaFact] @@ -454,7 +512,7 @@ public void ASecondTouchDuringAMarkerDrag_NeitherMovesNorEndsTheDrag() _viewModel.IsDragging.Should().BeFalse(); var movedElsewhere = marker with { TimeUtc = MomentAt(0.75) }; _channel.Push(movedElsewhere); - _viewModel.Markers.Markers.Should().Equal([movedElsewhere], "the drag released its hold on the marker"); + _viewModel.Markers.ShownMarkers.Should().Equal([movedElsewhere], "the drag released its hold on the marker"); } [AvaloniaFact] @@ -515,7 +573,7 @@ public void ADoubleClickInTheDataArea_AddsANumberedMarkerAtTheClickedMoment() add.Label.Should().Be("#1", "a new marker is numbered"); add.TimeUtc.Should().BeCloseTo(MomentAtPixel(clickedAt), _pixelMomentTolerance); add.TimeUtc.Kind.Should().Be(DateTimeKind.Utc, "Npgsql binds only a UTC moment to timestamptz"); - _viewModel.Markers.Markers.Should().ContainSingle().Which.Label.Should().Be("#1"); + _viewModel.Markers.ShownMarkers.Should().ContainSingle().Which.Label.Should().Be("#1"); Layer.Lines.Should().ContainSingle(); LabelEditor.IsOpen.Should().BeFalse("a double click opens no editor"); _viewModel.IsDragging.Should().BeFalse(); @@ -533,11 +591,60 @@ public void ADoubleClickOnAMarker_DeletesIt() _channel.Writes.Should().ContainSingle() .Which.Should().BeOfType() .Which.Marker.Should().Be(marker); - _viewModel.Markers.Markers.Should().BeEmpty(); + _viewModel.Markers.ShownMarkers.Should().BeEmpty(); Layer.Lines.Should().BeEmpty(); _viewModel.IsDragging.Should().BeFalse(); } + [AvaloniaFact] + public void ADoubleClickOnALockedMarker_LeavesItStored() + { + var marker = new StoredMarker(1, MomentAt(0.5), "Etch.csv", MarkerKind.RecipeStart, IsLocked: true); + _channel.Push(marker); + + HeadlessInput.Click(_shown.Window, _shown.PlotControl, MarkerPoint(marker)); + HeadlessInput.Click(_shown.Window, _shown.PlotControl, MarkerPoint(marker)); + + _channel.Writes.Should().BeEmpty("a double click on a locked marker neither deletes it nor adds one"); + _viewModel.Markers.ShownMarkers.Should().Equal([marker]); + Layer.Lines.Should().ContainSingle(); + _viewModel.IsDragging.Should().BeFalse(); + } + + [AvaloniaFact] + public void ADragOnALockedMarker_PansAndLeavesTheMarkerWhereItIs() + { + var marker = new StoredMarker(1, MomentAt(0.5), "Etch.csv", MarkerKind.RecipeStart, IsLocked: true); + _channel.Push(marker); + var fromBefore = _viewModel.Navigation.From; + var pressAt = MarkerPoint(marker); + var dropAt = new Point(pressAt.X - DragDistancePixels, pressAt.Y); + + _shown.Window.MouseDown(ToWindow(pressAt), MouseButton.Left); + _shown.Window.MouseMove(ToWindow(new Point(pressAt.X - (DragDistancePixels / 2.0), pressAt.Y))); + _shown.Window.MouseMove(ToWindow(dropAt)); + _shown.Window.MouseUp(ToWindow(dropAt), MouseButton.Left); + Dispatcher.UIThread.RunJobs(); + + _channel.Writes.Should().BeEmpty(); + _viewModel.Markers.ShownMarkers.Should().Equal([marker]); + _viewModel.Navigation.From.Should().BeAfter(fromBefore, "a drag to the left on a locked marker pans"); + _viewModel.IsDragging.Should().BeFalse(); + } + + [AvaloniaFact] + public void HoveringALockedMarker_KeepsTheHandAndSnapsTheCursorToItsMoment() + { + var marker = new StoredMarker(1, MomentAt(0.5), "Etch.csv", MarkerKind.RecipeStart, IsLocked: true); + _channel.Push(marker); + var handCursor = _shown.PlotControl.Cursor; + + _shown.Window.MouseMove(ToWindow(new Point(MarkerPoint(marker).X + WithinHitPixels, MarkerPoint(marker).Y))); + + _shown.PlotControl.Cursor.Should().BeSameAs(handCursor, "a press on a locked marker pans"); + _viewModel.CursorTime.Should().Be(marker.TimeUtc); + } + [AvaloniaFact] public void AddMarkerHere_AddsANumberedMarkerAtTheClickedMoment() { @@ -550,7 +657,7 @@ public void AddMarkerHere_AddsANumberedMarkerAtTheClickedMoment() .Which.Should().BeOfType().Subject; add.Label.Should().Be("#1"); add.TimeUtc.Should().BeCloseTo(MomentAtPixel(clickedAt), _pixelMomentTolerance); - _viewModel.Markers.Markers.Should().ContainSingle(); + _viewModel.Markers.ShownMarkers.Should().ContainSingle(); LabelEditor.IsOpen.Should().BeFalse(); } @@ -600,10 +707,118 @@ public void DeleteOnAMarker_RemovesIt() _channel.Writes.Should().ContainSingle() .Which.Should().BeOfType() .Which.Marker.Should().Be(marker); - _viewModel.Markers.Markers.Should().BeEmpty(); + _viewModel.Markers.ShownMarkers.Should().BeEmpty(); Layer.Lines.Should().BeEmpty(); } + [AvaloniaFact] + public void LockOnAnUnlockedMarker_ReadsLockAndLocksIt() + { + var marker = new StoredMarker(1, MomentAt(0.25), "Etch start"); + _channel.Push(marker); + + RightClick(MarkerPoint(marker)); + PickMenuItem("MarkerMenuFlyout", Resources.MarkerMenuLock); + + _channel.Writes.Should().ContainSingle() + .Which.Should().Be(new FakeMarkerWrite.Lock(marker, true)); + _viewModel.Markers.ShownMarkers.Should().ContainSingle().Which.IsLocked.Should().BeTrue(); + } + + [AvaloniaFact] + public void UnlockOnALockedMarker_ReadsUnlockAndUnlocksIt() + { + var marker = new StoredMarker(1, MomentAt(0.25), "Etch.csv", MarkerKind.RecipeStart, IsLocked: true); + _channel.Push(marker); + + RightClick(MarkerPoint(marker)); + PickMenuItem("MarkerMenuFlyout", Resources.MarkerMenuUnlock); + + _channel.Writes.Should().ContainSingle() + .Which.Should().Be(new FakeMarkerWrite.Lock(marker, false)); + _viewModel.Markers.ShownMarkers.Should().ContainSingle().Which.IsLocked.Should().BeFalse(); + } + + [AvaloniaFact] + public void AFailedLock_AfterAReadLockedTheMarkerWhileTheMenuWasOpen_KeepsTheStoredLock() + { + var marker = new StoredMarker(1, MomentAt(0.25), "Etch start"); + _channel.Push(marker); + var lockedMeanwhile = marker with { IsLocked = true }; + _channel.WriteResult = Result.Fail(FakeDataProvider.UnreachableArchive()); + + RightClick(MarkerPoint(marker)); + _channel.Push(lockedMeanwhile); + PickMenuItem("MarkerMenuFlyout", Resources.MarkerMenuLock); + + _channel.Writes.Should().ContainSingle() + .Which.Should().Be(new FakeMarkerWrite.Lock(lockedMeanwhile, true)); + _viewModel.Markers.ShownMarkers.Should().Equal([lockedMeanwhile], "the failure restores the lock the read stored"); + } + + [AvaloniaFact] + public void DeleteOnALockedMarker_RemovesIt() + { + var marker = new StoredMarker(1, MomentAt(0.25), "Etch.csv", MarkerKind.RecipeStart, IsLocked: true); + _channel.Push(marker); + + RightClick(MarkerPoint(marker)); + PickMenuItem("MarkerMenuFlyout", Resources.MarkerMenuDelete); + + _channel.Writes.Should().ContainSingle() + .Which.Should().Be(new FakeMarkerWrite.Delete(marker)); + Layer.Lines.Should().BeEmpty(); + } + + [AvaloniaFact] + public void RenameOnALockedMarker_RelabelsIt() + { + var marker = new StoredMarker(1, MomentAt(0.25), "Etch.csv", MarkerKind.RecipeStart, IsLocked: true); + _channel.Push(marker); + + OpenLabelEditorToRename(marker); + HeadlessInput.Clear(LabelEditorTopLevel, LabelBox); + HeadlessInput.Type(LabelEditorTopLevel, LabelBox, "Purge.csv"); + HeadlessInput.Click(LabelEditorTopLevel, LabelEditorButton("MarkerLabelOk")); + + _channel.Writes.Should().ContainSingle() + .Which.Should().Be(new FakeMarkerWrite.Rename(marker, "Purge.csv")); + Layer.Lines[1].LabelText.Should().StartWith("Purge.csv \u00B7 "); + } + + [AvaloniaFact] + public void AKindChangeBetweenTwoReads_RecoloursTheLine() + { + using var scope = ThemeProbe.ApplyVariant(ThemeVariant.Light); + Dispatcher.UIThread.RunJobs(); + var marker = new StoredMarker(1, MomentAt(0.25), "Etch.csv"); + _channel.Push(marker); + Layer.Lines[1].LineColor.Should().Be(ThemeProbe.PlotColour("AppMarkerLineBrush", ThemeVariant.Light)); + + _channel.Push(marker with { Kind = MarkerKind.RecipeEnd }); + + Layer.Lines[1].LineColor.Should().Be(ThemeProbe.PlotColour("AppRecipeMarkerLineBrush", ThemeVariant.Light)); + } + + [AvaloniaFact] + public void HidingRecipeMarkers_TakesTheirLinesOff_AndShowingThemBringsTheLinesBack() + { + var recipeStart = new StoredMarker(1, MomentAt(0.25), "Etch.csv", MarkerKind.RecipeStart, IsLocked: true); + var user = new StoredMarker(2, MomentAt(0.75), "#1"); + _channel.Push(recipeStart, user); + var recipeLine = Layer.Lines[1]; + + _viewModel.Markers.ToggleRecipeMarkers(); + + Layer.Lines.Keys.Should().Equal(2L); + _viewModel.Plot.GetPlottables().Should().NotContain(recipeLine); + + _viewModel.Markers.ToggleRecipeMarkers(); + + Layer.Lines.Keys.Should().BeEquivalentTo([1L, 2L]); + Layer.Lines[1].X.Should().Be(LocalTimeAxis.ToAxis(recipeStart.TimeUtc)); + } + [AvaloniaFact] public void RenameOnAMarker_WithANewLabelAndEnter_RelabelsIt() { @@ -642,7 +857,7 @@ public void RenameOnAMarker_WithAnEmptyLabelAndEnter_StoresNoLabel(string typed) _channel.Writes.Should().ContainSingle() .Which.Should().BeOfType() .Which.Label.Should().BeNull(); - _viewModel.Markers.Markers.Should().ContainSingle().Which.Label.Should().BeNull(); + _viewModel.Markers.ShownMarkers.Should().ContainSingle().Which.Label.Should().BeNull(); } [AvaloniaFact] diff --git a/SemiPlot/SemiPlot.Tests.Unit/UI/Chart/ChartMarkersTests.cs b/SemiPlot/SemiPlot.Tests.Unit/UI/Chart/ChartMarkersTests.cs index 743310c..c641b64 100644 --- a/SemiPlot/SemiPlot.Tests.Unit/UI/Chart/ChartMarkersTests.cs +++ b/SemiPlot/SemiPlot.Tests.Unit/UI/Chart/ChartMarkersTests.cs @@ -53,7 +53,7 @@ public async Task AnAdd_PlacesTheMarkerWithTheReturnedId() await Markers.AddAtAsync(_nine); _channel.Writes.Should().Equal(new FakeMarkerWrite.Add(_nine, "#1")); - Markers.Markers.Should().Equal(new StoredMarker(7, _nine, "#1")); + Markers.ShownMarkers.Should().Equal(new StoredMarker(7, _nine, "#1")); } [AvaloniaTheory] @@ -71,6 +71,19 @@ public async Task AnAdd_LabelsTheMarkerOnePastTheHighestNumberShown(string[] sho _channel.Writes.Should().Equal(new FakeMarkerWrite.Add(_nine, expected)); } + [AvaloniaFact] + public async Task AnAdd_NumbersPastTheUserMarkers_NotPastARecipeMarker() + { + _channel.Push( + new StoredMarker(1, _eight, "#3"), + new StoredMarker(2, _nine, "#9", MarkerKind.RecipeStart, IsLocked: true)); + _channel.AddResult = Result.Ok(3L); + + await Markers.AddAtAsync(_ten); + + _channel.Writes.Should().Equal(new FakeMarkerWrite.Add(_ten, "#4")); + } + [AvaloniaFact] public async Task AnAdd_AfterTheHighestNumberWasRenamed_TakesTheNextNumberOfTheRest() { @@ -92,7 +105,7 @@ public async Task AFailedAdd_PlacesNothing() await Markers.AddAtAsync(_nine); - Markers.Markers.Should().BeEmpty(); + Markers.ShownMarkers.Should().BeEmpty(); changes().Should().Be(0); } @@ -104,12 +117,12 @@ public async Task AReadLandingBeforeTheAddsId_LeavesOneMarker() var added = new StoredMarker(7, _nine, "#1"); var adding = Markers.AddAtAsync(_nine); - Markers.Markers.Should().BeEmpty("a pending add draws nothing until its id lands"); + Markers.ShownMarkers.Should().BeEmpty("a pending add draws nothing until its id lands"); _channel.Push(added); heldAdd.SetResult(); await adding; - Markers.Markers.Should().Equal(added); + Markers.ShownMarkers.Should().Equal(added); } [AvaloniaFact] @@ -120,11 +133,11 @@ public async Task AFailedMove_RestoresTheStoredMoment() Markers.BeginMove(_etchStart); Markers.Move(_nine); - Markers.Markers.Should().Equal([_etchStart with { TimeUtc = _nine }], "the line follows the pointer"); + Markers.ShownMarkers.Should().Equal([_etchStart with { TimeUtc = _nine }], "the line follows the pointer"); await Markers.EndMoveAsync(); _channel.Writes.Should().Equal(new FakeMarkerWrite.Move(_etchStart, _nine)); - Markers.Markers.Should().Equal(_etchStart); + Markers.ShownMarkers.Should().Equal(_etchStart); } [AvaloniaFact] @@ -137,12 +150,12 @@ public async Task AFailedMove_DuringASecondDragOfTheSameMarker_KeepsTheSecondDra Markers.BeginMove(_etchStart); Markers.Move(_nine); var firstMove = Markers.EndMoveAsync(); - Markers.BeginMove(Markers.Markers[0]); + Markers.BeginMove(Markers.ShownMarkers[0]); Markers.Move(_ten); heldMove.SetResult(); await firstMove; - Markers.Markers.Should().Equal(_etchStart with { TimeUtc = _ten }); + Markers.ShownMarkers.Should().Equal(_etchStart with { TimeUtc = _ten }); } [AvaloniaFact] @@ -155,7 +168,7 @@ public async Task AMoveOfAGoneMarker_RemovesIt() Markers.Move(_nine); await Markers.EndMoveAsync(); - Markers.Markers.Should().Equal(_etchEnd); + Markers.ShownMarkers.Should().Equal(_etchEnd); } [AvaloniaFact] @@ -166,7 +179,7 @@ public async Task ARenameOfAGoneMarker_RemovesIt() await Markers.RenameAsync(_etchStart, "Etch end"); - Markers.Markers.Should().Equal(_etchEnd); + Markers.ShownMarkers.Should().Equal(_etchEnd); } [AvaloniaFact] @@ -179,7 +192,7 @@ public async Task AReadAfterALandedMove_AppliesAgain() _channel.Push(_etchStart with { TimeUtc = _ten }); - Markers.Markers.Should().Equal([_etchStart with { TimeUtc = _ten }], "the landed move released its hold"); + Markers.ShownMarkers.Should().Equal([_etchStart with { TimeUtc = _ten }], "the landed move released its hold"); } [AvaloniaFact] @@ -190,7 +203,7 @@ public async Task AReadAfterALandedRename_AppliesAgain() _channel.Push(_etchStart with { Label = "Purge" }); - Markers.Markers.Should().Equal([_etchStart with { Label = "Purge" }], "the landed rename released its hold"); + Markers.ShownMarkers.Should().Equal([_etchStart with { Label = "Purge" }], "the landed rename released its hold"); } [AvaloniaFact] @@ -201,7 +214,7 @@ public async Task ARename_ShowsTheNewLabel() await Markers.RenameAsync(_etchStart, "Etch end"); _channel.Writes.Should().Equal(new FakeMarkerWrite.Rename(_etchStart, "Etch end")); - Markers.Markers.Should().Equal(_etchStart with { Label = "Etch end" }); + Markers.ShownMarkers.Should().Equal(_etchStart with { Label = "Etch end" }); } [AvaloniaTheory] @@ -214,7 +227,7 @@ public async Task ATypedLabel_IsStoredWithoutItsSurroundingBlanks(string typed, await Markers.RenameAsync(_etchStart, typed); _channel.Writes.Should().Equal(new FakeMarkerWrite.Rename(_etchStart, stored)); - Markers.Markers.Should().Equal(_etchStart with { Label = stored }); + Markers.ShownMarkers.Should().Equal(_etchStart with { Label = stored }); } [AvaloniaFact] @@ -225,7 +238,71 @@ public async Task AFailedRename_RestoresTheLabel() await Markers.RenameAsync(_etchStart, "Etch end"); - Markers.Markers.Should().Equal(_etchStart); + Markers.ShownMarkers.Should().Equal(_etchStart); + } + + [AvaloniaFact] + public async Task ALock_ShowsAtOnce_BeforeTheWriteLands() + { + _channel.Push(_etchStart); + var heldLock = _channel.HoldNextWrite(); + + var locking = Markers.ToggleLockAsync(_etchStart); + Markers.ShownMarkers.Should().Equal(_etchStart with { IsLocked = true }); + heldLock.SetResult(); + await locking; + + _channel.Writes.Should().Equal(new FakeMarkerWrite.Lock(_etchStart, true)); + Markers.ShownMarkers.Should().Equal(_etchStart with { IsLocked = true }); + } + + [AvaloniaFact] + public async Task AReadDuringALock_DoesNotUndoTheShownLock() + { + _channel.Push(_etchStart); + var heldLock = _channel.HoldNextWrite(); + + var locking = Markers.ToggleLockAsync(_etchStart); + _channel.Push(_etchStart); + Markers.ShownMarkers.Should().Equal(_etchStart with { IsLocked = true }); + heldLock.SetResult(); + await locking; + } + + [AvaloniaFact] + public async Task AFailedUnlock_RestoresTheLock() + { + var locked = _etchStart with { IsLocked = true }; + _channel.Push(locked); + _channel.WriteResult = Result.Fail(FakeDataProvider.UnreachableArchive()); + + await Markers.ToggleLockAsync(locked); + + _channel.Writes.Should().Equal(new FakeMarkerWrite.Lock(locked, false)); + Markers.ShownMarkers.Should().Equal(locked); + } + + [AvaloniaFact] + public async Task ALockOfAGoneMarker_RemovesIt() + { + _channel.Push(_etchStart, _etchEnd); + _channel.WriteResult = Result.Fail(FakeDataProvider.BenchArchiveError(ArchiveFault.MarkerGone, "Etch start")); + + await Markers.ToggleLockAsync(_etchStart); + + Markers.ShownMarkers.Should().Equal(_etchEnd); + } + + [AvaloniaFact] + public async Task ALock_StartsFromTheMarkerTheSetHolds_NotTheOneTheMenuSaw() + { + var renamedMeanwhile = _etchStart with { Label = "Purge" }; + _channel.Push(renamedMeanwhile); + + await Markers.ToggleLockAsync(_etchStart); + + _channel.Writes.Should().Equal(new FakeMarkerWrite.Lock(renamedMeanwhile, true)); + Markers.ShownMarkers.Should().Equal(renamedMeanwhile with { IsLocked = true }); } [AvaloniaFact] @@ -236,7 +313,7 @@ public async Task ADelete_RemovesTheMarker() await Markers.DeleteAsync(_etchStart); _channel.Writes.Should().Equal(new FakeMarkerWrite.Delete(_etchStart)); - Markers.Markers.Should().Equal(_etchEnd); + Markers.ShownMarkers.Should().Equal(_etchEnd); } [AvaloniaFact] @@ -247,7 +324,7 @@ public async Task AFailedDelete_KeepsTheMarker() await Markers.DeleteAsync(_etchStart); - Markers.Markers.Should().Equal(_etchStart); + Markers.ShownMarkers.Should().Equal(_etchStart); } [AvaloniaFact] @@ -259,7 +336,7 @@ public void AReadDuringADrag_DoesNotMoveTheDraggedMarker() Markers.Move(_nine); _channel.Push(_etchStart, _etchEnd); - Markers.Markers.Should().Equal(_etchStart with { TimeUtc = _nine }, _etchEnd); + Markers.ShownMarkers.Should().Equal(_etchStart with { TimeUtc = _nine }, _etchEnd); } [AvaloniaFact] @@ -276,16 +353,54 @@ public async Task Changed_FiresOncePerChange() _channel.Push(_etchStart with { TimeUtc = _nine }); changes().Should().Be(2); - await Markers.RenameAsync(Markers.Markers[0], "Etch end"); + await Markers.RenameAsync(Markers.ShownMarkers[0], "Etch end"); changes().Should().Be(3, "the rename shows at once, and its success changes nothing more"); - Markers.BeginMove(Markers.Markers[0]); + Markers.BeginMove(Markers.ShownMarkers[0]); Markers.Move(_ten); Markers.Move(_ten); await Markers.EndMoveAsync(); changes().Should().Be(4, "a pointer move to the same moment changes nothing"); } + [AvaloniaFact] + public void HidingRecipeMarkers_LeavesOnlyUserMarkersShown_WithOneChange() + { + var recipeStart = new StoredMarker(3, _nine, "Etch.csv", MarkerKind.RecipeStart, IsLocked: true); + _channel.Push(_etchStart, recipeStart, _etchEnd); + var changes = CountChanges(); + + Markers.ToggleRecipeMarkers(); + + changes().Should().Be(1); + Markers.ShowsRecipeMarkers.Should().BeFalse(); + Markers.ShownMarkers.Should().Equal(_etchStart, _etchEnd); + Markers.NearestWithin(_nine, TimeSpan.FromMinutes(1)).Should().BeNull(); + + Markers.ToggleRecipeMarkers(); + + changes().Should().Be(2); + Markers.ShownMarkers.Should().Equal(_etchStart, recipeStart, _etchEnd); + Markers.NearestWithin(_nine, TimeSpan.FromMinutes(1)).Should().Be(recipeStart); + } + + [AvaloniaFact] + public async Task AFailedRenameOfARecipeMarkerHiddenMeanwhile_RestoresItsLabel() + { + var recipeStart = new StoredMarker(3, _nine, "Etch.csv", MarkerKind.RecipeStart, IsLocked: true); + _channel.Push(_etchStart, recipeStart); + _channel.WriteResult = Result.Fail(FakeDataProvider.UnreachableArchive()); + var heldRename = _channel.HoldNextWrite(); + + var renaming = Markers.RenameAsync(recipeStart, "Purge.csv"); + Markers.ToggleRecipeMarkers(); + heldRename.SetResult(); + await renaming; + Markers.ToggleRecipeMarkers(); + + Markers.ShownMarkers.Should().Equal(_etchStart, recipeStart); + } + [AvaloniaFact] public void AFailedReadStream_ReachesThePanel() { diff --git a/SemiPlot/SemiPlot.Tests.Unit/UI/Chart/ChartPaletteTests.cs b/SemiPlot/SemiPlot.Tests.Unit/UI/Chart/ChartPaletteTests.cs index 1e94cb5..dd124c3 100644 --- a/SemiPlot/SemiPlot.Tests.Unit/UI/Chart/ChartPaletteTests.cs +++ b/SemiPlot/SemiPlot.Tests.Unit/UI/Chart/ChartPaletteTests.cs @@ -51,13 +51,14 @@ public void Apply_PaintsEverySurfaceWithTheVariantsPalette(AppThemeVariant theme [AvaloniaTheory] [InlineData(AppThemeVariant.Light)] [InlineData(AppThemeVariant.Dark)] - public void MarkerColors_ResolveBothMarkerKeysUnderTheVariant(AppThemeVariant theme) + public void MarkerColors_ResolveEveryMarkerKeyUnderTheVariant(AppThemeVariant theme) { var variant = App.VariantFor(theme); var palette = ChartPalette.MarkerColors(Application.Current!, variant); palette.Line.Should().Be(Resolve("AppMarkerLineBrush", variant)); + palette.RecipeLine.Should().Be(Resolve("AppRecipeMarkerLineBrush", variant)); palette.Label.Should().Be(Resolve("AppMarkerLabelBrush", variant)); palette.ReadingBackground.Should().Be(Resolve("AppContentBackgroundBrush", variant)); } diff --git a/SemiPlot/SemiPlot.Tests.Unit/UI/Chart/ChartPressRouterTests.cs b/SemiPlot/SemiPlot.Tests.Unit/UI/Chart/ChartPressRouterTests.cs index 9a3b584..312ee2a 100644 --- a/SemiPlot/SemiPlot.Tests.Unit/UI/Chart/ChartPressRouterTests.cs +++ b/SemiPlot/SemiPlot.Tests.Unit/UI/Chart/ChartPressRouterTests.cs @@ -133,6 +133,24 @@ public void Route_TurnsOnlyTheSecondClickOfAPanPressIntoAnAddOrADelete( ChartPressRouter.Route(region, modifiers, tool, clickCount).Should().Be(expected); } + [Theory] + [InlineData(KeyModifiers.None, LeftButtonTool.Pan, 1, ChartPressAction.PanOrPickPen)] + [InlineData(KeyModifiers.None, LeftButtonTool.Pan, 2, ChartPressAction.PanOrPickPen)] + [InlineData(KeyModifiers.Shift, LeftButtonTool.Pan, 2, ChartPressAction.PanOrPickPen)] + [InlineData(KeyModifiers.None, LeftButtonTool.Pan, 3, ChartPressAction.PanOrPickPen)] + [InlineData(KeyModifiers.Control, LeftButtonTool.Pan, 1, ChartPressAction.ShiftActivePen)] + [InlineData(KeyModifiers.Control, LeftButtonTool.Pan, 2, ChartPressAction.ShiftActivePen)] + [InlineData(KeyModifiers.None, LeftButtonTool.DeltaPlacement, 1, ChartPressAction.PlaceDeltaCursor)] + [InlineData(KeyModifiers.None, LeftButtonTool.DeltaPlacement, 2, ChartPressAction.PlaceDeltaCursor)] + public void Route_SendsALockedMarkerPressToAPanForEveryClickCount( + KeyModifiers modifiers, + LeftButtonTool tool, + int clickCount, + ChartPressAction expected) + { + ChartPressRouter.Route(ChartPressRegion.LockedMarker, modifiers, tool, clickCount).Should().Be(expected); + } + [Theory] [InlineData(0.0, 0.0, false)] [InlineData(4.0, 0.0, false)] diff --git a/SemiPlot/SemiPlot.Tests.Unit/UI/MainWindow/AppMenuBarTests.cs b/SemiPlot/SemiPlot.Tests.Unit/UI/MainWindow/AppMenuBarTests.cs index e9a7946..4b1aaed 100644 --- a/SemiPlot/SemiPlot.Tests.Unit/UI/MainWindow/AppMenuBarTests.cs +++ b/SemiPlot/SemiPlot.Tests.Unit/UI/MainWindow/AppMenuBarTests.cs @@ -95,6 +95,7 @@ public void EditMenu_HoldsTheSettingsItemThenThePenEditorItemEachBoundToItsComma [InlineData("ViewNavigationBar")] [InlineData("ViewLegend")] [InlineData("ViewMinimap")] + [InlineData("ViewRecipeMarkers")] public void ToggleItem_TakesItsCheckStateFromTheCommandAndWritesNothingBack(string itemName) { using var stand = NewWindowStand(); @@ -104,6 +105,8 @@ public void ToggleItem_TakesItsCheckStateFromTheCommandAndWritesNothingBack(stri { "ViewNavigationBar" => (viewModel.ToggleNavigationBarCommand, () => viewModel.IsNavigationBarVisible), "ViewLegend" => (viewModel.ToggleLegendCommand, () => viewModel.IsLegendVisible), + "ViewRecipeMarkers" => ( + viewModel.ToggleRecipeMarkersCommand, () => viewModel.ChartViewModel.Markers.ShowsRecipeMarkers), _ => (viewModel.ToggleMinimapCommand, () => viewModel.IsMinimapVisible) }; @@ -235,7 +238,8 @@ public void ViewMenu_HoldsThePenScaleSubmenuBetweenTheTogglesAndTheMessagePanel( .Select(item => item is Separator ? "-" : item.Name) .Should() .Equal( - "ViewNavigationBar", "ViewLegend", "ViewMinimap", "-", "ViewPenScale", "-", "ViewMessagePanel"); + "ViewNavigationBar", "ViewLegend", "ViewMinimap", "ViewRecipeMarkers", "-", "ViewPenScale", "-", + "ViewMessagePanel"); viewMenu.Items.OfType().Single(item => item.Name == "ViewPenScale").Items.OfType() .Select(item => item.Name) .Should() diff --git a/SemiPlot/SemiPlot.Tests.Unit/UI/MainWindow/MainWindowViewModelTests.cs b/SemiPlot/SemiPlot.Tests.Unit/UI/MainWindow/MainWindowViewModelTests.cs index 0ceb1d5..73f9c8e 100644 --- a/SemiPlot/SemiPlot.Tests.Unit/UI/MainWindow/MainWindowViewModelTests.cs +++ b/SemiPlot/SemiPlot.Tests.Unit/UI/MainWindow/MainWindowViewModelTests.cs @@ -234,6 +234,26 @@ public void Export_IsDisabledWhileTheChartHasNoPensAndEnabledAfterACatalogueWith canExecute.Should().Equal(false, true); } + [AvaloniaFact] + public async Task ToggleRecipeMarkers_FlipsTheChartsFlagAndTheMirroredProperty() + { + using var stand = NewWindowStand(); + var viewModel = stand.ViewModel; + var markers = viewModel.ChartViewModel.Markers; + + viewModel.ShowsRecipeMarkers.Should().BeTrue("a new window starts with recipe markers shown"); + + await viewModel.ToggleRecipeMarkersCommand.Execute(); + + markers.ShowsRecipeMarkers.Should().BeFalse(); + viewModel.ShowsRecipeMarkers.Should().BeFalse(); + + await viewModel.ToggleRecipeMarkersCommand.Execute(); + + markers.ShowsRecipeMarkers.Should().BeTrue(); + viewModel.ShowsRecipeMarkers.Should().BeTrue(); + } + private static async Task OpenPenEditorAsync(MainWindowViewModel viewModel) { var requests = new List(); diff --git a/SemiPlot/SemiPlot.Tests.Unit/UI/MainWindow/TrendWindowTests.cs b/SemiPlot/SemiPlot.Tests.Unit/UI/MainWindow/TrendWindowTests.cs index 8d55b68..ca49f57 100644 --- a/SemiPlot/SemiPlot.Tests.Unit/UI/MainWindow/TrendWindowTests.cs +++ b/SemiPlot/SemiPlot.Tests.Unit/UI/MainWindow/TrendWindowTests.cs @@ -72,7 +72,7 @@ public async Task TheChart_ReadsAndWritesThroughTheMarkerSyncTheWindowStarts() var markers = stand.ViewModel.ChartViewModel.Markers; stand.Scheduler.AdvanceBy(ArchiveReadLoop.ReadInterval.Ticks); - markers.Markers.Should().Equal(marker); + markers.ShownMarkers.Should().Equal(marker); await markers.DeleteAsync(marker); diff --git a/SemiPlot/SemiPlot.Tests.Unit/UI/Markers/FakeMarkerWriter.cs b/SemiPlot/SemiPlot.Tests.Unit/UI/Markers/FakeMarkerWriter.cs index 2d99bb7..fc71bb8 100644 --- a/SemiPlot/SemiPlot.Tests.Unit/UI/Markers/FakeMarkerWriter.cs +++ b/SemiPlot/SemiPlot.Tests.Unit/UI/Markers/FakeMarkerWriter.cs @@ -17,6 +17,8 @@ public sealed record Move(StoredMarker Marker, DateTime TimeUtc) : FakeMarkerWri public sealed record Rename(StoredMarker Marker, string? Label) : FakeMarkerWrite; + public sealed record Lock(StoredMarker Marker, bool IsLocked) : FakeMarkerWrite; + public sealed record Delete(StoredMarker Marker) : FakeMarkerWrite; } @@ -32,7 +34,7 @@ internal abstract class FakeMarkerWriter public Result AddResult { get; set; } = Result.Ok(1L); - /// The answer to a move, a rename and a delete. + /// The answer to a move, a rename, a lock and a delete. public Result WriteResult { get; set; } = Result.Ok(); /// Holds the next write until the test completes the gate. @@ -59,6 +61,11 @@ public Task RenameAsync(StoredMarker marker, string? label) return AnswerAsync(new FakeMarkerWrite.Rename(marker, label), () => WriteResult); } + public Task SetLockedAsync(StoredMarker marker, bool isLocked) + { + return AnswerAsync(new FakeMarkerWrite.Lock(marker, isLocked), () => WriteResult); + } + public Task DeleteAsync(StoredMarker marker) { return AnswerAsync(new FakeMarkerWrite.Delete(marker), () => WriteResult); diff --git a/SemiPlot/SemiPlot.Tests.Unit/UI/Markers/MarkerSyncTests.cs b/SemiPlot/SemiPlot.Tests.Unit/UI/Markers/MarkerSyncTests.cs index f0f0aa5..5f740da 100644 --- a/SemiPlot/SemiPlot.Tests.Unit/UI/Markers/MarkerSyncTests.cs +++ b/SemiPlot/SemiPlot.Tests.Unit/UI/Markers/MarkerSyncTests.cs @@ -143,15 +143,22 @@ public async Task ASecondWrite_StartsOnlyAfterTheFirstLands() new FakeMarkerWrite.Move(_etchStart, _etchStart.TimeUtc)); } - [Fact] - public async Task AFailedWrite_ReachesThePanelOnce_AndReturnsItsFailure() + [Theory] + [InlineData("Rename")] + [InlineData("Unlock")] + public async Task AFailedWrite_ReachesThePanelOnce_AndReturnsItsFailure(string write) { var gone = FakeDataProvider.BenchArchiveError(ArchiveFault.MarkerGone, "Etch start"); _store.WriteResult = Result.Fail(gone); - var renamed = await _sync.RenameAsync(_etchStart, "Etch end"); + var written = write switch + { + "Rename" => await _sync.RenameAsync(_etchStart, "Etch end"), + "Unlock" => await _sync.SetLockedAsync(_etchStart with { IsLocked = true }, false), + _ => throw new ArgumentOutOfRangeException(nameof(write), write, "Unknown write.") + }; - renamed.Errors.Should().ContainSingle().Which.Should().Be(gone); + written.Errors.Should().ContainSingle().Which.Should().Be(gone); _messagePanel.Entries.Should().ContainSingle() .Which.View.Should().Be(ArchiveFailureMapper.Map(gone)); } @@ -170,8 +177,29 @@ public async Task EveryWrite_EndsWithARead_WhateverItsOutcome() await _sync.MoveAsync(_etchStart, _etchEnd.TimeUtc); await _sync.RenameAsync(_etchStart, null); + await _sync.SetLockedAsync(_etchStart, true); await _sync.DeleteAsync(_etchStart); - _store.ReadCount.Should().Be(5); + _store.ReadCount.Should().Be(6); + } + + [Fact] + public async Task ALockWrite_WaitsForTheWriteAheadOfIt_AndReadsAfterItLands() + { + StartAndEnterTheWait(); + var heldRename = _store.HoldNextWrite(); + var renaming = _sync.RenameAsync(_etchStart, "Etch end"); + var locking = _sync.SetLockedAsync(_etchStart, true); + + _store.Writes.Should().ContainSingle("the lock queues behind the rename"); + + heldRename.SetResult(); + await renaming; + (await locking).IsSuccess.Should().BeTrue(); + + _store.Writes.Should().Equal( + new FakeMarkerWrite.Rename(_etchStart, "Etch end"), + new FakeMarkerWrite.Lock(_etchStart, true)); + _store.ReadCount.Should().Be(2, "each landed write asks for a read"); } [Fact] diff --git a/SemiPlot/SemiPlot.Tests.Unit/UI/Minimap/MinimapViewModelTests.cs b/SemiPlot/SemiPlot.Tests.Unit/UI/Minimap/MinimapViewModelTests.cs index 94891ad..06b3108 100644 --- a/SemiPlot/SemiPlot.Tests.Unit/UI/Minimap/MinimapViewModelTests.cs +++ b/SemiPlot/SemiPlot.Tests.Unit/UI/Minimap/MinimapViewModelTests.cs @@ -354,4 +354,23 @@ public async Task TimeMarkerFractions_PlaceEveryMarkerInsideTheExtentAlongTheStr stand.ViewModel.TimeMarkerFractions.Should().Equal([0.5], "a marker read gone leaves the strip"); } + + [AvaloniaFact] + public async Task TimeMarkerFractions_LeaveOutHiddenRecipeMarkers_AndTakeThemBackWhenShown() + { + using var stand = new MinimapStand(); + var span = _extentLast - _extentFirst; + stand.MarkerChannel.Push( + new StoredMarker(1, _extentFirst + (span / 4.0), "Etch.csv", MarkerKind.RecipeStart, IsLocked: true), + new StoredMarker(2, _extentFirst + (span / 2.0), "#1")); + await stand.LoadExtentAsync(); + + stand.Chart.Markers.ToggleRecipeMarkers(); + + stand.ViewModel.TimeMarkerFractions.Should().Equal(0.5); + + stand.Chart.Markers.ToggleRecipeMarkers(); + + stand.ViewModel.TimeMarkerFractions.Should().Equal(0.25, 0.5); + } } diff --git a/SemiPlot/SemiPlot.UI/Chart/ChartMarkerLines.cs b/SemiPlot/SemiPlot.UI/Chart/ChartMarkerLines.cs index ec0bb5b..e31600d 100644 --- a/SemiPlot/SemiPlot.UI/Chart/ChartMarkerLines.cs +++ b/SemiPlot/SemiPlot.UI/Chart/ChartMarkerLines.cs @@ -8,7 +8,7 @@ namespace SemiPlot.UI.Chart; -/// One dashed vertical line per marker on the time axis, labelled inside the data area's top edge. +/// One vertical line per marker on the time axis, labelled inside the data area's top edge. internal sealed class ChartMarkerLines(Plot plot) { private const float LineWidth = 1.5f; @@ -44,6 +44,11 @@ public void Sync(IReadOnlyList markers) line.X = LocalTimeAxis.ToAxis(marker.TimeUtc); line.LabelText = LabelTextOf(marker); + line.LinePattern = marker.IsLocked ? LinePattern.Solid : LinePattern.Dashed; + if (_palette is { } palette) + { + Paint(line, marker, palette); + } } var hasGoneLines = _lines.Count > markers.Count; @@ -85,15 +90,15 @@ public void Project(DateTime fromUtc, DateTime toUtc, double dataAreaWidth) } } - /// Recolours every line; a line added later takes the same colours. + /// Recolours every line by its marker's kind; a line added later takes the same colours. public void ApplyPalette(MarkerPalette palette) { _palette = palette; lock (_plot.Sync) { - foreach (var line in _lines.Values) + foreach (var marker in _markers) { - Paint(line, palette); + Paint(_lines[marker.Id], marker, palette); } } } @@ -151,9 +156,9 @@ private static double EstimatedLabelWidth(VerticalLine line) return LabelOffsetX + (line.LabelText.Length * line.LabelFontSize * LabelCharacterWidth); } - private static void Paint(VerticalLine line, MarkerPalette palette) + private static void Paint(VerticalLine line, StoredMarker marker, MarkerPalette palette) { - line.LineColor = palette.Line; + line.LineColor = marker.Kind == MarkerKind.User ? palette.Line : palette.RecipeLine; line.LabelFontColor = palette.Label; } @@ -163,16 +168,11 @@ private VerticalLine AddLine() line.Axes.XAxis = _plot.Axes.Bottom; line.EnableAutoscale = false; line.LineWidth = LineWidth; - line.LinePattern = LinePattern.Dashed; line.LabelOppositeAxis = true; line.ManualLabelAlignment = Alignment.UpperLeft; line.LabelOffsetX = LabelOffsetX; line.LabelOffsetY = LabelOffsetY; line.LabelBackgroundColor = Colors.Transparent; - if (_palette is { } palette) - { - Paint(line, palette); - } return line; } diff --git a/SemiPlot/SemiPlot.UI/Chart/ChartMarkers.cs b/SemiPlot/SemiPlot.UI/Chart/ChartMarkers.cs index bbeb916..5860ed3 100644 --- a/SemiPlot/SemiPlot.UI/Chart/ChartMarkers.cs +++ b/SemiPlot/SemiPlot.UI/Chart/ChartMarkers.cs @@ -34,11 +34,14 @@ public ChartMarkers(IMarkerChannel markerChannel, TrendChartViewModel chart) _disposables.Add(_markerChannel.Reads.Subscribe(ApplyRead, chart.ReportFailure)); } - /// The markers in time order, then by id; a new list per change. - public IReadOnlyList Markers => _markerSet.Markers; + /// The shown markers in time order, then by id; a new list per change. + public IReadOnlyList ShownMarkers => _markerSet.ShownMarkers; + + /// The window's own flag, not stored; a new window starts with recipe markers shown. + public bool ShowsRecipeMarkers => _markerSet.ShowsRecipeMarkers; /// - /// One signal per change of , raised on the UI thread; completes on dispose. + /// One signal per change of , raised on the UI thread; completes on dispose. /// public IObservable Changed => _changed.AsObservable(); @@ -47,6 +50,12 @@ public ChartMarkers(IMarkerChannel markerChannel, TrendChartViewModel chart) return _markerSet.NearestWithin(timeUtc, tolerance); } + public void ToggleRecipeMarkers() + { + _markerSet.ToggleRecipeMarkers(); + RaiseChanged(); + } + /// /// Stores a new marker labelled with the next number; it draws only once its id lands, and a failed add places /// nothing. @@ -61,7 +70,7 @@ public async Task AddAtAsync(DateTime timeUtc) } var placed = new StoredMarker(added.Value, timeUtc, label); - if (!Markers.Contains(placed)) + if (!_markerSet.All.Contains(placed)) { _markerSet.Place(placed); RaiseChanged(); @@ -117,6 +126,23 @@ await WriteHeldAsync( current => current with { Label = marker.Label }); } + /// + /// Stores the opposite of the lock carried and shows it at once; a failure restores the + /// lock the set held. + /// + public async Task ToggleLockAsync(StoredMarker seen) + { + var isLocked = !seen.IsLocked; + var marker = FindMarker(seen.Id) ?? seen; + _markerSet.Hold(marker.Id); + ReplaceHeld(marker.Id, current => current with { IsLocked = isLocked }); + + await WriteHeldAsync( + marker, + () => _markerChannel.SetLockedAsync(marker, isLocked), + current => current with { IsLocked = marker.IsLocked }); + } + /// Removes the marker once the delete lands; a failed delete keeps it. public async Task DeleteAsync(StoredMarker marker) { @@ -153,9 +179,9 @@ public void Dispose() private int NextNumber() { var highest = 0; - foreach (var marker in Markers) + foreach (var marker in _markerSet.All) { - if (NumberOf(marker.Label) is { } number) + if (marker.Kind == MarkerKind.User && NumberOf(marker.Label) is { } number) { highest = Math.Max(highest, number); } @@ -238,7 +264,7 @@ private void RemoveMarker(long id) private StoredMarker? FindMarker(long id) { - return Markers.FirstOrDefault(marker => marker.Id == id); + return _markerSet.All.FirstOrDefault(marker => marker.Id == id); } private void RaiseChanged() diff --git a/SemiPlot/SemiPlot.UI/Chart/ChartPalette.cs b/SemiPlot/SemiPlot.UI/Chart/ChartPalette.cs index 416f80f..6ed3783 100644 --- a/SemiPlot/SemiPlot.UI/Chart/ChartPalette.cs +++ b/SemiPlot/SemiPlot.UI/Chart/ChartPalette.cs @@ -19,6 +19,7 @@ public static class ChartPalette private const string MinorGridLineKey = "AppMinorGridLineBrush"; private const string AxisKey = "AppSecondaryForegroundBrush"; private const string MarkerLineKey = "AppMarkerLineBrush"; + private const string RecipeMarkerLineKey = "AppRecipeMarkerLineBrush"; private const string MarkerLabelKey = "AppMarkerLabelBrush"; public static void Apply(Plot plot, IResourceHost resources, ThemeVariant variant) @@ -48,6 +49,7 @@ public static MarkerPalette MarkerColors(IResourceHost resources, ThemeVariant v { return new MarkerPalette( Resolve(resources, variant, MarkerLineKey), + Resolve(resources, variant, RecipeMarkerLineKey), Resolve(resources, variant, MarkerLabelKey), Resolve(resources, variant, DataBackgroundKey)); } diff --git a/SemiPlot/SemiPlot.UI/Chart/ChartPressRouter.cs b/SemiPlot/SemiPlot.UI/Chart/ChartPressRouter.cs index 9acdd2c..822a328 100644 --- a/SemiPlot/SemiPlot.UI/Chart/ChartPressRouter.cs +++ b/SemiPlot/SemiPlot.UI/Chart/ChartPressRouter.cs @@ -20,7 +20,8 @@ public enum ChartPressRegion DataArea, ActivePenAxis, TimeAxis, - Marker + Marker, + LockedMarker } public static class ChartPressRouter @@ -53,6 +54,11 @@ public static ChartPressAction Route( return ChartPressAction.PlaceDeltaCursor; } + if (region == ChartPressRegion.LockedMarker) + { + return ChartPressAction.PanOrPickPen; + } + var isDoubleClick = clickCount == 2; if (region == ChartPressRegion.Marker) { diff --git a/SemiPlot/SemiPlot.UI/Chart/IMarkerChannel.cs b/SemiPlot/SemiPlot.UI/Chart/IMarkerChannel.cs index 7ea5796..620b650 100644 --- a/SemiPlot/SemiPlot.UI/Chart/IMarkerChannel.cs +++ b/SemiPlot/SemiPlot.UI/Chart/IMarkerChannel.cs @@ -4,7 +4,7 @@ namespace SemiPlot.UI.Chart; -/// The chart's way to the stored markers: every read on the UI thread, and the four writes. +/// The chart's way to the stored markers: every read on the UI thread. public interface IMarkerChannel { /// Every marker read that no write has overtaken, on the UI thread, in the order read. @@ -16,5 +16,7 @@ public interface IMarkerChannel Task RenameAsync(StoredMarker marker, string? label); + Task SetLockedAsync(StoredMarker marker, bool isLocked); + Task DeleteAsync(StoredMarker marker); } diff --git a/SemiPlot/SemiPlot.UI/Chart/MarkerPalette.cs b/SemiPlot/SemiPlot.UI/Chart/MarkerPalette.cs index bb00a03..ab3ac58 100644 --- a/SemiPlot/SemiPlot.UI/Chart/MarkerPalette.cs +++ b/SemiPlot/SemiPlot.UI/Chart/MarkerPalette.cs @@ -2,4 +2,4 @@ namespace SemiPlot.UI.Chart; -public readonly record struct MarkerPalette(Color Line, Color Label, Color ReadingBackground); +public readonly record struct MarkerPalette(Color Line, Color RecipeLine, Color Label, Color ReadingBackground); diff --git a/SemiPlot/SemiPlot.UI/Chart/TrendChartView.Markers.cs b/SemiPlot/SemiPlot.UI/Chart/TrendChartView.Markers.cs index e3a6942..901341e 100644 --- a/SemiPlot/SemiPlot.UI/Chart/TrendChartView.Markers.cs +++ b/SemiPlot/SemiPlot.UI/Chart/TrendChartView.Markers.cs @@ -6,6 +6,8 @@ using Serilog; +using LocalizedText = SemiPlot.UI.Localization.Resources; + namespace SemiPlot.UI.Chart; /// The chart's right-click menus and the marker label editor the rename opens. @@ -25,7 +27,14 @@ private void OpenChartMenu(Point position) _menuMoment = AnchorAt(position); _menuMarker = MarkerAt(position); - (_menuMarker is null ? _chartMenuFlyout : _markerMenuFlyout).ShowAt(PlotControl, true); + if (_menuMarker is null) + { + _chartMenuFlyout.ShowAt(PlotControl, true); + return; + } + + MarkerMenuLock.Header = _menuMarker.IsLocked ? LocalizedText.MarkerMenuUnlock : LocalizedText.MarkerMenuLock; + _markerMenuFlyout.ShowAt(PlotControl, true); } private async void OnAddMarkerClick(object? sender, RoutedEventArgs eventArgs) @@ -56,6 +65,24 @@ private void OnRenameMarkerClick(object? sender, RoutedEventArgs eventArgs) OpenMarkerLabelEditor(marker.Label ?? string.Empty, label => viewModel.Markers.RenameAsync(marker, label)); } + private async void OnLockMarkerClick(object? sender, RoutedEventArgs eventArgs) + { + if (_viewModel is not { } viewModel || _menuMarker is not { } marker) + { + return; + } + + try + { + await viewModel.Markers.ToggleLockAsync(marker); + } + catch (Exception failure) + { + Log.Error(failure, "The chart view failed to store a marker lock"); + viewModel.ReportFailure(failure); + } + } + private async void OnDeleteMarkerClick(object? sender, RoutedEventArgs eventArgs) { if (_viewModel is not { } viewModel || _menuMarker is not { } marker) diff --git a/SemiPlot/SemiPlot.UI/Chart/TrendChartView.axaml b/SemiPlot/SemiPlot.UI/Chart/TrendChartView.axaml index b330a02..743f8a4 100644 --- a/SemiPlot/SemiPlot.UI/Chart/TrendChartView.axaml +++ b/SemiPlot/SemiPlot.UI/Chart/TrendChartView.axaml @@ -22,6 +22,8 @@ + diff --git a/SemiPlot/SemiPlot.UI/Chart/TrendChartView.axaml.cs b/SemiPlot/SemiPlot.UI/Chart/TrendChartView.axaml.cs index 6256779..e031a2d 100644 --- a/SemiPlot/SemiPlot.UI/Chart/TrendChartView.axaml.cs +++ b/SemiPlot/SemiPlot.UI/Chart/TrendChartView.axaml.cs @@ -380,7 +380,7 @@ private void CreateMarkerLines(TrendChartViewModel viewModel) private void SyncMarkerLines(TrendChartViewModel viewModel) { - MarkerLines?.Sync(viewModel.Markers.Markers); + MarkerLines?.Sync(viewModel.Markers.ShownMarkers); ProjectMarkerLines(PlotControl.Bounds.Width); } @@ -389,7 +389,7 @@ private void UpdateMarkerReadings(TrendChartViewModel viewModel) { var navigation = viewModel.Navigation; MarkerReadings?.Update( - viewModel.Markers.Markers, + viewModel.Markers.ShownMarkers, viewModel.FindPen(viewModel.ActivePenId), viewModel.ActivePenReadingAt, navigation.From, @@ -558,7 +558,12 @@ private ChartPressRegion PressRegionAt(Point position, StoredMarker? marker) return ChartPressRegion.TimeAxis; } - return marker is null ? ChartPressRegion.DataArea : ChartPressRegion.Marker; + return marker is null ? ChartPressRegion.DataArea : MarkerRegion(marker); + } + + private static ChartPressRegion MarkerRegion(StoredMarker marker) + { + return marker.IsLocked ? ChartPressRegion.LockedMarker : ChartPressRegion.Marker; } private StoredMarker? MarkerAt(Point position) @@ -647,7 +652,7 @@ private void Hover(Point current, KeyModifiers modifiers) var marker = MarkerAt(current); var wouldDragMarker = marker is not null && ChartPressRouter.Route( - ChartPressRegion.Marker, + MarkerRegion(marker), modifiers, _viewModel!.ActiveLeftButtonTool, clickCount: 1) == ChartPressAction.DragMarker; diff --git a/SemiPlot/SemiPlot.UI/Localization/Resources.resx b/SemiPlot/SemiPlot.UI/Localization/Resources.resx index 1e3b1e7..d87e6ee 100644 --- a/SemiPlot/SemiPlot.UI/Localization/Resources.resx +++ b/SemiPlot/SemiPlot.UI/Localization/Resources.resx @@ -99,6 +99,9 @@ Minimap + + Recipe markers + Autoscale @@ -816,6 +819,12 @@ Rename + + Lock + + + Unlock + Delete diff --git a/SemiPlot/SemiPlot.UI/Localization/Resources.ru.resx b/SemiPlot/SemiPlot.UI/Localization/Resources.ru.resx index fdeb2a0..d477aab 100644 --- a/SemiPlot/SemiPlot.UI/Localization/Resources.ru.resx +++ b/SemiPlot/SemiPlot.UI/Localization/Resources.ru.resx @@ -99,6 +99,9 @@ Обзорная полоса + + Метки рецептов + Автомасштаб @@ -816,6 +819,12 @@ Переименовать + + Закрепить + + + Открепить + Удалить diff --git a/SemiPlot/SemiPlot.UI/MainWindow/AppMenuBar.axaml b/SemiPlot/SemiPlot.UI/MainWindow/AppMenuBar.axaml index b21f127..b891ab9 100644 --- a/SemiPlot/SemiPlot.UI/MainWindow/AppMenuBar.axaml +++ b/SemiPlot/SemiPlot.UI/MainWindow/AppMenuBar.axaml @@ -52,6 +52,11 @@ Command="{Binding ToggleMinimapCommand}" ToggleType="CheckBox" IsChecked="{Binding IsMinimapVisible, Mode=OneWay}" /> + diff --git a/SemiPlot/SemiPlot.UI/MainWindow/MainWindowViewModel.cs b/SemiPlot/SemiPlot.UI/MainWindow/MainWindowViewModel.cs index 832b268..b80c63b 100644 --- a/SemiPlot/SemiPlot.UI/MainWindow/MainWindowViewModel.cs +++ b/SemiPlot/SemiPlot.UI/MainWindow/MainWindowViewModel.cs @@ -39,6 +39,7 @@ public sealed class MainWindowViewModel : ReactiveObject, IDisposable private readonly Action _readCatalogueNow; private readonly InstanceLauncher _instanceLauncher; private readonly ObservableAsPropertyHelper _penScaleHeader; + private readonly ObservableAsPropertyHelper _showsRecipeMarkers; /// /// The window's parts are built and disposed by ; this view model holds them for the @@ -73,6 +74,10 @@ public MainWindowViewModel( _disposables.Add(_penScaleHeader = ChartViewModel .WhenAnyValue(chart => chart.DrawnPenId, chart => chart.Pens, (penId, _) => PenScaleHeaderFor(penId)) .ToProperty(this, viewModel => viewModel.PenScaleHeader)); + var markers = ChartViewModel.Markers; + _disposables.Add(_showsRecipeMarkers = markers.Changed + .Select(_ => markers.ShowsRecipeMarkers) + .ToProperty(this, viewModel => viewModel.ShowsRecipeMarkers, initialValue: markers.ShowsRecipeMarkers)); _disposables.Add(_aboutRequests); _disposables.Add(_exitRequests); @@ -86,6 +91,8 @@ public MainWindowViewModel( () => { IsLegendVisible = !IsLegendVisible; })); _disposables.Add(ToggleMinimapCommand = ReactiveCommand.Create( () => { IsMinimapVisible = !IsMinimapVisible; })); + _disposables.Add(ToggleRecipeMarkersCommand = ReactiveCommand.Create( + markers.ToggleRecipeMarkers)); _disposables.Add(AutoscaleCommand = ReactiveCommand.Create( () => ChartViewModel.AutoscaleActivePen())); _disposables.Add(InitialScaleCommand = ReactiveCommand.Create( @@ -150,12 +157,17 @@ public bool IsMinimapVisible /// The View menu's scale submenu header; it names the pen whose axis the chart draws. public string PenScaleHeader => _penScaleHeader.Value; + /// Mirrors the chart's flag, which raises no property notification of its own. + public bool ShowsRecipeMarkers => _showsRecipeMarkers.Value; + public ReactiveCommand ToggleNavigationBarCommand { get; } public ReactiveCommand ToggleLegendCommand { get; } public ReactiveCommand ToggleMinimapCommand { get; } + public ReactiveCommand ToggleRecipeMarkersCommand { get; } + public ReactiveCommand AutoscaleCommand { get; } public ReactiveCommand InitialScaleCommand { get; } diff --git a/SemiPlot/SemiPlot.UI/Markers/MarkerSync.cs b/SemiPlot/SemiPlot.UI/Markers/MarkerSync.cs index e780f6e..c741878 100644 --- a/SemiPlot/SemiPlot.UI/Markers/MarkerSync.cs +++ b/SemiPlot/SemiPlot.UI/Markers/MarkerSync.cs @@ -72,6 +72,11 @@ public Task RenameAsync(StoredMarker marker, string? label) return WriteAsync(() => _markerStore.RenameAsync(marker, label)); } + public Task SetLockedAsync(StoredMarker marker, bool isLocked) + { + return WriteAsync(() => _markerStore.SetLockedAsync(marker, isLocked)); + } + public Task DeleteAsync(StoredMarker marker) { return WriteAsync(() => _markerStore.DeleteAsync(marker)); diff --git a/SemiPlot/SemiPlot.UI/Minimap/MinimapViewModel.cs b/SemiPlot/SemiPlot.UI/Minimap/MinimapViewModel.cs index 4b80d3c..bb522aa 100644 --- a/SemiPlot/SemiPlot.UI/Minimap/MinimapViewModel.cs +++ b/SemiPlot/SemiPlot.UI/Minimap/MinimapViewModel.cs @@ -313,7 +313,7 @@ private void RefreshTimeMarkerFractions() } var fractions = new List(); - foreach (var marker in _chart.Markers.Markers) + foreach (var marker in _chart.Markers.ShownMarkers) { if (MinimapGeometry.FractionAt(ExtentFirst, ExtentLast, marker.TimeUtc) is { } fraction) { diff --git a/SemiPlot/SemiPlot.UI/Styles/Palette.axaml b/SemiPlot/SemiPlot.UI/Styles/Palette.axaml index d54038e..b93286f 100644 --- a/SemiPlot/SemiPlot.UI/Styles/Palette.axaml +++ b/SemiPlot/SemiPlot.UI/Styles/Palette.axaml @@ -85,6 +85,7 @@ + @@ -170,6 +171,7 @@ + diff --git a/docs/architecture/data-integration.md b/docs/architecture/data-integration.md index 5342210..6e327b1 100644 --- a/docs/architecture/data-integration.md +++ b/docs/architecture/data-integration.md @@ -270,10 +270,13 @@ A time marker is a vertical line the operator places on the chart at a moment | `id` | `bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY` | The marker's key; the server assigns it | | `t` | `timestamptz NOT NULL` | The marker's moment, an exact instant (Time boundary, below) | | `label` | `text CHECK (char_length(label) BETWEEN 1 AND 80)` | Optional: no label is `NULL`, and the check refuses `''` | +| `kind` | `smallint NOT NULL DEFAULT 0 CHECK (kind BETWEEN 0 AND 3)` | 0 is the operator's own marker; 1, 2 and 3 are the start, the end and the interruption of a recipe, which the SCADA inserts | +| `locked` | `boolean NOT NULL DEFAULT false` | A locked marker ignores the drag and the double click (`trend-interaction.md#the-time-markers`); the SCADA inserts its recipe markers locked | The table has no index, because every read takes all of it. It is not partitioned and is outside any -retention, so a marker outlives the day partition it points into. SemiBase v0.6.0 provisions it and grants -`semiplot` `SELECT, INSERT, UPDATE, DELETE` on it (`postgres-instance.md#the-semiplot-role`). +retention, so a marker outlives the day partition it points into. SemiBase v0.6.0 created it and v0.7.0 +added `kind` and `locked`. SemiBase grants `semiplot` `SELECT, INSERT, UPDATE, DELETE` on it +(`postgres-instance.md#the-semiplot-role`). ```csharp public interface IMarkerStore @@ -282,14 +285,27 @@ public interface IMarkerStore Task> AddAsync(DateTime timeUtc, string? label); Task MoveAsync(StoredMarker marker, DateTime timeUtc); Task RenameAsync(StoredMarker marker, string? label); + Task SetLockedAsync(StoredMarker marker, bool isLocked); Task DeleteAsync(StoredMarker marker); } -public sealed record StoredMarker(long Id, DateTime TimeUtc, string? Label); +public sealed record StoredMarker( + long Id, + DateTime TimeUtc, + string? Label, + MarkerKind Kind = MarkerKind.User, + bool IsLocked = false); + +public enum MarkerKind { User = 0, RecipeStart = 1, RecipeEnd = 2, RecipeInterrupted = 3 } ``` `StoredMarker` is one row as stored: `TimeUtc` has `DateTimeKind.Utc`, and a null `Label` is a stored -`NULL`. `PostgresMarkerStore` in `SemiPlot.DataSource.Postgres` is the only implementation. +`NULL`. The defaults of `Kind` and `IsLocked` are the column defaults, so a marker the viewer adds is the +row the add stores. The database does not enforce `locked`: the viewer's gestures honour it, and the +move and delete statements do not check it. A guarded statement that touched no row would read as +`MarkerGone` and remove a live marker from the window. A lock another window stores while this window +drags the marker is held off by the drag, and the drop overwrites the moment. `PostgresMarkerStore` in +`SemiPlot.DataSource.Postgres` is the only implementation. `AddPostgresData()` registers it by factory as a singleton beside the editor, over the same `NpgsqlDataSource`, so the one `semiplot` role and connection string serve it too. Its one consumer is `Markers/MarkerSync` (`overview.md#the-live-markers`). The chart names no Core interface for markers: it @@ -297,13 +313,14 @@ reads and writes through `Chart/IMarkerChannel`, its own port, which `MarkerSync | Operation | Constant | What the statement keeps | | --- | --- | --- | -| `ReadAsync` | `StoredMarkers` | `SELECT id, t, label FROM semiplot_markers ORDER BY t, id`: the whole table, in the order the chart keeps. | -| `AddAsync` | `AddMarker` | `INSERT ... RETURNING id`; the result is the new marker's id. | +| `ReadAsync` | `StoredMarkers` | `SELECT id, t, label, kind, locked FROM semiplot_markers ORDER BY t, id`: the whole table, in the order the chart keeps. A `kind` outside `MarkerKind` fails the read with `ShapeUnexpected` (Error semantics, below). | +| `AddAsync` | `AddMarker` | `INSERT INTO semiplot_markers (t, label) ... RETURNING id`; the result is the new marker's id, and `kind` and `locked` take their defaults. | | `MoveAsync` | `MoveMarker` | `UPDATE semiplot_markers SET t = @t WHERE id = @id`. | | `RenameAsync` | `RenameMarker` | `UPDATE semiplot_markers SET label = @label WHERE id = @id`; a null label binds `NULL`. | +| `SetLockedAsync` | `SetMarkerLocked` | `UPDATE semiplot_markers SET locked = @locked WHERE id = @id`. | | `DeleteAsync` | `DeleteMarker` | One row by id. Idempotent: a delete that touches no row succeeds, because the operator wanted the marker gone, as `RemoveMembership` does. | -A move or a rename must touch exactly one row. None touched means another window or an administrator +A move, a rename or a lock must touch exactly one row. None touched means another window or an administrator removed the marker, and the store returns `ArchiveFault.MarkerGone`, never success. `t` binds as `NpgsqlDbType.TimestampTz` with `DateTimeKind.Utc` and reads back with `Kind = Utc`; no `ArchiveTimeConverter` runs on the path. Every relation-naming failure carries `MarkersRelation`, @@ -314,7 +331,7 @@ editor trims the text and caps it at 80 characters, so the chart never reaches t that does gets `ValueRejected`. `ReadAsync` takes the read loop's stop token and rethrows `OperationCanceledException` ahead of the -mapper; the four writes take no token. `ArchiveStatementTextTests` does not pin these constants. +mapper; the five writes take no token. `ArchiveStatementTextTests` does not pin these constants. `MarkerStoreTests` (`SemiPlot.Tests.Integration`) runs every one of them as `semiplot` against a `CloneSource.Provisioned` clone, which also proves the grant, and pins the round trip of both UTC instants of the repeated autumn hour. @@ -1137,19 +1154,19 @@ that read's apply. | Connection refused or DNS failure at startup | failed `Result` | The startup-failure window opens, titled "No connection to the archive", naming the host and port, with a remedy | | Connection lost mid-session | failed `Result` on the query; realtime tick dropped | Chart keeps the data it has | | Three consecutive catalogue reads fail for lack of a connection | `ArchiveFault.ConnectionLost` on `PenCatalogueSync.ConnectionStates`; the loop keeps reading | The status indicator turns to the fault state and one `Warning` entry appears; the first catalogue read that succeeds restores the indicator and adds one `Info` entry | -| A column the read needs is absent (`42703`) | `ArchiveFault.ShapeUnexpected` with the server's detail | "The archive has an unexpected shape" — run `semibase site`, then find what altered the table | +| A column the read needs is absent (`42703`), or a marker read brings a `kind` `MarkerKind` does not define | `ArchiveFault.ShapeUnexpected` with the server's detail, or the value read | "The archive has an unexpected shape" — run `semibase site`, then find what altered the table | | Query timeout (`57014`) | `ArchiveFault.QueryTimedOut` | "The archive ended the statement"; `statement_timeout` is the `semiplot` role's own setting | | The database does not exist (`3D000`) | `ArchiveFault.DatabaseMissing` | "The archive is not provisioned" — run `semibase site` | | Credentials refused or a grant missing (`28P01`, `28000`, `42501`) | `ArchiveFault.AccessDenied` | "The archive refused access" — the user, password or grants | | A relation or function a statement needs does not exist (`42P01`, `42883`) | `ArchiveFault.TableMissing` whose detail names every relation that statement touches, or `semiplot_register_new_pens()` | "The archive is not provisioned" — run `semibase site`, which creates them all | | The catalogue re-read fails mid-session | failed `Result`; `PenCatalogueSync` keeps its snapshot | A connection-class failure logs one warning and goes to the bar's `ConnectionLost` entry, never to an entry of its own. Any other kind: nothing for the first two failures in a row, one log warning each; from the third one panel entry, coalesced with the ones after it. The next success applies everything stored since the last success | -| The marker re-read fails mid-session | failed `Result`; `MarkerSync` emits nothing and the chart keeps the markers it shows | As for the catalogue: a connection-class failure logs one warning and goes to the bar's entry, which the catalogue read raises; any other kind writes two log warnings, then one panel entry from the third failure in a row. Against a database without `semiplot_markers` that entry is a `TableMissing` Error about 10 s after the window opens, and the chart works without markers | +| The marker re-read fails mid-session | failed `Result`; `MarkerSync` emits nothing and the chart keeps the markers it shows | As for the catalogue: a connection-class failure logs one warning and goes to the bar's entry, which the catalogue read raises; any other kind writes two log warnings, then one panel entry from the third failure in a row. Against a database provisioned before SemiBase v0.7.0 that entry is an Error about 10 s after the window opens (`postgres-instance.md#what-semiplot-may-assume-about-the-server`), and the chart works without markers | | `semiplot_tags` present but empty | empty pen list, success | The chart area's own empty state, naming `Edit` -> `Pens and groups` -> `Refresh pen list`: no key has been registered as a pen yet. Not a message-panel entry: an empty catalogue is a state, not something that happened | | Archive present but no rows in the window | success, empty envelope list | Empty chart, no error | | A check constraint refuses a written value (`23514`) | `ArchiveFault.ValueRejected` | "The archive refused the value"; the field reverts, and the message line says why | | A group name another group already carries (`23505`) | `ArchiveFault.NameTaken` | "The name is already taken" | | A write names a pen or group that is gone (`23503`, or no row touched) | `ArchiveFault.RowGone` | "The entry no longer exists"; a refresh shows what the catalogue holds now | -| A move or rename names a time marker that is gone (no row touched) | `ArchiveFault.MarkerGone` | "The marker no longer exists"; the chart drops the marker | +| A move, rename or lock names a time marker that is gone (no row touched) | `ArchiveFault.MarkerGone` | "The marker no longer exists"; the chart drops the marker | ### Two error planes @@ -1182,13 +1199,13 @@ carries no file-access kind. | `AccessDenied` | `28P01`, `28000`, `42501` | the username | | `DatabaseMissing` | `3D000` | empty | | `TableMissing` | `42P01`, `42883` | every relation the failing statement touches: `trends` for the history and realtime reads, `semiplot_tags, trends` for the archive extent and the archive days, all three catalogue tables for the pen catalogue and every editor write, `semiplot_markers` for every marker statement; `semiplot_register_new_pens()` for the registration | -| `ShapeUnexpected` | `42703` | the server's own message | +| `ShapeUnexpected` | `42703`, or a marker read whose `kind` `MarkerKind` does not define | the server's own message, or `semiplot_markers.kind holds N, which MarkerKind does not define.` | | `QueryTimedOut` | `57014` | empty | | `ConnectionLost` | three consecutive catalogue reads that fail as `Unreachable` | the number of failures that raised it | | `ValueRejected` | `23514` on an editor or marker write | the pen's name, or the marker's label or local moment | | `NameTaken` | `23505` on an editor write | the group name asked for | | `RowGone` | `23503` on an editor write, or an update, rename or delete that touched no row | the pen or group name | -| `MarkerGone` | a marker move or rename that touched no row | the marker's label, or its local moment | +| `MarkerGone` | a marker move, rename or lock that touched no row | the marker's label, or its local moment | | `ReadFailed` | any other SQLSTATE, or a client-side throw, on a read or a write | the SQLSTATE, or empty | The write kinds come from `ArchiveExceptionMapper.MapWrite(exception, subject, relation)`. It maps @@ -1198,7 +1215,9 @@ caller's statement touches. The pen editor passes `PenCatalogRelations`: every e those three relations, and one provisioning run creates all three. The marker store passes `MarkersRelation`, so a marker write against a missing table names `semiplot_markers` and no pen table. `RowGone(subject)` is the form for an editor update that touched no row, and `MarkerGone(subject)` the -form for a marker move or rename that touched none; a marker's subject is in The marker store, above. +form for a marker move, rename or lock that touched none; a marker's subject is in The marker store, above. +`ShapeUnexpected(detail)` is the form for a value read back that the code cannot represent, the marker +read's `kind` guard. The subject is the pen's committed name for a pen change, including a `Name` change; for a rename it is the new name when the server refuses it and the stored name when the group is gone; a delete names the group; a membership names the pen when the diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md index a0a8df5..1ed0d17 100644 --- a/docs/architecture/overview.md +++ b/docs/architecture/overview.md @@ -279,6 +279,10 @@ two plain commands, Autoscale and Restore initial scale. They act on the active Each flag has one writer, the command the menu item invokes, and the item reads back that same flag `Mode=OneWay` — a `MenuItem` whose `IsChecked` were two-way would have the control as a second writer, and one reading back a property the command does not write would let a click move nothing on screen. +`Recipe markers` writes no row: `ToggleRecipeMarkersCommand` flips the chart's own flag through +`ChartMarkers.ToggleRecipeMarkers`, and the item reads `MainWindowViewModel.ShowsRecipeMarkers`, a mirror of that flag +over `ChartMarkers.Changed`, because `ChartMarkers` raises no property notification +(`trend-interaction.md#the-time-markers`). Row 4 is the one whose flag the operator is not the only source of. `MessagePanel.IsVisible` starts closed, so a session that never fails is never given the row, and `MessagePanelViewModel.Report` @@ -748,9 +752,9 @@ no other route. Nothing is pushed between windows, for the reasons | Part | Holds | | --- | --- | | `Markers/MarkerSync` | The read loop and the write queue over `IMarkerStore`. It implements `Chart/IMarkerChannel` and reports every failure but a lost connection to the message panel; a lost connection reaches it through the catalogue read's state (`#a-failed-read`). `TrendWindow` builds and disposes it. | -| `Chart/IMarkerChannel` | The chart's port: `Reads`, every read no write overtook, on the UI thread, and the four writes, each returning a `Result`. | -| `Chart/ChartMarkers` | `TrendChartViewModel.Markers`, created and disposed by the chart view model. It reconciles each read into a `MarkerSet`, runs the gestures' writes and raises `Changed` once per change. | -| `Core/Trends/MarkerSet` | The markers sorted by moment, then id, the hold counts and the hit test `NearestWithin`, a binary search. | +| `Chart/IMarkerChannel` | The chart's port: `Reads`, every read no write overtook, on the UI thread, and the five writes, each returning a `Result`. | +| `Chart/ChartMarkers` | `TrendChartViewModel.Markers`, created and disposed by the chart view model. It reconciles each read into a `MarkerSet`, runs the gestures' writes and raises `Changed` once per change, a flip of the recipe flag included. | +| `Core/Trends/MarkerSet` | Every marker in `All`, sorted by moment, then id; the shown ones in `ShownMarkers`, an array rebuilt only when the set or the `ShowsRecipeMarkers` flag changes; the hold counts; and the hit test `NearestWithin`, a binary search over `ShownMarkers`. | | `Chart/ChartMarkerLines` | One line per marker on the view's plot (`trend-interaction.md#the-time-markers`). | `Markers/` uses `Chart/` and `Bridge/`, and neither uses `Markers/`. `MarkerSync` implements @@ -768,12 +772,12 @@ failed read emits nothing and the chart keeps the markers it shows. A failure fo only logs a warning, and the bar's `ConnectionLost` entry, which the catalogue read raises, stands for it. Any other failure logs a warning for the first two in a row and goes to the panel from the third (`#a-failed-read`). Against a database -provisioned before SemiBase v0.6.0, which has no `semiplot_markers`, that is a `TableMissing` Error about -10 s after the window opens, and the chart works without markers. +provisioned before SemiBase v0.7.0 that is an Error about 10 s after the window opens +(`postgres-instance.md#what-semiplot-may-assume-about-the-server`), and the chart works without markers. #### The marker writes -The four writes, add, move, rename and delete, run through one `Bridge/ArchiveCallQueue` per window, one +The five writes, add, move, rename, lock and delete, run through one `Bridge/ArchiveCallQueue` per window, one at a time in the order issued, so two quick drags of one marker cannot commit out of order. A failed write goes to the panel through `ResultReporting.ReportFailure` and returns to its caller. Every write ends with `ReadNow()`, whatever its outcome, so the window that wrote reads again at once and every other window @@ -795,11 +799,12 @@ A write's own result updates the window at once, and the read after it confirms: | Add | Nothing until the id lands, then the marker; a read that brought the id first leaves one marker | Nothing is placed | | Move | The marker follows the pointer from the first move past the slop; the one write goes at the drop | The moment the drag began at | | Rename | The new label at once | The label the marker had | +| Lock, Unlock | The new state at once | The state the marker had | | Delete | The marker leaves once the delete lands | The marker stays | A marker with a write in flight, or under a drag, is held: a read does not move, relabel or remove it, and it stays when a read omits it. `MarkerSet` counts holds, so two overlapping writes on one marker keep -it held until both land. A failed move or rename restores the stored value only when its release brings +it held until both land. A failed move, rename or lock restores the stored value only when its release brings the count to zero, and a marker still held keeps the newer local state. `MarkerGone` removes the marker whatever the count. @@ -912,9 +917,9 @@ the archive extent, the archive days read and the windowed history read. `Postgr implements `ILiveSource` with the live-edge poll over the same archive. The chart draws history and follows the archive as it grows. The pen editor writes the catalogue through `IPenCatalogueEditor`, and every running chart follows what it writes within 5 s (`#the-live-catalogue`), except the start -values, which change nothing on screen (`#what-a-read-changes`). The chart places, drags, renames and -deletes time markers stored in `semiplot_markers`, and every window follows them within 5 s -(`#the-live-markers`). The export window writes the stored rows +values, which change nothing on screen (`#what-a-read-changes`). The chart places, drags, renames, +locks and deletes time markers stored in `semiplot_markers`, draws the SCADA's recipe markers and hides +them per window, and every window follows them within 5 s (`#the-live-markers`). The export window writes the stored rows of a range of at most 24 hours to a CSV file (`#the-export-window`). See [data-integration.md](./data-integration.md) for the contract and `docs/plans/` for the remaining work. diff --git a/docs/architecture/postgres-instance.md b/docs/architecture/postgres-instance.md index 6fc643f..b4bcd62 100644 --- a/docs/architecture/postgres-instance.md +++ b/docs/architecture/postgres-instance.md @@ -29,10 +29,11 @@ commissioning day and the copy that has drifted. - Provisioned by SemiBase v0.5.0 or newer. Both catalogue reads name `scale_min_on_start`, `scale_max_on_start` and `log_scale_on_start`, which v0.5.0 introduced; against an older schema every catalogue read fails with `42703`, `ArchiveFault.ShapeUnexpected` (`data-integration.md`). -- Provisioned by SemiBase v0.6.0 or newer for the time markers, because v0.6.0 introduced - `semiplot_markers`. Against an older schema every marker read fails with `42P01`, - `ArchiveFault.TableMissing` naming `semiplot_markers`, which the message panel shows from the third read - in a row; the rest of the viewer runs (`data-integration.md#the-marker-store`). +- Provisioned by SemiBase v0.7.0 or newer for the time markers, because v0.6.0 introduced + `semiplot_markers` and v0.7.0 its `kind` and `locked` columns. Against a v0.6.0 schema every marker + read fails with `42703`, `ArchiveFault.ShapeUnexpected`; against an older one with `42P01`, + `ArchiveFault.TableMissing` naming `semiplot_markers`. The message panel shows either from the third + read in a row, and the rest of the viewer runs (`data-integration.md#the-marker-store`). - The archive database holds `trends`, which the SCADA writes and SemiBase creates, the five configuration tables `semiplot_tags`, `semiplot_groups`, `semiplot_pen_groups`, `semiplot_markers` and `semiplot_meta`, which are SemiBase's outright, and `messages`, which is the SCADA's outright. Nothing of ours runs @@ -96,9 +97,10 @@ groups and adds and removes memberships; deleting a group removes its membership `ON DELETE CASCADE` and leaves the pens. `semiplot_markers` holds the chart's time markers, one row per marker: an identity `id`, a `timestamptz` -moment and an optional label of 1 to 80 characters. Every window reads all of it when it opens and every -5 s, and the chart writes it from its right-click menu and a marker drag -(`data-integration.md#the-marker-store`). +moment, an optional label of 1 to 80 characters, a `kind` and a `locked` flag. Every window reads all of it +when it opens and every 5 s, and the chart writes it from its right-click menu, a marker drag and a double +click (`data-integration.md#the-marker-store`). The SCADA inserts the recipe markers as `scada_writer`, +which holds `INSERT` on the table and nothing else on it: no `SELECT`, `UPDATE`, `DELETE` or `TRUNCATE`. An absent table and an empty catalogue are both normal states with their own message, and neither is ever a crash — but they travel in different channels. An empty catalogue is a successful read of zero diff --git a/docs/architecture/postgres-topology.md b/docs/architecture/postgres-topology.md index 7f44e3d..9e10db9 100644 --- a/docs/architecture/postgres-topology.md +++ b/docs/architecture/postgres-topology.md @@ -35,6 +35,7 @@ flowchart TB scada -- "writes rows" --> trends scada -- "creates and writes" --> msgs + scada -- "INSERT recipe markers
semiplot_markers" --> config prov -- "creates, never writes rows" --> trends prov -- "creates, never writes rows" --> config prov -- "creates" --> roles diff --git a/docs/architecture/trend-interaction.md b/docs/architecture/trend-interaction.md index d162917..8d63a20 100644 --- a/docs/architecture/trend-interaction.md +++ b/docs/architecture/trend-interaction.md @@ -219,10 +219,11 @@ handler is then the only writer of `Handled` for the wheel. Each event kind has point, and the handlers carry no modifier test of their own: the wheel goes through `Chart/ChartWheelRouter.Route(isAxisRegionHit, modifiers, delta)`, the left press through `Chart/ChartPressRouter.Route(region, modifiers, activeTool, clickCount)`. The view names the one -`ChartPressRegion` the press lands on (`ActivePenAxis`, `TimeAxis`, `Marker` or `DataArea`; the two bands -do not overlap, and `Marker` is a press inside the data rect within 4 px of a time marker), and the press -router checks the active pen's axis first, then Ctrl, then the time axis band, then the tool, then the -marker, then the click count (`#the-time-markers`, Add and delete). The left +`ChartPressRegion` the press lands on (`ActivePenAxis`, `TimeAxis`, `LockedMarker`, `Marker` or +`DataArea`; the two bands do not overlap, `LockedMarker` is a press inside the data rect within 4 px of a +locked time marker, and `Marker` the same press near an unlocked one), and the press router checks the +active pen's axis first, then Ctrl, then the time axis band, then the tool, then a locked marker (always +`PanOrPickPen`), then any other marker, then the click count (`#the-time-markers`, Add and delete). The left button is a single tool with an explicit state (`Chart/LeftButtonTool` = `Pan` | `DeltaPlacement`); the active tool is sourced from the navigation bar's delta-mode toggle (`TrendChartViewModel.ActiveLeftButtonTool`), so there is one left-button gesture, not overlapping hidden branches. Ctrl is a held key, not a tool. @@ -512,21 +513,24 @@ under sticky is now. A time marker is a stored vertical line at a moment, with an optional label of at most 80 characters: the operator marks an event worth returning to, the start of a process for one, and finds it again after a restart and in every other window (`overview.md#the-live-markers`, `data-integration.md#the-marker-store`). -The count has no cap: every window reads every marker and draws every one inside its time window. A marker +The count has no cap: every window reads every marker and draws every shown one inside its time window. +The SCADA adds recipe markers of its own, locked, at the start, the end and the interruption of a recipe. A marker list and bookmark navigation are not built (`trend-feature-spec.md` §CU-4); the minimap strip marks every marker of the archive with a tick (`#archive-overview-minimap`), and a press there brings it into the window. - **Drawing.** `Chart/ChartMarkerLines` owns one ScottPlot `VerticalLine` per marker, pinned to - `plot.Axes.Bottom` with `EnableAutoscale = false`: dashed, 1.5 px wide, in one theme colour for every - marker (`ui-theme.md#the-plot`). The label is the line's own label with `LabelOppositeAxis`, + `plot.Axes.Bottom` with `EnableAutoscale = false`, 1.5 px wide. A locked line is solid and an unlocked + one dashed; an operator's marker (`MarkerKind.User`) draws in the marker colour and a recipe marker in + the recipe colour (`ui-theme.md#the-plot`). The label is the line's own label with `LabelOppositeAxis`, `ManualLabelAlignment = UpperLeft`, offsets of 4 px and 12 px and a transparent background, so it hangs inside the data area under its top edge, right of the line, and draws no box. The default label covers the time axis ticks, and the strip above the data area is too narrow for it. The label text is the marker's label, a middle dot and the marker's local time as `HH:mm:ss`, or the time alone for an unlabelled marker. The time carries no date, which the hover readout shows. `Sync(markers)` is the one diff on the view side: it adds the line of a new id, removes the line of a - gone one, and sets the moment and the label text of every other line. The view calls it when it binds a view + gone one, and sets the moment, the label text, the pattern and the colour of every other line, since a + read can change the lock and the kind. The view calls it when it binds a view model and on every `Changed`, then requests a frame. `RemoveLines()` takes every line off the plot when the view binds again, so a rebind leaves one line per marker. - **Labels that do not fit.** `Project(from, to, dataAreaWidth)` hides a line outside the window, and a @@ -557,9 +561,10 @@ window. drop there lands in the one half (`data-integration.md#time-boundary`). - **Hover.** On a marker the cursor snaps to the marker's moment: `MoveCursor` receives that moment, and the hover readout lists every visible pen's value there. The pointer shows `SizeWestEast` only when a - press would drag the marker, so not with Ctrl held or in delta mode, and the hand elsewhere. While a + press would drag the marker, so not with Ctrl held, in delta mode or on a locked marker, and the hand + elsewhere. While a marker drags no readout follows it, and in delta mode the overlay stays hidden, as for every drag. -- **Drag.** A press on a marker routes to `ChartPressAction.DragMarker` after the axis region, Ctrl, the +- **Drag.** A press on an unlocked marker routes to `ChartPressAction.DragMarker` after the axis region, Ctrl, the time axis band and the tool. Ctrl therefore shifts the active pen over a marker, the time axis band opens its panel under one and never moves it, and delta mode places its cursor on top of one. The press captures the pointer and shows `SizeWestEast`. Past the 4 px slop the first move calls @@ -570,14 +575,21 @@ window. reaches it through the capture loss it raises, and a capture lost for another reason ends there too, as a pan keeps the window it reached. `EndMoveAsync` writes the moment of the last move, once. A release inside the slop is a click: it picks a pen, as a pan press does, and writes nothing. +- **The lock.** A locked marker ignores the two gestures that change a marker by accident, the drag and + the double click that deletes. `PressRegionAt` returns `ChartPressRegion.LockedMarker` for it, and the + router reads that region after the tool and maps it to `PanOrPickPen` for any click count: a drag on it + pans, and a double click on it neither deletes it nor adds a marker. The menu still finds it, so + `Rename`, `Delete` and `Unlock` act on it. The lock guards the gestures of the window that shows it, + not the stored row (`data-integration.md#the-marker-store`). - **Add and delete.** A double click adds a marker at the pointer's moment, and a double click on a marker - deletes it. A new marker is labelled `#N`, N one past the highest number among the shown labels of the - form `#` and decimal digits, or `#1` when there is none; the label is stored and `Rename` changes it + deletes it. A new marker is labelled `#N`, N one past the highest number among the labels of the form + `#` and decimal digits that the operator's markers carry, shown or hidden, or `#1` when there is none; + a recipe marker's label does not count; the label is stored and `Rename` changes it like any other. Two windows that add at once, or two quick double clicks in one window before the first add's id lands, can store the same number. The router reads the press's `ClickCount`: a second click routes to `ChartPressAction.AddMarker` where a single one would be `PanOrPickPen`, and to `DeleteMarker` where a - single one would be `DragMarker`, so only in the pan tool and without Ctrl. In delta mode a double click - places the delta cursors, and on an axis it opens that axis's panel. A third click is a single one again, + single one would be `DragMarker`, so only in the pan tool, without Ctrl and off a locked marker. In + delta mode a double click places the delta cursors, and on an axis it opens that axis's panel. A third click is a single one again, so a quick second double click on a new marker drags it rather than deleting it. The first click of the pair is an ordinary click and picks a pen. The marker shows once the add's id lands, and a failed add places nothing. The delete asks for no confirmation: a double click puts a lost marker back, and @@ -585,8 +597,9 @@ window. - **The right-click menu.** The tunnel release handler checks for the right button ahead of its left-button guard. A right release inside the data rect with no drag under way opens a `MenuFlyout` at the pointer through `ShowAt(PlotControl, true)`, as the two panels open: `MarkerMenuFlyout` (`Rename`, - `Delete`) on a marker, `ChartMenuFlyout` (`Add marker here`) elsewhere. The view keeps the clicked moment - and the marker hit. `Add marker here` adds a numbered marker at once, as a double click does. No `ContextFlyout` is declared, because `ContextRequested` may never fire on + `Lock` or `Unlock`, `Delete`) on a marker, `ChartMenuFlyout` (`Add marker here`) elsewhere. The view + keeps the clicked moment and the marker hit. `Add marker here` adds a numbered marker at once, as a + double click does. No `ContextFlyout` is declared, because `ContextRequested` may never fire on `AvaPlot`. With no pens `EmptyCatalogueMessage` covers the centre of the plot and takes the click there; a marker without pens has no use. - **The label editor.** One keyed flyout, `MarkerLabelFlyout`, opened by `Rename` only: a focused @@ -599,6 +612,15 @@ window. or a move carries the moment rounded to the microseconds `timestamptz` keeps, so the marker set changes once more by under a microsecond, which redraws nothing visible. - **Delete.** `Delete` removes the marker once the store answers, and a failed delete keeps it. +- **Lock and Unlock.** One item, `MarkerMenuLock`, whose header `OpenChartMenu` sets from the marker's + lock before the flyout shows. It writes the opposite of that header state through + `ChartMarkers.ToggleLockAsync`, which starts from the marker as the set holds it at the click: the line + changes its pattern at once, and a failed write restores the lock that read stored. +- **Hiding the recipe markers.** `View` -> `Recipe markers` hides the recipe markers in one window. The + flag is `MarkerSet.ShowsRecipeMarkers`, flipped through `ChartMarkers.ToggleRecipeMarkers`, which + raises `Changed`. It is not stored, and a new window starts with the recipe markers shown. A hidden + marker leaves `ShownMarkers`, so it loses its line, its reading, its hit and its minimap tick, and stays in + `MarkerSet.All`, so a revert or a `MarkerGone` of a write that began before the hiding still lands. ## Decimation & performance (architectural core) @@ -723,11 +745,11 @@ fraction → `NavigateToFraction`, which recenters the window via the **same** `ChartNavigationController` the chart navigates with. The highlight tracks every `WindowChanged` (pan / zoom and the sticky live-edge advance) and every move of the right bound. -**The time markers.** The strip draws one full-height 1 px tick per time marker inside the extent, in -`AppMarkerLineBrush`, over the highlight and under the hover line (`#the-time-markers`). The ticks show -where the markers outside the window are; a press on one navigates as a press anywhere on the strip does, +**The time markers.** The strip draws one full-height 1 px tick per shown time marker inside the extent, +recipe markers included, in `AppMarkerLineBrush`, over the highlight and under the hover line +(`#the-time-markers`). The ticks show where the markers outside the window are; a press on one navigates as a press anywhere on the strip does, so the ticks take no pointer. `MinimapViewModel.TimeMarkerFractions` comes from -`MinimapGeometry.FractionAt` over the chart's `Markers`, which drops a marker outside the extent, and is +`MinimapGeometry.FractionAt` over the chart's `ShownMarkers`, which drops a marker outside the extent, and is recomputed on every `ChartMarkers.Changed`, on the extent read and on every move of the right bound. The view draws the fractions as one `Path` of `LineGeometry` children, `TimeMarkerTicks`. diff --git a/docs/architecture/ui-text.md b/docs/architecture/ui-text.md index a950820..5a942f8 100644 --- a/docs/architecture/ui-text.md +++ b/docs/architecture/ui-text.md @@ -402,13 +402,16 @@ reaches the message panel, not this line. ## The marker menu and label editor's text -`Chart/TrendChartView.axaml` reads every string of the time markers but the line label, which -`Chart/ChartMarkerLines` formats (`trend-interaction.md#the-time-markers`): +`Chart/TrendChartView.axaml` reads every string of the time markers but three. `Chart/ChartMarkerLines` +formats the line label, `TrendChartView.Markers.cs` sets the lock item's header from the marker's lock, +and `MainWindow/AppMenuBar.axaml` reads the `View` item (`trend-interaction.md#the-time-markers`): | Key | English / Russian | Where | | --- | --- | --- | | `MarkerMenuAdd` | "Add marker here" / "Добавить метку здесь" | The chart menu, off a marker | | `MarkerMenuRename`, `MarkerMenuDelete` | "Rename" / "Переименовать", "Delete" / "Удалить" | The marker menu | +| `MarkerMenuLock`, `MarkerMenuUnlock` | "Lock" / "Закрепить", "Unlock" / "Открепить" | The marker menu, over an unlocked and a locked marker | +| `MenuViewRecipeMarkers` | "Recipe markers" / "Метки рецептов" | The `View` item that hides the recipe markers | | `MarkerLabelPlaceholder` | "Label (optional)" / "Подпись (необязательно)" | The label box's watermark | | `MarkerLabelOk`, `MarkerLabelCancel` | "OK" / "ОК", "Cancel" / "Отмена" | The editor's buttons | | `MarkerLineLabelFormat` | "{0} · {1}" in both sets | A labelled marker's line: the label, then its local time | diff --git a/docs/architecture/ui-theme.md b/docs/architecture/ui-theme.md index 936e36a..ca8caf4 100644 --- a/docs/architecture/ui-theme.md +++ b/docs/architecture/ui-theme.md @@ -148,7 +148,7 @@ and the picker's flyout keep Semi's 6 px, as the menu flyout does. ## The application's own surfaces -Semi owns the controls; these fifteen keys are ours, and each exists in both variants. +Semi owns the controls; these sixteen keys are ours, and each exists in both variants. | Key | Consumers | Light | Dark | | --- | --- | --- | --- | @@ -165,7 +165,8 @@ Semi owns the controls; these fifteen keys are ours, and each exists in both var | `AppSeverityInfoBrush` | The same dot on an `Info` entry | `#3574F0` | `#3574F0` | | `AppConnectionOkBrush` | The status bar's connection indicator, `connection-ok` | `#208A3C` | `#5FAD65` | | `AppConnectionFaultBrush` | The same indicator, `connection-fault` | `#DB3B4B` | `#E55765` | -| `AppMarkerLineBrush` | Every time marker line on the plot (`#the-plot`) and its tick on the minimap strip | `#6F737A` | `#A8ADBD` | +| `AppMarkerLineBrush` | The operator's time marker lines on the plot (`#the-plot`), and the tick of every shown marker on the minimap strip | `#6F737A` | `#A8ADBD` | +| `AppRecipeMarkerLineBrush` | The recipe marker lines on the plot | `#834DF0` | `#A571E6` | | `AppMarkerLabelBrush` | Every time marker label on the plot | `#000000` | `#DFE1E5` | Pen colours are not theme keys. They come from the archive with the pen and stay per pen under both @@ -458,18 +459,22 @@ of the last paint and does nothing when the axis set did not grow, and it never because every site that bumps `ScalesRevision` already follows with `RequestRedraw()`, which the view joins into the next display frame. -The time markers take two keys of their own, outside the five surfaces. `ChartPalette.MarkerColors` -resolves `AppMarkerLineBrush` and `AppMarkerLabelBrush` under the variant into a `MarkerPalette`, and -`ApplyChartPalette` hands it to the marker layer after every `Apply`, so a variant switch repaints every -marker line. `ChartMarkerLines.ApplyPalette` keeps the palette, and a line the layer adds later takes the -same colours. The line is a neutral grey, so it does not compete with the pens' colours, and the label is -the variant's default text colour; all four values are tones the palette already carries. Every marker -draws in these two colours, and a marker carries no colour of its own. The palette also carries -`AppContentBackgroundBrush` as the background of the active pen's reading at each marker, drawn at 85 % -opacity so the number stays legible over the pen lines; the reading's dot takes the active pen's colour. -`ChartPaletteTests.MarkerColors_ResolveBothMarkerKeysUnderTheVariant` resolves both keys under both +The time markers take three keys of their own, outside the five surfaces. `ChartPalette.MarkerColors` +resolves `AppMarkerLineBrush`, `AppRecipeMarkerLineBrush` and `AppMarkerLabelBrush` under the variant into +a `MarkerPalette`, and `ApplyChartPalette` hands it to the marker layer after every `Apply`, so a variant +switch repaints every marker line. `ChartMarkerLines.ApplyPalette` keeps the palette and recolours each +line by its marker's kind, and a line the layer adds later takes the same colours. The operator's line is +a neutral grey, so it does not compete with the pens' colours, and the label is the variant's default +text colour; those four values are tones the palette already carries. The recipe line is a purple apart +from the accent blue, the severity red and amber and the connection green. A marker's kind picks its line +colour, every label draws in the one label colour, and a marker carries no colour of its own. The palette +also carries `AppContentBackgroundBrush` as the background of the active pen's reading at each marker, +drawn at 85 % opacity so the number stays legible over the pen lines; the reading's dot takes the active +pen's colour. +`ChartPaletteTests.MarkerColors_ResolveEveryMarkerKeyUnderTheVariant` resolves every marker key under both variants, and `ChartMarkerViewTests.AfterAThemeVariantSwitch_EveryMarkerDrawsInTheNewVariant` reads an -existing line and a later one after a switch. +existing line and a later one after a switch; `AfterAThemeVariantSwitch_ARecipeLineKeepsTheRecipeColour` +reads a recipe line. The minor gridlines take their colour on every axis but draw only on a log10 axis: `ChartAxisBinder` sets their width to 1 px when the drawn axis is logarithmic and to 0 otherwise (`charting.md#log10-y-axis`). diff --git a/docs/plans/completed/20261028-recipe-markers-on-chart.md b/docs/plans/completed/20261028-recipe-markers-on-chart.md new file mode 100644 index 0000000..d12ed1c --- /dev/null +++ b/docs/plans/completed/20261028-recipe-markers-on-chart.md @@ -0,0 +1,322 @@ +# Recipe markers on the chart + +## Overview + +- The chart reads two new `semiplot_markers` columns, `kind` and `locked`, which SemiBase v0.7.0 ships + (Semiteq/SemiBase#21). The SCADA inserts recipe markers (kind 1 start, 2 end, 3 interrupted) with + `locked = true`; the viewer's own markers are kind 0. +- A locked marker ignores the two gestures that change a marker by accident, the drag and the double + click that deletes; the marker menu still renames and deletes it and gains `Lock` / `Unlock`. The + database does not enforce `locked`; the viewer's gestures honour it. +- A recipe marker draws in its own palette colour on the chart; its minimap tick keeps the one marker + colour (`docs/architecture/ui-theme.md`). A locked line draws solid instead of dashed. A + checkable `View` item hides the recipe markers in one window. +- The lock guards against gestures in the window that shows it. The move and delete statements do not + check `locked`: a lock another window stores while this window drags the marker is held off by the + drag (`MarkerSet.cs:31-34`), and the drop overwrites the moment. The statements stay unguarded, + because a guarded write that touches no row maps to `MarkerGone` and would remove a live marker. +- SemiBase v0.7.0 is the minimum. Against an older database every marker read fails with `42703`, + `ShapeUnexpected` (`ArchiveExceptionMapper.cs:116`), not the `TableMissing` that + `docs/architecture/postgres-instance.md:33-34` describes for a database without the table. +- This is the first of two PRs for #160. The second, picking an export range by markers and the CSV + file name, is out of scope here. + +## Context (from discovery) + +- `StoredMarker(long Id, DateTime TimeUtc, string? Label)` is the one marker type + (`SemiPlot.Core/Data/IMarkerStore.cs:20`); `IMarkerStore` has read, add, move, rename and delete + (`IMarkerStore.cs:6-17`). +- The read is `SELECT id, t, label FROM semiplot_markers ORDER BY t, id` + (`SemiPlot.DataSource.Postgres/ArchiveStatements.cs:143`), its column order is `StoredMarkerColumn` + (`ArchiveStatements.cs:33-38`), and `PostgresMarkerStore.ReadAsync` maps a row + (`PostgresMarkerStore.cs:47-53`). Move and rename share `UpdateOneRowAsync`, which returns + `MarkerGone` when no row is touched (`PostgresMarkerStore.cs:150-172`). +- `Chart/IMarkerChannel` mirrors the four writes (`IMarkerChannel.cs:13-19`); `Markers/MarkerSync` + implements it through one `ArchiveCallQueue` (`MarkerSync.cs:28`, `MarkerSync.cs:65-75`). +- `Chart/ChartMarkers` holds the `MarkerSet`, runs each write with hold and revert + (`ChartMarkers.cs:107-118`, `ChartMarkers.cs:187-212`) and numbers new labels from every shown + marker (`ChartMarkers.cs:153-165`). Its `Markers` and `Changed` feed the lines + (`TrendChartView.axaml.cs:371-385`), the readings (`TrendChartView.axaml.cs:390-392`) and the minimap + ticks (`MinimapViewModel.cs:53`, `MinimapViewModel.cs:308-325`). The hit test is + `ChartMarkers.NearestWithin` over `MarkerSet.NearestWithin` (`ChartMarkers.cs:45-48`, + `MarkerSet.cs:116-150`). +- The press router maps a marker press to `DragMarker` and a double click to `DeleteMarker` + (`ChartPressRouter.cs:56-60`); the view takes the region from `PressRegionAt` + (`TrendChartView.axaml.cs:548-562`) and the hover cursor from the same route + (`TrendChartView.axaml.cs:647-654`). +- The marker menu is a `MenuFlyout` with `Rename` and `Delete` (`TrendChartView.axaml:22-27`); + `OpenChartMenu` stores the marker under the pointer in `_menuMarker` + (`TrendChartView.Markers.cs:18-29`). +- `ChartMarkerLines.AddLine` draws every line dashed (`ChartMarkerLines.cs:166`) and paints it from + `MarkerPalette(Line, Label, ReadingBackground)` (`MarkerPalette.cs:5`, `ChartMarkerLines.cs:154-158`), + built from `AppMarkerLineBrush` and `AppMarkerLabelBrush` (`ChartPalette.cs:21`, `ChartPalette.cs:47-53`, + `Styles/Palette.axaml:86-87`, `Styles/Palette.axaml:171-172`). +- The `View` menu's checkable items bind `IsChecked` `Mode=OneWay` and write through a command + (`MainWindow/AppMenuBar.axaml:40-54`, `MainWindowViewModel.cs:87-88`); `MainWindowViewModel` holds the + chart as `ChartViewModel` (`MainWindowViewModel.cs:62`). +- `docs/architecture/postgres-instance.md:49` lists the `semiplot` role's privileges; the grant + `scada_writer` now holds on `semiplot_markers` is not stated anywhere in this repository. + +## Development Approach + +- **testing approach**: Regular (code first, then tests) +- complete each task fully before moving to the next +- make small, focused changes +- **CRITICAL: every task MUST include new/updated tests** for code changes in that task +- **CRITICAL: all tests must pass before starting next task** - no exceptions +- **CRITICAL: update this plan file when scope changes during implementation** +- run tests after each change + +## Testing Strategy + +- **unit tests**: `SemiPlot.Tests.Unit` for the Core set, the router, `ChartMarkers`, `MarkerSync`, the + lines, the menus and the view model. +- **integration tests**: `SemiPlot.Tests.Integration/MarkerStoreTests.cs` for the new columns and the + lock write, against the `ghcr.io/semiteq/semibase:latest` image, which is v0.7.0. +- no e2e suite beyond the headless view tests. + +## Acceptance Evidence + +The behaviour does not exist today: `StoredMarker` carries no kind or lock, and a double click on any +marker deletes it (`ChartPressRouter.cs:59`). Each item below is a test that is red before the change +and green after it. + +1. `dotnet test SemiPlot/SemiPlot.Tests.Unit/SemiPlot.Tests.Unit.csproj --filter "FullyQualifiedName~ChartPressRouterTests"`: + a press on a locked marker routes to `PanOrPickPen` for one click and for two. +2. `dotnet test SemiPlot/SemiPlot.Tests.Unit/SemiPlot.Tests.Unit.csproj --filter "FullyQualifiedName~ChartMarkersTests"`: + `ToggleLockAsync` shows the new state at once and restores it on failure; hiding recipe markers + leaves only kind 0 in `ShownMarkers` and out of `NearestWithin`; numbering ignores a recipe marker's `#N` + label. +3. `dotnet test SemiPlot/SemiPlot.Tests.Integration/SemiPlot.Tests.Integration.csproj --filter "FullyQualifiedName~MarkerStoreTests"`: + a row inserted with `kind = 1, locked = true` reads back with both; `SetLockedAsync` writes that + row only; a lock write to a deleted marker is `MarkerGone`. +4. Manual, on the stand (`dotnet run --project SemiPlot/SemiPlot.AppHost`), after + `INSERT INTO semiplot_markers (t, label, kind, locked) VALUES (now(), 'Etch.csv', 1, true)` as + `postgres`: + 1. The marker draws solid in the recipe colour. + 2. A drag on it pans the chart; a double click on it does nothing. + 3. The marker menu shows `Unlock`; after it the line draws dashed and drags. + 4. `View` -> `Recipe markers` unticked removes the line and its minimap tick; ticked brings them back. + +## Progress Tracking + +- mark completed items with `[x]` immediately when done +- add newly discovered tasks with ➕ prefix +- document issues/blockers with ⚠️ prefix +- keep plan in sync with actual work done + +## Solution Overview + +- `StoredMarker` gains `Kind` (a Core enum `MarkerKind`: `User = 0`, `RecipeStart = 1`, + `RecipeEnd = 2`, `RecipeInterrupted = 3`) and `IsLocked`, as trailing parameters with the defaults + `MarkerKind.User` and `false`, so a marker the viewer adds is what the database defaults store. +- One new write, `SetLockedAsync(StoredMarker marker, bool isLocked)`, runs the same path as rename + through store statement, `IMarkerStore`, `IMarkerChannel` and `MarkerSync`; `ChartMarkers` exposes it + as `ToggleLockAsync(StoredMarker seen)`, with hold and revert. No other write changes: add still + inserts `(t, label)`. +- The lock is a press region, not a new action: `PressRegionAt` returns `ChartPressRegion.LockedMarker` + for a locked marker, and the router maps it to `PanOrPickPen` for any click count. The hover cursor + follows from the same route. The menu still finds the marker, because `MarkerAt` is unchanged. +- Hiding is a filter inside `MarkerSet`, which Core owns together with `MarkerKind`. The set keeps every + marker in `All` and a cached `ShownMarkers` array of the shown ones, rebuilt only when the set changes or + the flag flips; `NearestWithin` searches the cached array. `ShownMarkers` is read every frame, every pointer + move and every drag move (`TrendChartView.axaml.cs:392`, `TrendChartView.axaml.cs:575`), so it never + filters per call. The lines, the readings, the minimap ticks and the hit test follow `ShownMarkers` without + a filter of their own. The id lookups (`ChartMarkers.FindMarker`, `ChartMarkers.cs:239-242`, behind + `ReplaceHeld` and `RemoveMarker`), `NextNumber` and the `Contains` in `AddAtAsync` read `All`, so a + revert or a `MarkerGone` on a marker hidden after its write began still lands. +- The flag lives in `MarkerSet.ShowsRecipeMarkers`; `ChartMarkers` exposes it read-only and flips it + through `ToggleRecipeMarkers`, which raises `Changed`. `MainWindowViewModel.ToggleRecipeMarkersCommand` + calls it, and `ShowsRecipeMarkers`, the property the menu item reads, is an + `ObservableAsPropertyHelper` over `Markers.Changed`: `ChartMarkers` raises no property notification, so + the view model mirrors it as an adapter. +- `MarkerPalette` gains the recipe line colour from a new `AppRecipeMarkerLineBrush` key in both theme + variants. `ChartMarkerLines.Sync` sets the colour from the kind and the pattern from the lock on every + line it touches, since both can change between reads. + +## Technical Details + +- Statement: `SELECT id, t, label, kind, locked FROM semiplot_markers ORDER BY t, id`; + `StoredMarkerColumn` gains `Kind = 3` and `Locked = 4`; `kind` reads with `GetInt16` and casts to + `MarkerKind`. The column's `CHECK (kind BETWEEN 0 AND 3)` bounds it; a value outside the enum is + `ShapeUnexpected`, not a crash. ASSUMPTION: the mapper has no existing path for an out-of-range + value; the implementer adds the guard in `ReadAsync` and maps it there. +- Lock statement: `UPDATE semiplot_markers SET locked = @locked WHERE id = @id`, through + `UpdateOneRowAsync`, so no touched row is `MarkerGone` naming the marker. +- `MarkerSet` keeps one binary search, over the shown array. +- `ChartMarkers.NextNumber` counts only `MarkerKind.User` markers of `All`. +- `ChartMarkerLines.ApplyPalette` recolours every line by its marker's kind, so it keeps the kind of each + line it drew (`ChartMarkerLines.cs:89-99` iterates the lines alone today). +- Menu: one `MenuItem` named `MarkerMenuLock`; `OpenChartMenu` sets its header to `Lock` or `Unlock` + from `_menuMarker.IsLocked` before showing the flyout. Two resource keys, `MarkerMenuLock` and + `MarkerMenuUnlock`, in `Resources.resx` and `Resources.ru.resx` ("Закрепить", "Открепить"). The + `View` item is `MenuViewRecipeMarkers`, "Recipe markers" / "Метки рецептов", ticked by default. +- The flag is per window and not stored; a new window starts with recipe markers shown. + +## What Goes Where + +- **Implementation Steps**: code, tests and docs in this repository. +- **Post-Completion**: the stand check and the SCADA script, which live outside it. + +## Implementation Steps + +### Task 1: Read kind and lock from the store + +**Files:** +- Modify: `SemiPlot/SemiPlot.Core/Data/IMarkerStore.cs` +- Modify: `SemiPlot/SemiPlot.DataSource.Postgres/ArchiveStatements.cs` +- Modify: `SemiPlot/SemiPlot.DataSource.Postgres/PostgresMarkerStore.cs` +- Modify: `SemiPlot/SemiPlot.Tests.Integration/MarkerStoreTests.cs` +- Modify: `SemiPlot/SemiPlot.Tests.Unit/UI/Markers/FakeMarkerWriter.cs` + +- [x] confirm the test image carries the columns: run the marker store tests once against `ghcr.io/semiteq/semibase:latest` after `docker pull`, and stop with ⚠️ if `kind` is missing (⚠️ Docker daemon down and starting it was denied: confirmed instead from SemiBase v0.7.0 `sql/semiplot_markers.sql`, which declares `kind smallint NOT NULL DEFAULT 0 CHECK (kind BETWEEN 0 AND 3)` and `locked boolean NOT NULL DEFAULT false`; the container tests ran later with Docker up against v0.7.0 and passed, MarkerStoreTests 25/25) +- [x] add `MarkerKind` beside `StoredMarker` and the two trailing parameters to the record +- [x] select `kind` and `locked` in `StoredMarkers`, extend `StoredMarkerColumn`, map both in `ReadAsync` +- [x] add `SetLockedAsync` to `IMarkerStore` and `PostgresMarkerStore` with the `SetMarkerLocked` statement +- [x] add the lock write to `FakeMarkerWriter`, which `FakeMarkerStore` implements `IMarkerStore` through (`FakeMarkerStore.cs:11`), so the unit project still builds +- [x] write integration tests: a raw row with `kind = 1, locked = true` reads back with both; an added marker reads `User`, unlocked +- [x] write integration tests: `SetLockedAsync` writes that row only; add a `Lock` arm to the deleted-marker theory (`MarkerStoreTests.cs:94`) and the dropped-table theory (`MarkerStoreTests.cs:196`) +- [x] run `dotnet test SemiPlot.slnx` - must pass before task 2 (unit project passed, 2405 tests; the integration project did not run then for lack of a Docker daemon; the container tests ran and passed in task 7, 210/210) + +### Task 2: Carry the lock write through the channel + +**Files:** +- Modify: `SemiPlot/SemiPlot.UI/Chart/IMarkerChannel.cs` +- Modify: `SemiPlot/SemiPlot.UI/Markers/MarkerSync.cs` +- Modify: `SemiPlot/SemiPlot.UI/Chart/ChartMarkers.cs` +- Modify: `SemiPlot/SemiPlot.Tests.Unit/UI/Markers/MarkerSyncTests.cs` +- Modify: `SemiPlot/SemiPlot.Tests.Unit/UI/Chart/ChartMarkersTests.cs` + +- [x] add `SetLockedAsync` to `IMarkerChannel` and route it through `MarkerSync`'s queue like rename +- [x] ➕ add the lock write to `SemiPlot.Tests.Integration/Journeys/NoMarkers.cs`, which implements `IMarkerChannel`, so the integration project still builds +- [x] add `ChartMarkers.ToggleLockAsync`: hold, show the new state, revert on failure, remove on `MarkerGone` +- [x] make `NextNumber` count only `MarkerKind.User` markers +- [x] write tests: `MarkerSync` queues the lock write and reads after it +- [x] write tests: `ChartMarkers` shows the lock at once, reverts it on failure, and numbers past a user `#3` but not a recipe `#9` +- [x] run `dotnet test SemiPlot/SemiPlot.Tests.Unit/SemiPlot.Tests.Unit.csproj` - must pass before task 3 + +### Task 3: Make a locked marker ignore drag and double click + +**Files:** +- Modify: `SemiPlot/SemiPlot.UI/Chart/ChartPressRouter.cs` +- Modify: `SemiPlot/SemiPlot.UI/Chart/TrendChartView.axaml.cs` +- Modify: `SemiPlot/SemiPlot.Tests.Unit/UI/Chart/ChartPressRouterTests.cs` +- Modify: `SemiPlot/SemiPlot.Tests.Unit/UI/Chart/ChartMarkerViewTests.cs` + +- [x] add `ChartPressRegion.LockedMarker`, routed to `PanOrPickPen` for every click count after the axis region, Ctrl, the time axis and the tool +- [x] return it from `PressRegionAt` and use it in `Hover`, so a locked marker shows the hand cursor +- [x] write router tests: one and two clicks on a locked marker; Ctrl and delta mode keep their branches +- [x] write view tests: a double click on a locked marker leaves it stored; a drag on it pans; a hover on it shows the hand cursor and still snaps the cursor to its moment +- [x] run `dotnet test SemiPlot/SemiPlot.Tests.Unit/SemiPlot.Tests.Unit.csproj` - must pass before task 4 + +### Task 4: Add Lock and Unlock to the marker menu + +**Files:** +- Modify: `SemiPlot/SemiPlot.UI/Chart/TrendChartView.axaml` +- Modify: `SemiPlot/SemiPlot.UI/Chart/TrendChartView.Markers.cs` +- Modify: `SemiPlot/SemiPlot.UI/Localization/Resources.resx` +- Modify: `SemiPlot/SemiPlot.UI/Localization/Resources.ru.resx` +- Modify: `SemiPlot/SemiPlot.Tests.Unit/UI/Chart/ChartMarkerViewTests.cs` + +- [x] add `MarkerMenuLock` to `MarkerMenuFlyout` with a `Click` handler calling `ToggleLockAsync(marker)` +- [x] set its header from `_menuMarker.IsLocked` in `OpenChartMenu` +- [x] add `MarkerMenuLock` and `MarkerMenuUnlock` in both resource files +- [x] write view tests: the menu over an unlocked marker reads `Lock` and locks it; over a locked one reads `Unlock` and unlocks it +- [x] run `dotnet test SemiPlot/SemiPlot.Tests.Unit/SemiPlot.Tests.Unit.csproj` - must pass before task 5 + +### Task 5: Draw kind and lock on the line + +**Files:** +- Modify: `SemiPlot/SemiPlot.UI/Styles/Palette.axaml` +- Modify: `SemiPlot/SemiPlot.UI/Chart/MarkerPalette.cs` +- Modify: `SemiPlot/SemiPlot.UI/Chart/ChartPalette.cs` +- Modify: `SemiPlot/SemiPlot.UI/Chart/ChartMarkerLines.cs` +- Modify: `SemiPlot/SemiPlot.Tests.Unit/UI/Chart/ChartMarkerViewTests.cs` + +- [x] add `AppRecipeMarkerLineBrush` to both theme dictionaries and `RecipeLine` to `MarkerPalette` +- [x] in `Sync`, set each line's colour from its kind and its pattern from its lock; `ApplyPalette` recolours by kind +- [x] write tests: a recipe line takes the recipe colour, a user line the marker colour; a locked line is solid, an unlocked one dashed; a lock change between two syncs changes the pattern +- [x] write tests: a theme change keeps the recipe colour on a recipe line +- [x] run `dotnet test SemiPlot/SemiPlot.Tests.Unit/SemiPlot.Tests.Unit.csproj` - must pass before task 6 + +### Task 6: Hide recipe markers per window + +**Files:** +- Modify: `SemiPlot/SemiPlot.Core/Trends/MarkerSet.cs` +- Modify: `SemiPlot/SemiPlot.UI/Chart/ChartMarkers.cs` +- Modify: `SemiPlot/SemiPlot.UI/MainWindow/MainWindowViewModel.cs` +- Modify: `SemiPlot/SemiPlot.UI/MainWindow/AppMenuBar.axaml` +- Modify: `SemiPlot/SemiPlot.UI/Localization/Resources.resx` +- Modify: `SemiPlot/SemiPlot.UI/Localization/Resources.ru.resx` +- Modify: `SemiPlot/SemiPlot.Tests.Unit/Core/Trends/MarkerSetTests.cs` +- Modify: `SemiPlot/SemiPlot.Tests.Unit/UI/Chart/ChartMarkersTests.cs` +- Modify: `SemiPlot/SemiPlot.Tests.Unit/UI/MainWindow/AppMenuBarTests.cs` +- Modify: `SemiPlot/SemiPlot.Tests.Unit/UI/MainWindow/MainWindowViewModelTests.cs` + +- [x] give `MarkerSet` `All`, the cached `ShownMarkers` and the flag; `NearestWithin` searches the cached array +- [x] give `ChartMarkers` `ShowsRecipeMarkers` and `ToggleRecipeMarkers`, raising `Changed`; point `FindMarker`, `NextNumber` and `AddAtAsync`'s `Contains` at `All` +- [x] add `ToggleRecipeMarkersCommand` and the `ShowsRecipeMarkers` OAPH to `MainWindowViewModel`, and the `ViewRecipeMarkers` item after `ViewMinimap` +- [x] write tests: hidden recipe markers leave `ShownMarkers` and `NearestWithin`, stay in `All`, raise one `Changed`, and come back on show; `ShownMarkers` returns the same array between two changes +- [x] write tests: a rename of a recipe marker that fails after the marker was hidden restores the label in `All` +- [x] write tests: the menu item starts ticked and its command flips the flag and the tick; add a `ViewRecipeMarkers` arm to the switch at `AppMenuBarTests.cs:103-108` +- [x] run `dotnet test SemiPlot/SemiPlot.Tests.Unit/SemiPlot.Tests.Unit.csproj` - must pass before task 7 + +### Task 7: Verify acceptance criteria + +- [x] verify every Overview item is implemented +- [x] run the three Acceptance Evidence commands (ChartPressRouterTests 43/43, ChartMarkersTests 30/30, MarkerStoreTests 25/25; the manual stand check, item 4, is not automatable and stays in Post-Completion) +- [x] run the full suite: `dotnet test SemiPlot.slnx` (unit 2437/2437, integration 210/210 with Docker up) +- [x] run `dotnet format SemiPlot.slnx --verify-no-changes` and `dotnet terse` over the touched files (both exit 0, 27 files) + +### Task 8: [Final] Update documentation + +- [x] `docs/architecture/data-integration.md#the-marker-store`: the two columns, `MarkerKind`, the lock statement, five writes +- [x] `docs/architecture/postgres-instance.md`: the minimum becomes SemiBase v0.7.0 with the `ShapeUnexpected` failure (lines 32-35); the table row at line 98 names `kind` and `locked`; `scada_writer` holds `INSERT` on `semiplot_markers` and nothing else on it +- [x] `AGENTS.md`: the left-button gesture paragraph names the locked-marker region, and "four writes" becomes five wherever the markers are described +- [x] `docs/architecture/trend-interaction.md#the-time-markers`: the lock, the recipe colour, the solid line, the hiding +- [x] `docs/architecture/overview.md#the-live-markers`, `ui-text.md#the-marker-menu-and-label-editors-text`, `ui-theme.md`: the five writes, the new strings, the new palette key +- ⚠️ move this plan to `docs/plans/completed/` (left for the delivery step, not done here) + +## Post-Completion + +**Manual verification**: +- the stand check in Acceptance Evidence, item 4, in both themes. + +**External system updates**: +- the SCADA project script issues `INSERT INTO semiplot_markers (t, label, kind, locked) VALUES + (clock_timestamp(), NULLIF(left('', 80), ''), , true)` as `scada_writer` + (Semiteq/SemiBase#21). + +**Remaining work for #160**: the second PR, picking the export range by markers and proposing the CSV +file name from the start marker's label. + +**Executed by exec:** +- branch: recipe-markers-on-chart + +## Verify it yourself + +Automated, each from the repository root on `recipe-markers-on-chart`. The tests do not exist at +`9370cec` (the plan commit), where `StoredMarker` has no `Kind` or `IsLocked`, so there is no red run to +compare; each passes at `fb69271`. + +1. Locked-marker routing: `dotnet test SemiPlot/SemiPlot.Tests.Unit/SemiPlot.Tests.Unit.csproj --filter "FullyQualifiedName~ChartPressRouterTests"`. +2. Lock write, hiding, numbering, the lock menu, the line colour and pattern: + `dotnet test SemiPlot/SemiPlot.Tests.Unit/SemiPlot.Tests.Unit.csproj --filter "FullyQualifiedName~ChartMarkersTests|FullyQualifiedName~MarkerSetTests|FullyQualifiedName~ChartMarkerViewTests|FullyQualifiedName~MinimapViewModelTests"`. +3. The store against SemiBase v0.7.0, Docker up: + `dotnet test SemiPlot/SemiPlot.Tests.Integration/SemiPlot.Tests.Integration.csproj --filter "FullyQualifiedName~MarkerStoreTests"` (26 tests). + +Manual, on the stand: `dotnet run --project SemiPlot/SemiPlot.AppHost`, then as `postgres` in the +stand's database run +`INSERT INTO semiplot_markers (t, label, kind, locked) VALUES (now(), 'Etch.csv', 1, true);` and wait up to +5 s for the read. + +1. The marker draws as a solid purple line (`#834DF0` light, `#A571E6` dark) labelled `Etch.csv`; a + marker added by double click draws grey and dashed. +2. A press and drag on the purple line pans the chart and leaves the marker in place; a double click on + it does nothing, and the pointer shows the hand, not the resize cursor. +3. Right click on it: the menu reads `Unlock` (`Открепить`). After it the line turns dashed, still + purple, and now drags; the menu then reads `Lock`. +4. `Rename` and `Delete` from the menu work on a locked marker. +5. `View` -> `Recipe markers` unticked removes the purple line and its minimap tick and keeps the grey + one; ticked brings both back. A second window keeps its own tick state. +6. Switch the theme: the purple line keeps the recipe colour of the new theme. diff --git a/readme.md b/readme.md index 80ceb37..a581ce1 100644 --- a/readme.md +++ b/readme.md @@ -34,14 +34,17 @@ SemiPlot — программа просмотра трендов техноло давления. Флажок «Логарифмическая шкала» в панели шкалы переключает её в текущем окне. - Курсор показывает значения всех видимых перьев в выбранной точке. В режиме «Приращение» два щелчка ставят два курсора, а рядом с кнопкой видны Δt и Δy активного пера между ними. -- Метки времени: двойной щелчок по графику ставит вертикальную линию с порядковым номером вида `#1` и временем, то - же делает пункт «Добавить метку здесь» в меню правой кнопки. Метку можно перетащить мышью, двойной щелчок по метке - удаляет её, а щелчок правой кнопкой по метке открывает меню «Переименовать» и «Удалить»; подпись - необязательна, до 80 символов. Метки хранятся - в архиве и видны во всех открытых окнах и после перезапуска, а на полосе обзора архива внизу каждая - метка отмечена штрихом. На каждой метке точка и число показывают - значение активного пера в её момент; при наведении на метку курсор показывает значения всех видимых - перьев. +- Метки времени: двойной щелчок по графику ставит вертикальную линию с порядковым номером вида `#1` и + временем, то же делает пункт «Добавить метку здесь» в меню правой кнопки. Метку можно перетащить мышью, + двойной щелчок по метке удаляет её, а щелчок правой кнопкой по метке открывает меню «Переименовать», + «Закрепить» и «Удалить»; подпись необязательна, до 80 символов. Метки хранятся в архиве и видны во всех + открытых окнах и после перезапуска, а на полосе обзора архива внизу каждая метка отмечена штрихом. На + каждой метке точка и число показывают значение активного пера в её момент; при наведении на метку курсор + показывает значения всех видимых перьев. +- Метки рецептов ставит SCADA: начало, конец и прерывание рецепта с именем его файла. Они рисуются своим + цветом и приходят закреплёнными. Закреплённая метка рисуется сплошной линией, её нельзя перетащить или + удалить двойным щелчком; пункт «Открепить» в её меню снимает закрепление, а «Переименовать» и «Удалить» + работают и для неё. Пункт «Вид → Метки рецептов» скрывает и показывает метки рецептов в текущем окне. - Изменение масштаба и сдвиг по времени, переход к текущему времени, режим «Следовать за текущим временем». - Щелчок по шкале времени открывает панель интервала: начало и конец задаются датой и временем, ширина @@ -93,7 +96,8 @@ SemiPlot — программа просмотра трендов техноло | Источник данных | Архив Simple-Scada 2 в PostgreSQL, установленный [SemiBase](https://github.com/Semiteq/SemiBase) | | Конфигурация | Каталог с разделами `app/` и `connection/`; образец — `ConfigFiles/` | -Метки времени требуют SemiBase 0.6.0 или новее: эта версия создаёт таблицу `semiplot_markers`. +Метки времени требуют SemiBase 0.7.0 или новее: версия 0.6.0 создаёт таблицу `semiplot_markers`, а 0.7.0 +добавляет в неё столбцы `kind` и `locked`. Начиная с версии 2.7.5.0 Simple-Scada не пишет суточный слой. Самый грубый слой SemiPlot — часовой, поэтому программа одинаково работает с архивами любой версии.