808 lines
32 KiB
C#
808 lines
32 KiB
C#
using System.Collections.ObjectModel;
|
||
using System.Windows;
|
||
using System.Windows.Media;
|
||
using CommunityToolkit.Mvvm.ComponentModel;
|
||
using CommunityToolkit.Mvvm.Input;
|
||
using TuneBoss.Core.BLE;
|
||
using TuneBoss.Core.Models;
|
||
|
||
namespace TuneBossPC.ViewModels.Tables;
|
||
|
||
// ────────────────────────────────────────────────────────────────────────────
|
||
// Nav-tree entry / group (1D-specific, parallel to TableEntry/GroupViewModel).
|
||
// Kept separate so the shared 2D nav types stay untouched.
|
||
// ────────────────────────────────────────────────────────────────────────────
|
||
public partial class OneDimEntryViewModel : ObservableObject
|
||
{
|
||
public int Slot { get; init; }
|
||
public string Label { get; init; } = string.Empty;
|
||
public OneDimGroup Group { get; init; }
|
||
public ushort Address { get; init; }
|
||
public byte ReadLength { get; init; }
|
||
public bool IsAvailable { get; init; } = true;
|
||
|
||
/// <summary>Display-only unit labels (default from registry, editable in the UI).</summary>
|
||
[ObservableProperty] private string _axisUnit = string.Empty;
|
||
[ObservableProperty] private string _valueUnit = string.Empty;
|
||
|
||
[ObservableProperty] private bool _isSelected;
|
||
[ObservableProperty] private bool _isLoaded;
|
||
[ObservableProperty] private bool _isLoading;
|
||
|
||
/// <summary>Loaded model (null until first read).</summary>
|
||
public OneDimTable? Table { get; set; }
|
||
}
|
||
|
||
public partial class OneDimGroupViewModel : ObservableObject
|
||
{
|
||
public string Label { get; init; } = string.Empty;
|
||
[ObservableProperty] private bool _isExpanded = true;
|
||
[ObservableProperty] private bool _isSelected;
|
||
public List<OneDimEntryViewModel> Entries { get; } = new();
|
||
}
|
||
|
||
// ────────────────────────────────────────────────────────────────────────────
|
||
// 1D Tables page view-model
|
||
// ────────────────────────────────────────────────────────────────────────────
|
||
public partial class OneDimTablesViewModel : ObservableObject, IDisposable
|
||
{
|
||
private const int N = OneDimTable.PointCount; // 8
|
||
|
||
private readonly IBleService _ble;
|
||
private readonly TuneBossPC.Services.ISessionService _session;
|
||
|
||
private static readonly Brush CellBg = MakeFrozen(0x22, 0x26, 0x2B);
|
||
|
||
// ── Nav tree ──────────────────────────────────────────────────────────────
|
||
public ObservableCollection<OneDimGroupViewModel> Groups { get; } = new();
|
||
|
||
[ObservableProperty]
|
||
[NotifyPropertyChangedFor(nameof(HasSelectedTable))]
|
||
private OneDimEntryViewModel? _selectedEntry;
|
||
|
||
public bool HasSelectedTable => SelectedEntry != null;
|
||
|
||
// ── Grid (single value row + editable axis breakpoints) ───────────────────
|
||
public ObservableCollection<TuningTableCellViewModel> Cells { get; } = new();
|
||
[ObservableProperty] private ObservableCollection<AxisHeaderViewModel> _axisHeaders = new();
|
||
|
||
[ObservableProperty] private TuningTableCellViewModel? _selectedCell;
|
||
[ObservableProperty] private TuningTableCellViewModel? _editingCell;
|
||
[ObservableProperty] private AxisHeaderViewModel? _editingHeader;
|
||
|
||
[ObservableProperty] private string _setValueText = string.Empty;
|
||
[ObservableProperty] private string _statusMessage = string.Empty;
|
||
[ObservableProperty] private string _metaSummary = string.Empty;
|
||
[ObservableProperty] private bool _isReading;
|
||
[ObservableProperty] private bool _isWriting;
|
||
/// <summary>Bumped on each confirmed flash — drives the FLASH button's green blink.</summary>
|
||
[ObservableProperty] private int _flashSuccessCount;
|
||
|
||
/// <summary>Raised when the curve needs redrawing (after populate or any value/axis edit).</summary>
|
||
public event Action? CurveInvalidated;
|
||
|
||
private readonly DiagnosticsStripViewModel _strip;
|
||
|
||
public OneDimTablesViewModel(IBleService ble, TuneBossPC.Services.ISessionService session,
|
||
DiagnosticsStripViewModel strip)
|
||
{
|
||
_ble = ble;
|
||
_session = session;
|
||
_strip = strip;
|
||
_session.SessionChanged += () => OnPropertyChanged(nameof(CanComms));
|
||
|
||
for (int c = 0; c < N; c++)
|
||
Cells.Add(new TuningTableCellViewModel { Row = 0, Col = c });
|
||
|
||
RebuildNavTree();
|
||
}
|
||
|
||
/// <summary>
|
||
/// When true, the Y (value) column is shown raw × value-multiplier; when false
|
||
/// (default) the raw stored values are shown as-is. Independent of the X toggle.
|
||
/// </summary>
|
||
[ObservableProperty] private bool _showYMultiplied;
|
||
|
||
/// <summary>
|
||
/// When true, the X (axis/breakpoint) row is shown raw × raw-multiplier; when
|
||
/// false (default) the raw stored breakpoints are shown as-is. Independent of Y.
|
||
/// </summary>
|
||
[ObservableProperty] private bool _showXMultiplied;
|
||
|
||
partial void OnShowYMultipliedChanged(bool value)
|
||
{
|
||
if (SelectedEntry?.Table != null) PopulateGrid(SelectedEntry.Table);
|
||
CurveInvalidated?.Invoke();
|
||
}
|
||
|
||
partial void OnShowXMultipliedChanged(bool value)
|
||
{
|
||
if (SelectedEntry?.Table != null) PopulateGrid(SelectedEntry.Table);
|
||
CurveInvalidated?.Invoke();
|
||
}
|
||
|
||
/// <summary>Effective value multiplier honouring the Y toggle (1 = unscaled).</summary>
|
||
private int DisplayConvMult => ShowYMultiplied ? EffConvMult : 1;
|
||
|
||
/// <summary>Value multiplier the curve axis labels should use (honours the Y toggle).</summary>
|
||
public int DisplayCurveMult => DisplayConvMult;
|
||
|
||
/// <summary>X-axis (breakpoint) multiplier — honours the independent X toggle
|
||
/// (1 = unscaled when unchecked).</summary>
|
||
public int AxisDisplayMult => ShowXMultiplied ? EffRawMult : 1;
|
||
|
||
// ── Metadata bytes [16..23] of the selected 1D table (read-only display) ──────
|
||
// Shown to the right of the curve as a label/value pair list.
|
||
/// <summary>
|
||
/// One row in the metadata panel. Read-only display by default; when the panel is
|
||
/// unlocked (5 clicks on the header) the numeric rows expose an editable text box
|
||
/// whose committed value writes straight back to the OneDimTable model, so the
|
||
/// existing 1D WRITE (which serialises via ToWirePayload) sends the new metadata.
|
||
/// </summary>
|
||
public sealed partial class MetaRow : ObservableObject
|
||
{
|
||
private readonly System.Func<string>? _read;
|
||
private readonly System.Action<string>? _apply;
|
||
|
||
public string Label { get; }
|
||
public bool IsEditable => _apply != null;
|
||
|
||
[ObservableProperty] private string _value = string.Empty;
|
||
[ObservableProperty] private string _editText = string.Empty;
|
||
|
||
// Display-only row (e.g. Address).
|
||
public MetaRow(string label, string value)
|
||
{
|
||
Label = label;
|
||
Value = value;
|
||
}
|
||
|
||
// Editable row: read() gives the display value, apply(text) parses + writes the model.
|
||
public MetaRow(string label, System.Func<string> read, System.Action<string> apply)
|
||
{
|
||
Label = label;
|
||
_read = read;
|
||
_apply = apply;
|
||
Value = read();
|
||
EditText = Value;
|
||
}
|
||
|
||
/// <summary>Parse the edit box and push into the model; refresh display. Returns
|
||
/// false (and reverts the box) if the text isn't a valid byte value.</summary>
|
||
public bool Commit()
|
||
{
|
||
if (_apply == null || _read == null) return true;
|
||
try { _apply(EditText.Trim()); }
|
||
catch { EditText = Value; return false; }
|
||
Value = _read();
|
||
EditText = Value;
|
||
return true;
|
||
}
|
||
|
||
public void Revert()
|
||
{
|
||
if (_read != null) { Value = _read(); EditText = Value; }
|
||
}
|
||
}
|
||
|
||
/// <summary>True once the hidden 5-click gesture on the metadata header unlocks editing.</summary>
|
||
[ObservableProperty] private bool _metadataUnlocked;
|
||
|
||
private int _metaClickCount;
|
||
private System.DateTime _lastMetaClickUtc;
|
||
|
||
/// <summary>
|
||
/// Hidden gesture: five clicks on the metadata header (within ~2s of each other)
|
||
/// unlocks the metadata fields for editing. A sixth click re-locks them.
|
||
/// </summary>
|
||
public void RegisterMetadataHeaderClick()
|
||
{
|
||
var now = System.DateTime.UtcNow;
|
||
if ((now - _lastMetaClickUtc).TotalSeconds > 2) _metaClickCount = 0;
|
||
_lastMetaClickUtc = now;
|
||
_metaClickCount++;
|
||
|
||
if (_metaClickCount >= 5)
|
||
{
|
||
_metaClickCount = 0;
|
||
MetadataUnlocked = !MetadataUnlocked;
|
||
StatusMessage = MetadataUnlocked
|
||
? "Metadata editing UNLOCKED — values will be written on WRITE."
|
||
: "Metadata editing locked.";
|
||
if (!MetadataUnlocked) OnPropertyChanged(nameof(MetaRows)); // discard uncommitted edits
|
||
}
|
||
}
|
||
|
||
public IReadOnlyList<MetaRow> MetaRows
|
||
{
|
||
get
|
||
{
|
||
var t = SelectedEntry?.Table;
|
||
if (t == null) return System.Array.Empty<MetaRow>();
|
||
|
||
// Editable numeric row: parse as int, range-check to a byte/sbyte, assign.
|
||
MetaRow ByteRow(string label, System.Func<int> get, System.Action<int> set,
|
||
int lo, int hi) =>
|
||
new(label, () => get().ToString(), text =>
|
||
{
|
||
if (!int.TryParse(text, out int v) || v < lo || v > hi)
|
||
throw new System.FormatException();
|
||
set(v);
|
||
});
|
||
|
||
return new MetaRow[]
|
||
{
|
||
new("Address", "0x" + SelectedEntry!.Address.ToString("X4")),
|
||
ByteRow("Max Raw", () => t.MaxRaw, v => t.MaxRaw = v, -128, 255),
|
||
ByteRow("Min Raw", () => t.MinRaw, v => t.MinRaw = v, -128, 255),
|
||
ByteRow("Raw Signed", () => t.RawSignedFlag, v => t.RawSignedFlag = (byte)v, 0, 255),
|
||
ByteRow("Conv Signed", () => t.ConvSignedFlag, v => t.ConvSignedFlag = (byte)v, 0, 255),
|
||
ByteRow("Raw Mult", () => t.RawMultiplier, v => t.RawMultiplier = (byte)v, 0, 255),
|
||
ByteRow("Conv Mult", () => t.ConvMultiplier, v => t.ConvMultiplier = (byte)v, 0, 255),
|
||
ByteRow("Raw Round", () => t.RawRounding, v => t.RawRounding = (byte)v, 0, 255),
|
||
ByteRow("Conv Offset", () => (int)t.ConvOffset, v => t.ConvOffset = (sbyte)v, -128, 127),
|
||
};
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Diagnostics stops at the protocol level on every write and nothing restarts it;
|
||
/// resume the live stream if the strip says it should be running.
|
||
/// </summary>
|
||
private async Task ResumeDiagnosticsIfLiveAsync()
|
||
{
|
||
try { if (_strip.IsRunning) await _ble.StartDiagnosticsAsync(); }
|
||
catch { /* best-effort */ }
|
||
}
|
||
|
||
// ── Nav tree ──────────────────────────────────────────────────────────────
|
||
|
||
/// <summary>True when hardware comms are allowed — a live session. Offline is view-only.</summary>
|
||
public bool CanComms => _session.IsActive;
|
||
|
||
/// <summary>Rebuilds the nav tree from the current session layout. Call after connect.</summary>
|
||
public void RebuildNavTree()
|
||
{
|
||
OnPropertyChanged(nameof(CanComms));
|
||
Groups.Clear();
|
||
if (!_session.HasLayout || _session.Layout is null) return;
|
||
|
||
var layout = _session.Layout;
|
||
|
||
var entries = new List<OneDimEntryViewModel>();
|
||
foreach (var def in OneDimTableRegistry.All)
|
||
{
|
||
int idx = def.Slot - 1;
|
||
if (idx < 0 || idx >= layout.OneDimTables.Length) continue;
|
||
|
||
var region = layout.OneDimTables[idx];
|
||
if (!region.IsAvailable) continue; // FW / generation gated out
|
||
|
||
entries.Add(new OneDimEntryViewModel
|
||
{
|
||
Slot = def.Slot,
|
||
Label = def.Label,
|
||
Group = def.Group,
|
||
Address = region.Address,
|
||
ReadLength = region.Length,
|
||
IsAvailable = true,
|
||
AxisUnit = def.AxisUnit,
|
||
ValueUnit = def.ValueUnit,
|
||
});
|
||
}
|
||
|
||
foreach (var g in OneDimTableRegistry.GroupOrder)
|
||
{
|
||
var groupEntries = entries.Where(e => e.Group == g).ToList();
|
||
if (groupEntries.Count == 0) continue;
|
||
|
||
var gvm = new OneDimGroupViewModel { Label = OneDimTableRegistry.DisplayName(g) };
|
||
gvm.Entries.AddRange(groupEntries);
|
||
Groups.Add(gvm);
|
||
}
|
||
|
||
// Two-panel nav: default to the first category
|
||
SelectGroup(Groups.FirstOrDefault());
|
||
}
|
||
|
||
// ── Category (main group) selection — drives the child entry panel ─────────
|
||
|
||
[ObservableProperty] private OneDimGroupViewModel? _selectedGroup;
|
||
|
||
[RelayCommand]
|
||
public void SelectGroup(OneDimGroupViewModel? group)
|
||
{
|
||
foreach (var g in Groups) g.IsSelected = false;
|
||
SelectedGroup = group;
|
||
if (group != null) group.IsSelected = true;
|
||
}
|
||
|
||
// ── Nav selection ─────────────────────────────────────────────────────────
|
||
|
||
[RelayCommand]
|
||
public void SelectEntry(OneDimEntryViewModel entry)
|
||
{
|
||
// Keep the category panel in sync when selection comes from code
|
||
// (e.g. first-loaded entry after connect).
|
||
var owner = Groups.FirstOrDefault(g => g.Entries.Contains(entry));
|
||
if (owner != null && owner != SelectedGroup) SelectGroup(owner);
|
||
|
||
// Preserve unwritten edits: harvest the OUTGOING table's on-screen values into
|
||
// its model before navigating away, so returning shows edits not the read data.
|
||
if (SelectedEntry is { IsLoaded: true, Table: not null } prev && prev != entry)
|
||
HarvestToModel(prev);
|
||
|
||
if (SelectedEntry != null) SelectedEntry.IsSelected = false;
|
||
ClearSelection();
|
||
|
||
SelectedEntry = entry;
|
||
entry.IsSelected = true;
|
||
|
||
if (entry.IsLoaded && entry.Table != null)
|
||
PopulateGrid(entry.Table);
|
||
else
|
||
{
|
||
ClearGrid();
|
||
OnPropertyChanged(nameof(MetaRows));
|
||
StatusMessage = "Click READ to load this table.";
|
||
}
|
||
}
|
||
|
||
// ── Read / Write / Flash ──────────────────────────────────────────────────
|
||
|
||
[RelayCommand]
|
||
public async Task ReadAsync()
|
||
{
|
||
var entry = SelectedEntry;
|
||
if (entry == null) return;
|
||
|
||
IsReading = true;
|
||
StatusMessage = "Reading…";
|
||
try
|
||
{
|
||
if (await ReadEntryAsync(entry) && entry.Table != null)
|
||
{
|
||
PopulateGrid(entry.Table);
|
||
StatusMessage = "Read OK";
|
||
}
|
||
}
|
||
catch (Exception ex) { StatusMessage = $"Error: {ex.Message}"; }
|
||
finally { IsReading = false; await ResumeDiagnosticsIfLiveAsync(); }
|
||
}
|
||
|
||
/// <summary>
|
||
/// Forces a fresh BLE re-read of one 1D table by slot (1-based), refreshing the cached
|
||
/// model and the on-screen grid if that table is selected. Used after TPS calibration,
|
||
/// which writes the Throttle Position table (slot 6) directly on the device — without
|
||
/// this, the 1D page would keep showing the copy cached at connect.
|
||
/// </summary>
|
||
public async Task RefreshSlotAsync(int slot)
|
||
{
|
||
var entry = Groups.SelectMany(g => g.Entries).FirstOrDefault(e => e.Slot == slot);
|
||
if (entry == null) return;
|
||
try
|
||
{
|
||
if (await ReadEntryAsync(entry) && entry.Table != null && SelectedEntry == entry)
|
||
Application.Current.Dispatcher.Invoke(() => PopulateGrid(entry.Table));
|
||
}
|
||
catch { /* best-effort refresh */ }
|
||
}
|
||
|
||
/// <summary>Reads all available 1D tables so they're cached for instant viewing. Mirrors the 2D init.</summary>
|
||
public async Task InitializeAllAsync(IProgress<string>? progress = null)
|
||
{
|
||
IsReading = true;
|
||
var all = Groups.SelectMany(g => g.Entries).ToList();
|
||
|
||
int done = 0;
|
||
foreach (var e in all)
|
||
{
|
||
progress?.Report($"Loading {e.Label}… ({++done}/{all.Count})");
|
||
try { await ReadEntryAsync(e); }
|
||
catch { /* keep loading the rest */ }
|
||
}
|
||
IsReading = false;
|
||
|
||
var first = all.FirstOrDefault(e => e.IsLoaded);
|
||
if (first != null)
|
||
Application.Current.Dispatcher.Invoke(() => SelectEntry(first));
|
||
}
|
||
|
||
private async Task<bool> ReadEntryAsync(OneDimEntryViewModel entry)
|
||
{
|
||
if (!entry.IsAvailable) return false;
|
||
|
||
entry.IsLoading = true;
|
||
try
|
||
{
|
||
var r = await _ble.ReadTable1DAsync(entry.Address, entry.ReadLength);
|
||
if (!r.Success) { StatusMessage = $"Read failed: {r.ErrorMessage}"; return false; }
|
||
if (r.Payload.Length < 4 + OneDimTable.WireLength)
|
||
{ StatusMessage = "Read returned a short payload."; return false; }
|
||
|
||
entry.Table = OneDimTable.FromWire(r.Payload, 4); // skip 51 43 17 00
|
||
entry.IsLoaded = true;
|
||
return true;
|
||
}
|
||
finally { entry.IsLoading = false; }
|
||
}
|
||
|
||
[RelayCommand]
|
||
public async Task WriteAsync()
|
||
{
|
||
var entry = SelectedEntry;
|
||
if (entry?.Table == null || !entry.IsLoaded) return;
|
||
|
||
IsWriting = true;
|
||
StatusMessage = "Writing…";
|
||
try
|
||
{
|
||
HarvestToModel(entry);
|
||
var w = await _ble.WriteTable1DAsync(entry.Address, entry.Table.ToWirePayload());
|
||
StatusMessage = w.Success
|
||
? "Write OK — click Flash to make permanent"
|
||
: $"Write failed: {w.ErrorMessage}";
|
||
}
|
||
catch (Exception ex) { StatusMessage = $"Error: {ex.Message}"; }
|
||
finally { IsWriting = false; await ResumeDiagnosticsIfLiveAsync(); }
|
||
}
|
||
|
||
[RelayCommand]
|
||
private async Task FlashAsync()
|
||
{
|
||
IsWriting = true;
|
||
StatusMessage = "Flashing to ECU…";
|
||
try
|
||
{
|
||
var fr = await _ble.FlashWriteAsync();
|
||
if (fr.Success) FlashSuccessCount++;
|
||
StatusMessage = fr.Success
|
||
? "Flash OK — settings saved to ECU"
|
||
: $"Flash failed: {fr.ErrorMessage}";
|
||
}
|
||
catch (Exception ex) { StatusMessage = $"Error: {ex.Message}"; }
|
||
finally { IsWriting = false; }
|
||
}
|
||
|
||
// ── Bulk adjust / set ─────────────────────────────────────────────────────
|
||
|
||
// Effective display multipliers (0/1 => unscaled). Display = raw × mult.
|
||
private int EffRawMult => Math.Max(1, (int)(SelectedEntry?.Table?.RawMultiplier ?? 1));
|
||
private int EffConvMult => Math.Max(1, (int)(SelectedEntry?.Table?.ConvMultiplier ?? 1));
|
||
|
||
[RelayCommand] public void AdjustPlus1() => AdjustSelected(+1);
|
||
[RelayCommand] public void AdjustMinus1() => AdjustSelected(-1);
|
||
|
||
[RelayCommand]
|
||
private void ApplySetValue()
|
||
{
|
||
if (double.TryParse(SetValueText, out double disp)) ApplyDisplayToSelection(disp);
|
||
}
|
||
|
||
/// <summary>Bulk nudge by whole RAW units (one press = ±1 raw = ±multiplier on the display).</summary>
|
||
private void AdjustSelected(int rawDelta)
|
||
{
|
||
if (SelectedEntry?.Table == null) return;
|
||
foreach (var c in BulkTargets()) SetCellValue(c, c.RawValue + rawDelta);
|
||
CurveInvalidated?.Invoke();
|
||
}
|
||
|
||
/// <summary>Set the selection from a DISPLAYED (scaled) value. Rejects non-multiples of the value multiplier.</summary>
|
||
public void ApplyDisplayToSelection(double display)
|
||
{
|
||
if (SelectedEntry?.Table == null) return;
|
||
|
||
int mult = DisplayConvMult;
|
||
double q = display / mult;
|
||
if (Math.Abs(q - Math.Round(q)) > 1e-6)
|
||
{
|
||
StatusMessage = mult == 1
|
||
? "Value must be a whole number"
|
||
: $"Value must be a multiple of {mult}";
|
||
return;
|
||
}
|
||
|
||
double raw = Math.Round(q);
|
||
foreach (var c in BulkTargets()) SetCellValue(c, raw);
|
||
CurveInvalidated?.Invoke();
|
||
}
|
||
|
||
/// <summary>Stores the RAW value on the cell and shows raw × multiplier.</summary>
|
||
private void SetCellValue(TuningTableCellViewModel cell, double raw)
|
||
{
|
||
double cv = ClampConv(raw);
|
||
cell.RawValue = cv;
|
||
cell.DisplayValue = ((long)Math.Round(cv * DisplayConvMult)).ToString();
|
||
}
|
||
|
||
private double ClampConv(double v)
|
||
{
|
||
var t = SelectedEntry?.Table;
|
||
double r = Math.Round(v);
|
||
if (t == null) return r;
|
||
return t.IsConvSigned ? Math.Clamp(r, -128, 127) : Math.Clamp(r, 0, 255);
|
||
}
|
||
|
||
// ── Selection (single row → contiguous column span) ───────────────────────
|
||
|
||
private IEnumerable<TuningTableCellViewModel> SelectedCells => Cells.Where(c => c.IsSelected);
|
||
|
||
public void BeginSelection(TuningTableCellViewModel cell)
|
||
{
|
||
CommitEdit();
|
||
foreach (var c in Cells) c.IsSelected = false;
|
||
SelectedCell = cell;
|
||
cell.IsSelected = true;
|
||
UpdateSelectionBorders();
|
||
CurveInvalidated?.Invoke(); // recolour the active curve point
|
||
}
|
||
|
||
public void ExtendSelection(TuningTableCellViewModel target)
|
||
{
|
||
if (SelectedCell == null) { BeginSelection(target); return; }
|
||
int c0 = Math.Min(SelectedCell.Col, target.Col);
|
||
int c1 = Math.Max(SelectedCell.Col, target.Col);
|
||
foreach (var c in Cells) c.IsSelected = c.Col >= c0 && c.Col <= c1;
|
||
UpdateSelectionBorders();
|
||
CurveInvalidated?.Invoke();
|
||
}
|
||
|
||
private void UpdateSelectionBorders()
|
||
{
|
||
const double bw = 2.5;
|
||
var cols = new HashSet<int>(SelectedCells.Select(c => c.Col));
|
||
foreach (var c in Cells)
|
||
{
|
||
if (!c.IsSelected) { c.SelectionBorder = new Thickness(0); continue; }
|
||
double l = cols.Contains(c.Col - 1) ? 0 : bw;
|
||
double r = cols.Contains(c.Col + 1) ? 0 : bw;
|
||
c.SelectionBorder = new Thickness(l, bw, r, bw);
|
||
}
|
||
}
|
||
|
||
private void ClearSelection()
|
||
{
|
||
CancelEdit();
|
||
foreach (var c in Cells) c.IsSelected = false;
|
||
SelectedCell = null;
|
||
UpdateSelectionBorders();
|
||
}
|
||
|
||
private List<TuningTableCellViewModel> BulkTargets()
|
||
{
|
||
var t = SelectedCells.ToList();
|
||
if (t.Count == 0 && SelectedCell != null) t.Add(SelectedCell);
|
||
return t;
|
||
}
|
||
|
||
// ── In-cell editing ───────────────────────────────────────────────────────
|
||
|
||
public void BeginEdit(string? seed = null)
|
||
{
|
||
if (SelectedCell == null || SelectedEntry?.Table == null) return;
|
||
CancelEdit();
|
||
EditingCell = SelectedCell;
|
||
SelectedCell.EditText = seed ?? SelectedCell.DisplayValue;
|
||
SelectedCell.IsEditing = true;
|
||
}
|
||
|
||
public void CommitEdit()
|
||
{
|
||
var cell = EditingCell;
|
||
if (cell == null) return;
|
||
cell.IsEditing = false;
|
||
EditingCell = null;
|
||
if (double.TryParse(cell.EditText, out double v)) ApplyDisplayToSelection(v);
|
||
}
|
||
|
||
public void CancelEdit()
|
||
{
|
||
if (EditingCell == null) return;
|
||
EditingCell.IsEditing = false;
|
||
EditingCell = null;
|
||
}
|
||
|
||
// ── Copy / paste (horizontal) ─────────────────────────────────────────────
|
||
|
||
private double[]? _clipboard;
|
||
|
||
[RelayCommand]
|
||
private void CopySelection()
|
||
{
|
||
var cells = SelectedCells.OrderBy(c => c.Col).ToList();
|
||
if (cells.Count == 0) return;
|
||
_clipboard = cells.Select(c => c.RawValue).ToArray();
|
||
StatusMessage = $"Copied {_clipboard.Length} cells";
|
||
}
|
||
|
||
[RelayCommand]
|
||
private void PasteToSelection()
|
||
{
|
||
if (_clipboard == null || SelectedEntry?.Table == null || SelectedCell == null) return;
|
||
|
||
int baseC = SelectedCell.Col;
|
||
var pasted = new List<TuningTableCellViewModel>();
|
||
for (int i = 0; i < _clipboard.Length; i++)
|
||
{
|
||
int cc = baseC + i;
|
||
if (cc >= N) break; // clamp to last column
|
||
SetCellValue(Cells[cc], _clipboard[i]);
|
||
pasted.Add(Cells[cc]);
|
||
}
|
||
|
||
foreach (var c in Cells) c.IsSelected = false;
|
||
foreach (var c in pasted) c.IsSelected = true;
|
||
UpdateSelectionBorders();
|
||
CurveInvalidated?.Invoke();
|
||
StatusMessage = $"Pasted {pasted.Count} cells";
|
||
}
|
||
|
||
// ── Axis breakpoint editing ───────────────────────────────────────────────
|
||
|
||
public void BeginAxisEdit(AxisHeaderViewModel h)
|
||
{
|
||
CommitEdit();
|
||
foreach (var x in AxisHeaders) x.IsEditing = false;
|
||
h.EditText = h.DisplayValue;
|
||
h.IsEditing = true;
|
||
EditingHeader = h;
|
||
}
|
||
|
||
public void CommitAxisEdit(AxisHeaderViewModel h)
|
||
{
|
||
if (!h.IsEditing) return;
|
||
h.IsEditing = false;
|
||
if (ReferenceEquals(EditingHeader, h)) EditingHeader = null;
|
||
|
||
var t = SelectedEntry?.Table;
|
||
if (t == null) return;
|
||
if (!double.TryParse(h.EditText, out double entered)) return; // revert silently
|
||
|
||
// Match whatever the axis is currently displaying: scaled when the ×scale
|
||
// toggle is on, unscaled (raw) when off — so the user types what they see.
|
||
int mult = ShowXMultiplied ? EffRawMult : 1;
|
||
double q = entered / mult;
|
||
if (Math.Abs(q - Math.Round(q)) > 1e-6)
|
||
{
|
||
StatusMessage = mult == 1
|
||
? "Axis must be a whole number"
|
||
: $"Axis must be a multiple of {mult}";
|
||
return; // reject, display reverts
|
||
}
|
||
|
||
// Bound only to what a raw axis byte can physically store. The table's
|
||
// MinRaw/MaxRaw bytes are display metadata and are frequently 0/0, which
|
||
// previously clamped every entry to 0 and then failed the sequence check.
|
||
// The strict-between-neighbours check below is the real ordering constraint.
|
||
int lo = t.IsRawSigned ? -128 : 0;
|
||
int hi = t.IsRawSigned ? 127 : 255;
|
||
int raw = Math.Clamp((int)Math.Round(q), lo, hi);
|
||
|
||
var vals = AxisHeaders.Select(x => x.Value).ToList();
|
||
if (!IsInSequence(vals, h.Index, raw))
|
||
{
|
||
StatusMessage = SequenceMessage(vals, h.Index, mult);
|
||
return; // out of sequence → reject, display reverts
|
||
}
|
||
|
||
h.Value = raw;
|
||
h.DisplayValue = ((long)raw * mult).ToString();
|
||
StatusMessage = $"Axis[{h.Index}] = {(long)raw * mult}{UnitSuffix(SelectedEntry?.AxisUnit)}";
|
||
CurveInvalidated?.Invoke();
|
||
}
|
||
|
||
public void CancelAxisEdit(AxisHeaderViewModel h)
|
||
{
|
||
h.IsEditing = false;
|
||
if (ReferenceEquals(EditingHeader, h)) EditingHeader = null;
|
||
}
|
||
|
||
/// <summary>Strict monotonic check against immediate neighbours (direction auto-detected).</summary>
|
||
private static bool IsInSequence(IReadOnlyList<int> vals, int index, int newVal)
|
||
{
|
||
bool ascending = vals.Count < 2 || vals[^1] >= vals[0];
|
||
int? lo = index > 0 ? vals[index - 1] : (int?)null;
|
||
int? hi = index < vals.Count - 1 ? vals[index + 1] : (int?)null;
|
||
|
||
return ascending
|
||
? (lo is null || newVal > lo) && (hi is null || newVal < hi)
|
||
: (lo is null || newVal < lo) && (hi is null || newVal > hi);
|
||
}
|
||
|
||
private static string SequenceMessage(IReadOnlyList<int> vals, int index, int mult)
|
||
{
|
||
bool ascending = vals.Count < 2 || vals[^1] >= vals[0];
|
||
int? lo = index > 0 ? vals[index - 1] : (int?)null;
|
||
int? hi = index < vals.Count - 1 ? vals[index + 1] : (int?)null;
|
||
long? lower = (ascending ? lo : hi) is int a ? (long)a * mult : (long?)null;
|
||
long? upper = (ascending ? hi : lo) is int b ? (long)b * mult : (long?)null;
|
||
|
||
if (lower is not null && upper is not null) return $"Axis must be between {lower} and {upper}";
|
||
if (lower is not null) return $"Axis must be greater than {lower}";
|
||
if (upper is not null) return $"Axis must be less than {upper}";
|
||
return "Axis out of sequence";
|
||
}
|
||
|
||
private static string UnitSuffix(string? u) => string.IsNullOrWhiteSpace(u) ? "" : " " + u;
|
||
|
||
// ── Grid population ───────────────────────────────────────────────────────
|
||
|
||
private void PopulateGrid(OneDimTable t)
|
||
{
|
||
int rawMult = Math.Max(1, (int)t.RawMultiplier);
|
||
int convMult = Math.Max(1, (int)t.ConvMultiplier);
|
||
|
||
AxisHeaders.Clear();
|
||
for (int i = 0; i < N; i++)
|
||
AxisHeaders.Add(new AxisHeaderViewModel
|
||
{
|
||
Index = i,
|
||
Kind = AxisKind.Rpm, // tag only; 1D edit logic is local
|
||
Value = t.RawAxis[i],
|
||
DisplayValue = ((long)t.RawAxis[i] * (ShowXMultiplied ? rawMult : 1)).ToString(),
|
||
});
|
||
|
||
for (int c = 0; c < N; c++)
|
||
{
|
||
var cell = Cells[c];
|
||
cell.RawValue = t.ConvValues[c];
|
||
cell.DisplayValue = ((long)t.ConvValues[c] * (ShowYMultiplied ? convMult : 1)).ToString();
|
||
cell.Background = CellBg;
|
||
cell.Foreground = Brushes.White;
|
||
cell.IsSelected = false;
|
||
cell.SelectionBorder = new Thickness(0);
|
||
}
|
||
|
||
MetaSummary = BuildMeta(t);
|
||
OnPropertyChanged(nameof(MetaRows));
|
||
CurveInvalidated?.Invoke();
|
||
}
|
||
|
||
private void ClearGrid()
|
||
{
|
||
AxisHeaders.Clear();
|
||
foreach (var c in Cells)
|
||
{
|
||
c.RawValue = 0;
|
||
c.DisplayValue = string.Empty;
|
||
c.IsSelected = false;
|
||
c.SelectionBorder = new Thickness(0);
|
||
}
|
||
MetaSummary = string.Empty;
|
||
CurveInvalidated?.Invoke();
|
||
}
|
||
|
||
private void HarvestToModel(OneDimEntryViewModel entry)
|
||
{
|
||
var t = entry.Table;
|
||
if (t == null) return;
|
||
|
||
for (int c = 0; c < N; c++)
|
||
t.ConvValues[c] = (int)Math.Round(Cells[c].RawValue);
|
||
|
||
for (int i = 0; i < N && i < AxisHeaders.Count; i++)
|
||
t.RawAxis[i] = AxisHeaders[i].Value;
|
||
|
||
// Metadata bytes (sign / min / max / multipliers / rounding / offset) are
|
||
// left untouched and round-trip verbatim via OneDimTable.ToWirePayload().
|
||
}
|
||
|
||
private static string BuildMeta(OneDimTable t)
|
||
{
|
||
int rm = Math.Max(1, (int)t.RawMultiplier), cm = Math.Max(1, (int)t.ConvMultiplier);
|
||
string axisRange = $"[{(long)t.MinRaw * rm}\u2026{(long)t.MaxRaw * rm}]";
|
||
return $"axis {(t.IsRawSigned ? "signed" : "unsigned")} {axisRange} \u00D7{rm} " +
|
||
$"value {(t.IsConvSigned ? "signed" : "unsigned")} \u00D7{cm} offset {t.ConvOffset} " +
|
||
$"(display = raw \u00D7 multiplier)";
|
||
}
|
||
|
||
private static Brush MakeFrozen(byte r, byte g, byte b)
|
||
{
|
||
var br = new SolidColorBrush(Color.FromRgb(r, g, b));
|
||
br.Freeze();
|
||
return br;
|
||
}
|
||
|
||
public void Dispose() { }
|
||
}
|