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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 17 additions & 1 deletion SemiPlot/SemiPlot.Core/Data/IMarkerStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,24 @@ public interface IMarkerStore

Task<Result> RenameAsync(StoredMarker marker, string? label);

Task<Result> SetLockedAsync(StoredMarker marker, bool isLocked);

Task<Result> DeleteAsync(StoredMarker marker);
}

/// <summary>One <c>semiplot_markers</c> row as stored; a null label is a stored <c>NULL</c>.</summary>
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);

/// <summary>The <c>semiplot_markers.kind</c> values; the SCADA writes the recipe kinds.</summary>
public enum MarkerKind
{
User = 0,
RecipeStart = 1,
RecipeEnd = 2,
RecipeInterrupted = 3
}
113 changes: 77 additions & 36 deletions SemiPlot/SemiPlot.Core/Trends/MarkerSet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,38 @@

namespace SemiPlot.Core.Trends;

/// <summary>The markers a window shows, sorted by time then id; a held marker keeps its local state.</summary>
/// <summary>
/// The markers a window holds, sorted by time then id, and the ones it shows; a held marker keeps its local state.
/// </summary>
public sealed class MarkerSet
{
private static readonly Comparer<StoredMarker> _byTimeThenId = Comparer<StoredMarker>.Create(CompareByTimeThenId);

private readonly Dictionary<long, int> _holdCounts = [];

private StoredMarker[] _markers = [];
private StoredMarker[] _all = [];
private StoredMarker[] _shownMarkers = [];

/// <summary>A snapshot: every change replaces the array, so a reader never sees it mutate.</summary>
public IReadOnlyList<StoredMarker> Markers => _markers;
/// <summary>Every marker, shown or hidden; a snapshot like <see cref="ShownMarkers"/>.</summary>
public IReadOnlyList<StoredMarker> All => _all;

/// <summary>
/// The shown markers as a snapshot: every change replaces the array, so a reader never sees it mutate.
/// </summary>
public IReadOnlyList<StoredMarker> ShownMarkers => _shownMarkers;

public bool ShowsRecipeMarkers { get; private set; } = true;

public void ToggleRecipeMarkers()
{
ShowsRecipeMarkers = !ShowsRecipeMarkers;
RebuildShown();
}

public bool Apply(IReadOnlyList<StoredMarker> read)
{
var heldLocally = new Dictionary<long, StoredMarker>();
foreach (var marker in _markers)
foreach (var marker in _all)
{
if (_holdCounts.ContainsKey(marker.Id))
{
Expand All @@ -41,12 +57,13 @@ public bool Apply(IReadOnlyList<StoredMarker> 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;
}
Expand Down Expand Up @@ -76,48 +93,32 @@ public bool Release(long id)
return true;
}

/// <summary>An upsert by id in one copy pass; it runs on every pointer move of a marker drag.</summary>
/// <summary>An upsert by id, one copy pass per list the marker is in; it runs on every move of a drag.</summary>
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();
}

/// <summary>The marker closest to <paramref name="time"/> within the tolerance; the lower id wins a tie.</summary>
public StoredMarker? NearestWithin(DateTime time, TimeSpan tolerance)
{
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--;
}
Expand All @@ -126,12 +127,12 @@ public void Remove(long id)
var nearestDistance = TimeSpan.MaxValue;
foreach (var index in (ReadOnlySpan<int>)[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)
{
Expand All @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,18 @@ public ArchiveError RowGone(string subject)
return Fault(ArchiveFault.RowGone, subject);
}

/// <summary>A move or rename that touched no row: the marker it names is gone.</summary>
/// <summary>A move, rename or lock that touched no row: the marker it names is gone.</summary>
public ArchiveError MarkerGone(string subject)
{
return Fault(ArchiveFault.MarkerGone, subject);
}

/// <summary>A value read back that this code cannot represent; <paramref name="detail"/> names it.</summary>
public ArchiveError ShapeUnexpected(string detail)
{
return Fault(ArchiveFault.ShapeUnexpected, detail);
}

private static ArchiveFault? WriteFaultOf(string sqlState)
{
return sqlState switch
Expand Down
6 changes: 5 additions & 1 deletion SemiPlot/SemiPlot.DataSource.Postgres/ArchiveStatements.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/// <summary>Every statement this project issues; parameters are bound, never interpolated.</summary>
Expand Down Expand Up @@ -140,14 +142,16 @@ 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;";

public const string MoveMarker = "UPDATE semiplot_markers SET t = @t WHERE id = @id;";

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;";

/// <summary>The name PostgreSQL gives the membership's foreign key to the pen SemiBase declares unnamed.</summary>
Expand Down
27 changes: 24 additions & 3 deletions SemiPlot/SemiPlot.DataSource.Postgres/PostgresMarkerStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
namespace SemiPlot.DataSource.Postgres;

/// <summary>
/// Reads and writes <c>semiplot_markers</c> over the provider's <see cref="NpgsqlDataSource"/> and role. A move or
/// rename touching no row is <see cref="ArchiveFault.MarkerGone"/>; a delete touching none succeeds.
/// Reads and writes <c>semiplot_markers</c> over the provider's <see cref="NpgsqlDataSource"/> and role. A move,
/// rename or lock touching no row is <see cref="ArchiveFault.MarkerGone"/>; a delete touching none succeeds.
/// </summary>
public sealed class PostgresMarkerStore : IMarkerStore
{
Expand Down Expand Up @@ -46,10 +46,20 @@ public async Task<Result<IReadOnlyList<StoredMarker>>> ReadAsync(CancellationTok

while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
{
var kind = (MarkerKind)reader.GetInt16(StoredMarkerColumn.Kind);

if (!Enum.IsDefined(kind))
{
return Result.Fail<IReadOnlyList<StoredMarker>>(_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<DateTime>(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<IReadOnlyList<StoredMarker>>(markers);
Expand Down Expand Up @@ -106,6 +116,17 @@ public Task<Result> RenameAsync(StoredMarker marker, string? label)
goneSubject: SubjectOf(marker.TimeUtc, marker.Label));
}

public Task<Result> 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);
}

/// <summary>Idempotent: deleting a marker another window already removed succeeds.</summary>
public async Task<Result> DeleteAsync(StoredMarker marker)
{
Expand Down
5 changes: 5 additions & 0 deletions SemiPlot/SemiPlot.Tests.Integration/Journeys/NoMarkers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ public Task<Result> RenameAsync(StoredMarker marker, string? label)
throw new NotSupportedException();
}

public Task<Result> SetLockedAsync(StoredMarker marker, bool isLocked)
{
throw new NotSupportedException();
}

public Task<Result> DeleteAsync(StoredMarker marker)
{
throw new NotSupportedException();
Expand Down
Loading
Loading