using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Threading; using System.Threading.Tasks; using OpenNest.Collections; using OpenNest.Diagnostics; using OpenNest.Forms; using OpenNest.Geometry; namespace OpenNest.Controls; /// /// UI-thread owner of overlap requests and their cached display geometry. /// Workers see only owned analyzer snapshots, never the live plate or view. /// When auto-check is enabled, an unchecked or out-of-date layout is rechecked after it /// has been quiet for (see ). /// internal sealed class OverlapOverlayController : IDisposable { private readonly PlateView view; private readonly OverlapReportState state = new(); private readonly OverlapAutoCheckScheduler autoCheck = new(); // Prepared drawing material survives rechecks; only in-place program edits clear it. private readonly OverlapMaterialCache materialCache = new(); // Last completed report: pairs of parts unchanged since then are reused, not clipped again. private PlateOverlapReport baseline; private readonly System.Windows.Forms.Timer autoCheckTimer; private Func autoCheckUnits; private ObservableList observedParts; private CancellationTokenSource cancellation; private string reportedSummary; private GraphicsPath path; private IReadOnlyList pathPairs; private float pathScale; private Units capturedUnits; private Plate observedPlate; private IReadOnlyList hoveredPairs = Array.Empty(); private IReadOnlyList hoveredSpacing = Array.Empty(); private IReadOnlyList hoveredEdges = Array.Empty(); private string hoverText; private OverlapHoverPages hoverPages; private Point hoverPoint; private (float Scale, PointF Offset, int Dpi) hoverTransform; private bool disposed; public OverlapOverlayController(PlateView view) { this.view = view; autoCheckTimer = new System.Windows.Forms.Timer { Interval = DefaultAutoCheckDelayMs }; autoCheckTimer.Tick += AutoCheckTick; } public const int DefaultAutoCheckDelayMs = 500; public event EventHandler StateChanged; public OverlapCheckStatus Status => state.Status; public PlateOverlapReport Report => state.Report; public bool IsRunning => state.IsRunning; // Deterministic worker seam for STA lifecycle tests. Capture always stays on the UI thread. // Null runs the incremental analyzer against the last completed report. internal Func Analyze { get; set; } internal GraphicsPath CachedPath => path; internal OverlapHoverPages HoverPages => hoverPages; internal RectangleF HoverBounds { get; private set; } internal bool IsAutoCheckEnabled => autoCheckUnits != null; internal bool IsAutoCheckScheduled => autoCheckTimer.Enabled; // Test seam for gestures that cannot be simulated off a real message loop. internal Func IsInteractionActive { get; set; } = DefaultInteractionActive; public int AutoCheckDelay { get => autoCheckTimer.Interval; set => autoCheckTimer.Interval = value; } public string Message => autoCheck.IsWaiting ? "Overlaps: check pending…" : state.Message; /// The status bar's words: one steady "checking" for both pending and running. public string Summary => IsSettling ? "Layout: checking…" : state.Summary; public bool NeedsAttention => !IsSettling && state.NeedsAttention; /// /// The corner stays empty unless something is wrong: on a clear result, and while an /// automatic recheck settles after one or before the first. Views without automatic rechecks /// keep their pending text, because nothing will arrive unless the user asks. /// internal bool ShowsNoLabel => IsSettling ? state.SettledMessage == null || state.SettledClear : state.IsAllClear; private bool IsSettling => autoCheckUnits != null && (autoCheck.IsWaiting || state.IsRunning); /// /// Recheck automatically after layout edits settle. Units are read when each request /// starts, like the manual command. Pass null to return to manual-only checks. /// public void SetAutoCheck(Func units) { autoCheckUnits = units; autoCheck.Reset(); autoCheckTimer.Stop(); NotifyChanged(); } public OverlapDisplayMode DisplayMode { get => state.DisplayMode; set { if (state.DisplayMode == value) return; state.DisplayMode = value; NotifyChanged(); } } public void SetPlate(Plate plate) { Unsubscribe(); CancelWorker(); state.Reset(); autoCheck.Reset(); baseline = null; ReleasePath(); observedPlate = plate; if (observedPlate != null) observedPlate.ClampZonesChanged += ZonesChanged; observedParts = plate?.Parts; if (observedParts != null) { observedParts.ItemAdded += PartAdded; observedParts.ItemRemoved += PartRemoved; observedParts.ItemChanged += PartChanged; observedParts.ItemsReordered += PartsReordered; } NotifyChanged(); } public Task CheckAsync(Units units) => CheckAsync(units, automatic: false); // Automatic requests keep the display mode and report only on the canvas label; the // status bar keeps the user's last command result (for example a fill's timing). private async Task CheckAsync(Units units, bool automatic) { if (!CanUseView || view.Plate == null) return; if (view.InvokeRequired) throw new InvalidOperationException("Overlap checks must be started on the UI thread."); CancelWorker(); var plate = view.Plate; var generation = state.Begin(plate, automatic); autoCheck.Started(plate); capturedUnits = units; // Same request boundary as the owned geometry/names, never read live units in paint. var source = new CancellationTokenSource(); cancellation = source; var token = source.Token; NotifyChanged(toStatusBar: !automatic); try { // Do not include PreviewManager parts. Capture owns clean geometry and stable names. var snapshot = PlateOverlapAnalyzer.CapturePlate(plate, materialCache, token); var previous = baseline; var analyze = Analyze ?? ((input, cancel) => PlateOverlapAnalyzer.Analyze(input, previous, cancel)); var report = await Task.Run(() => analyze(snapshot, token), token); if (!CanUseView || generation != state.Generation || !ReferenceEquals(plate, view.Plate)) return; if (token.IsCancellationRequested) state.Cancel(); else if (state.TryPublish(generation, view.Plate, report)) baseline = report; else CancelWorker(); // A pose/reference mismatch discovered at publication is stale. NotifyChanged(toStatusBar: !automatic); } catch (OperationCanceledException) when (token.IsCancellationRequested) { if (CanUseView && generation == state.Generation) { state.Cancel(); NotifyChanged(toStatusBar: !automatic); } } catch (Exception ex) { Debug.WriteLine($"Overlap check failed: {ex}"); if (CanUseView && generation == state.Generation) { if (!state.TryFail(generation, view.Plate)) CancelWorker(); NotifyChanged(toStatusBar: !automatic); } } finally { if (ReferenceEquals(cancellation, source)) cancellation = null; source.Dispose(); } } private bool CanUseView => !disposed && !view.IsDisposed && !view.Disposing && view.IsHandleCreated; public void Cancel() { if (!state.IsRunning) return; CancelWorker(); state.Cancel(); ReleasePath(); NotifyChanged(toStatusBar: true); // The user's Cancel command. } /// /// For editors that may mutate clean drawing programs in place: drops cached material /// as well as the current report. Call before loading the editor. /// public void InvalidateGeometry() { materialCache.Clear(); baseline = null; state.Invalidate(); CancelWorker(); ReleasePath(); NotifyChanged(); } public void Invalidate() { var generation = state.Generation; var display = state.DisplayPairs; state.Invalidate(view.Plate); if (!ReferenceEquals(display, state.DisplayPairs)) { ReleasePath(); ClearHover(); } if (generation == state.Generation) { // Already unchecked/stale: an edit restarts the quiet period. Bulk fills raise one // event per part, so only restart the timer here; the next paint or the timer's own // settle check refreshes the layout stamp. if (autoCheck.IsWaiting) RestartAutoCheckTimer(); else UpdateAutoCheck(repaint: true); return; } CancelWorker(); NotifyChanged(); } public void ReleaseHandle() { CancelWorker(); state.Cancel(); state.Invalidate(); ReleasePath(); // Handle loss is not a user cancel: forget that request so the first paint after // recreation can schedule a recheck. A tick while the handle is gone only resets. autoCheck.Reset(); autoCheckTimer.Stop(); NotifyChanged(); } private void CancelWorker() { // The awaiting request disposes its own source after the worker exits. var source = cancellation; cancellation = null; source?.Cancel(); } private void NotifyChanged(bool toStatusBar = false) { if (!ReferenceEquals(pathPairs, state.DisplayPairs)) ReleasePath(); ClearHover(); if (disposed || view.IsDisposed || view.Disposing) return; UpdateAutoCheck(repaint: false); // Without auto-check every change is reported as before. if (toStatusBar || autoCheckUnits == null) view.Status = Message; view.Invalidate(); reportedSummary = Summary; StateChanged?.Invoke(this, EventArgs.Empty); } /// /// Restart the quiet period when the layout changed since it was last observed. /// redraws the label if its pending text changed; paint and /// NotifyChanged callers draw or invalidate themselves. /// private void UpdateAutoCheck(bool repaint) { if (autoCheckUnits == null || disposed) return; var wasWaiting = autoCheck.IsWaiting; if (autoCheck.Observe(view.Plate, state)) RestartAutoCheckTimer(); else if (!autoCheck.IsWaiting) autoCheckTimer.Stop(); if (repaint && wasWaiting != autoCheck.IsWaiting && !view.IsDisposed && !view.Disposing) view.Invalidate(); } private void RestartAutoCheckTimer() { autoCheckTimer.Stop(); autoCheckTimer.Start(); } private void AutoCheckTick(object sender, EventArgs e) => RunAutoCheckTimer(); /// The timer's tick. Returns the started request, if any, for STA tests. internal Task RunAutoCheckTimer() { autoCheckTimer.Stop(); if (autoCheckUnits == null || disposed) return Task.CompletedTask; if (!CanUseView) { autoCheck.Reset(); return Task.CompletedTask; } var busy = view.IsFillInProgress || IsInteractionActive(); switch (autoCheck.Elapsed(view.Plate, state, busy)) { case OverlapAutoCheckStep.Wait: autoCheckTimer.Start(); return Task.CompletedTask; case OverlapAutoCheckStep.Check: // CheckAsync reports its own failures through the state label. return CheckAsync(autoCheckUnits(), automatic: true); default: view.Invalidate(); // Pending text may have cleared. return Task.CompletedTask; } } // Do not check mid-gesture or while another operation owns the plate: dragging holds a // mouse button, fills/auto-nest show a progress window, and modal editors (for example // the drawing converter) may be mutating clean programs in place. private static bool DefaultInteractionActive() => System.Windows.Forms.Control.MouseButtons != System.Windows.Forms.MouseButtons.None || System.Windows.Forms.Application.OpenForms.Cast() .Any(form => form.Modal || form is NestProgressForm); private void ZonesChanged(object sender, EventArgs e) => Invalidate(); private void PartAdded(object sender, ItemAddedEventArgs e) => Invalidate(); private void PartRemoved(object sender, ItemRemovedEventArgs e) => Invalidate(); private void PartChanged(object sender, ItemChangedEventArgs e) => Invalidate(); private void PartsReordered(object sender, EventArgs e) => Invalidate(); private void Unsubscribe() { if (observedPlate != null) { observedPlate.ClampZonesChanged -= ZonesChanged; observedPlate = null; } if (observedParts == null) return; observedParts.ItemAdded -= PartAdded; observedParts.ItemRemoved -= PartRemoved; observedParts.ItemChanged -= PartChanged; observedParts.ItemsReordered -= PartsReordered; observedParts = null; } public void Draw(Graphics graphics) { if (disposed) return; EnsureFresh(); UpdateAutoCheck(repaint: false); // Drags/nudges are only visible to the stamp; the label is drawn below. // A wait can start or end here without a state change, and the status bar must follow. if (reportedSummary != Summary) { reportedSummary = Summary; StateChanged?.Invoke(this, EventArgs.Empty); } ValidateHoverTransform(); if (state.DisplayPairs.Count > 0) { if (state.DisplayMode is OverlapDisplayMode.Areas or OverlapDisplayMode.Both) { EnsurePath(); if (path.PointCount > 0) { using var brush = new SolidBrush(Color.FromArgb(100, 255, 0, 80)); // A single winding fill is the union: triple overlap is not painted darker. graphics.FillPath(brush, path); } } if (ShowsCentroids) DrawCentroids(graphics); } if (state.DisplayMode != OverlapDisplayMode.Off) { DrawCutOffClampContacts(graphics); DrawSpacingMarkers(graphics); DrawEdgeMarkers(graphics); } DrawStateLabel(graphics); } private bool EnsureFresh() { if (disposed) return false; var generation = state.Generation; var display = state.DisplayPairs; var fresh = state.EnsureFresh(view.Plate); if (!ReferenceEquals(display, state.DisplayPairs)) { ReleasePath(); ClearHover(); } if (generation != state.Generation) { CancelWorker(); NotifyChanged(); } return fresh; } private bool ShowsCentroids => state.DisplayMode is OverlapDisplayMode.Centroids or OverlapDisplayMode.Both; private (float, PointF, int) ViewTransform => (view.ViewScale, view.PointControlToGraph(Point.Empty), view.DeviceDpi); internal string HoverText { get { if (!EnsureFresh()) ClearHover(); ValidateHoverTransform(); return hoverText; } } public void UpdateHover(Point point) { ValidateHoverTransform(); if (!EnsureFresh() || state.DisplayMode == OverlapDisplayMode.Off || state.Report == null) { ClearHover(); return; } // Graph coordinates are already screen-scaled; remove pan from the pointer once. var graphPoint = view.PointControlToGraph(point); var pointer = new Vector(graphPoint.X, graphPoint.Y); Vector ToGraph(Vector world) { var graph = view.PointWorldToGraph(world); return new Vector(graph.X, graph.Y); } // Overlap markers exist only in these modes; spacing and edge markers in every visible one. var hits = ShowsCentroids ? OverlapPairPresentation.HitTest(state.DisplayPairs, ToGraph, pointer, view.DeviceDpi) : Array.Empty(); var spacingHits = OverlapPairPresentation.HitTest(state.DisplaySpacingPairs, ToGraph, pointer, view.DeviceDpi); var edgeHits = OverlapPairPresentation.HitTest(state.DisplayEdgeFindings, ToGraph, pointer, view.DeviceDpi); var changed = !hits.SequenceEqual(hoveredPairs) || !spacingHits.SequenceEqual(hoveredSpacing) || !edgeHits.SequenceEqual(hoveredEdges); var moved = point != hoverPoint; hoveredPairs = hits; hoveredSpacing = spacingHits; hoveredEdges = edgeHits; hoverPoint = point; hoverTransform = ViewTransform; if (changed) { hoverPages = null; HoverBounds = RectangleF.Empty; hoverText = hits.Count + spacingHits.Count + edgeHits.Count == 0 ? null : string.Join("\n\n", hits.Select(pair => OverlapPairPresentation.Details(pair, capturedUnits)) .Concat(spacingHits.Select(pair => OverlapPairPresentation.Details(pair, capturedUnits))) .Concat(edgeHits.Select(finding => OverlapPairPresentation.Details(finding, capturedUnits)))); } if (changed || (moved && hoverText != null)) view.Invalidate(); } private void ValidateHoverTransform() { if (hoverText != null && hoverTransform != ViewTransform) ClearHover(); } public void ClearHover() { var visible = hoverText != null; hoverText = null; hoverPages = null; HoverBounds = RectangleF.Empty; hoveredPairs = Array.Empty(); hoveredSpacing = Array.Empty(); hoveredEdges = Array.Empty(); if (visible && !disposed && !view.IsDisposed && !view.Disposing) view.Invalidate(); } public bool TryPageHover(int delta) { // Revalidate even when a key arrives before the next paint/mouse event. if (HoverText == null || hoverPages == null || hoverPages.PageCount < 2) return false; hoverPages.MovePage(delta); view.Invalidate(); return true; } private void DrawCentroids(Graphics graphics) { var dpiScale = view.DeviceDpi / 96f; var radius = (float)OverlapPairPresentation.MarkerHalfSize(view.DeviceDpi); using var halo = new Pen(Color.White, 4 * dpiScale); using var crosshair = new Pen(Color.DarkRed, 2 * dpiScale); // Stack coincident pair labels instead of replacing them with a fragment count. var labelRows = new Dictionary(); foreach (var pair in state.DisplayPairs.OrderBy(pair => pair.PartAId).ThenBy(pair => pair.PartBId)) { var center = view.PointWorldToGraph(pair.Marker); if (!float.IsFinite(center.X) || !float.IsFinite(center.Y)) continue; foreach (var pen in new[] { halo, crosshair }) { graphics.DrawLine(pen, center.X - radius, center.Y, center.X + radius, center.Y); graphics.DrawLine(pen, center.X, center.Y - radius, center.X, center.Y + radius); } var label = OverlapPairPresentation.Label(pair); var size = graphics.MeasureString(label, view.Font); labelRows.TryGetValue(center, out var row); labelRows[center] = row + 1; var x = center.X + radius + 3 * dpiScale; var y = center.Y - radius + row * size.Height; graphics.FillRectangle(Brushes.White, x, y, size.Width, size.Height); graphics.DrawString(label, view.Font, Brushes.DarkRed, x, y); } } // Draw last, over action adorners. The normal part tooltip is suppressed only while // these details are actually visible; its independent timer/state is not stolen. public bool DrawHover(Graphics graphics) { var text = HoverText; // Includes a fresh stamp check even if no mouse move/paint preceded this. if (text == null) return false; var saved = graphics.Save(); try { graphics.ResetTransform(); graphics.SetClip(view.ClientRectangle, CombineMode.Intersect); var scale = view.DeviceDpi / 96f; var padding = 4 * scale; var maxWidth = System.Math.Min(560 * scale, view.ClientSize.Width - 2) - padding * 2; var lineHeight = (float)System.Math.Ceiling(view.Font.GetHeight(graphics)); var maxRows = (int)((view.ClientSize.Height - 2 - padding * 2) / lineHeight); using var format = (StringFormat)StringFormat.GenericTypographic.Clone(); format.FormatFlags |= StringFormatFlags.NoWrap | StringFormatFlags.MeasureTrailingSpaces; float Measure(string line) => graphics.MeasureString(line, view.Font, PointF.Empty, format).Width; hoverPages ??= OverlapHoverPages.Create(text, hoveredPairs.Count + hoveredSpacing.Count + hoveredEdges.Count, maxRows, maxWidth, line => Measure(line)); if (hoverPages.NeedsLargerViewport) { // A viewport smaller than a content line plus its paging hint cannot // show details legibly. Say so rather than presenting clipped data. HoverBounds = new RectangleF(0, 0, view.ClientSize.Width, view.ClientSize.Height); graphics.FillRectangle(Brushes.White, HoverBounds); graphics.DrawString("Enlarge view to read overlap details", view.Font, Brushes.DarkRed, HoverBounds); return true; } var lines = hoverPages.Lines.Concat(hoverPages.NavigationLines).ToArray(); var width = lines.Max(Measure) + padding * 2; var height = lines.Length * lineHeight + padding * 2; var x = System.Math.Max(0, System.Math.Min(hoverPoint.X + 16 * scale, view.ClientSize.Width - width)); var y = hoverPoint.Y - height - 6 * scale; if (y < 0) y = System.Math.Max(0, System.Math.Min(hoverPoint.Y + 20 * scale, view.ClientSize.Height - height)); HoverBounds = new RectangleF(x, y, width, height); graphics.FillRectangle(Brushes.White, x, y, width, height); graphics.DrawRectangle(Pens.DimGray, x, y, width, height); for (var row = 0; row < lines.Length; row++) graphics.DrawString(lines[row], view.Font, row < hoverPages.Lines.Count ? Brushes.Black : Brushes.DarkRed, new PointF(x + padding, y + padding + row * lineHeight), format); } finally { graphics.Restore(saved); } return true; } private void EnsurePath() { if (ReferenceEquals(pathPairs, state.DisplayPairs) && pathScale == view.ViewScale && path != null) return; ReleasePath(); var next = new GraphicsPath(FillMode.Winding); try { foreach (var pair in state.DisplayPairs) { foreach (var region in pair.Regions) { // Outlines wind one way and holes the other, so the winding fill leaves // holes empty while overlapping pairs' islands still merge. next.AddPolygon(GraphRing(region.Vertices, positive: true)); foreach (var hole in region.Holes) next.AddPolygon(GraphRing(hole, positive: false)); } } path = next; pathPairs = state.DisplayPairs; pathScale = view.ViewScale; } catch { next.Dispose(); throw; } } /// /// Graph points of a closed world ring (the analyzer repeats the closing vertex), wound /// positive for outlines or negative for holes in world space whatever the input order. /// private PointF[] GraphRing(IReadOnlyList vertices, bool positive) { var points = new PointF[vertices.Count - 1]; var signedArea = 0.0; var start = vertices[0]; for (var i = 0; i < points.Length; i++) { var a = vertices[i] - start; var b = vertices[i + 1] - start; signedArea += a.X * b.Y - b.X * a.Y; // The host has already translated by origin: graph, not control coordinates. points[i] = view.PointWorldToGraph(vertices[i]); } if (signedArea < 0 == positive) Array.Reverse(points); return points; } private void DrawCutOffClampContacts(Graphics graphics) { var dpi = view.DeviceDpi / 96f; using var halo = new Pen(Color.White, 4 * dpi); using var warning = new Pen(Color.DarkRed, 2 * dpi); foreach (var finding in state.DisplayCutOffClampFindings) { var point = view.PointWorldToGraph(finding.Location); if (!float.IsFinite(point.X) || !float.IsFinite(point.Y)) continue; foreach (var pen in new[] { halo, warning }) { graphics.DrawLine(pen, point.X - 8 * dpi, point.Y - 8 * dpi, point.X + 8 * dpi, point.Y + 8 * dpi); graphics.DrawLine(pen, point.X - 8 * dpi, point.Y + 8 * dpi, point.X + 8 * dpi, point.Y - 8 * dpi); } var label = $"Cut-off {finding.CutOffIndex + 1} / {finding.ClampId}"; var size = graphics.MeasureString(label, view.Font); var x = point.X + 10 * dpi; var y = point.Y - size.Height; graphics.FillRectangle(Brushes.White, x, y, size.Width, size.Height); graphics.DrawString(label, view.Font, Brushes.DarkRed, x, y); } } // A gap has no shared area to shade, so every visible mode marks it: an orange ring at the // narrowest point, apart from the red overlap crosshairs. Labels on one point stack. private void DrawSpacingMarkers(Graphics graphics) { var dpiScale = view.DeviceDpi / 96f; var radius = (float)OverlapPairPresentation.MarkerHalfSize(view.DeviceDpi); var color = Color.FromArgb(200, 90, 0); using var halo = new Pen(Color.White, 4 * dpiScale); using var ring = new Pen(color, 2 * dpiScale); using var text = new SolidBrush(color); var labelRows = new Dictionary(); foreach (var pair in state.DisplaySpacingPairs) { var center = view.PointWorldToGraph(pair.Marker); if (!float.IsFinite(center.X) || !float.IsFinite(center.Y)) continue; foreach (var pen in new[] { halo, ring }) graphics.DrawEllipse(pen, center.X - radius, center.Y - radius, radius * 2, radius * 2); var label = OverlapPairPresentation.Label(pair); var size = graphics.MeasureString(label, view.Font); labelRows.TryGetValue(center, out var row); labelRows[center] = row + 1; var x = center.X + radius + 3 * dpiScale; var y = center.Y - radius + row * size.Height; graphics.FillRectangle(Brushes.White, x, y, size.Width, size.Height); graphics.DrawString(label, view.Font, text, x, y); } } // Edge findings mark a point, not shared area, so every visible mode shows them: off the // plate in the overlaps' red crosshair, outside the work area in the spacing ring's orange. private void DrawEdgeMarkers(Graphics graphics) { var dpiScale = view.DeviceDpi / 96f; var radius = (float)OverlapPairPresentation.MarkerHalfSize(view.DeviceDpi); var spacingColor = Color.FromArgb(200, 90, 0); using var halo = new Pen(Color.White, 4 * dpiScale); using var crosshair = new Pen(Color.DarkRed, 2 * dpiScale); using var ring = new Pen(spacingColor, 2 * dpiScale); using var spacingText = new SolidBrush(spacingColor); var labelRows = new Dictionary(); foreach (var finding in state.DisplayEdgeFindings) { var center = view.PointWorldToGraph(finding.Marker); if (!float.IsFinite(center.X) || !float.IsFinite(center.Y)) continue; if (finding.OffPlate) { foreach (var pen in new[] { halo, crosshair }) { graphics.DrawLine(pen, center.X - radius, center.Y, center.X + radius, center.Y); graphics.DrawLine(pen, center.X, center.Y - radius, center.X, center.Y + radius); } } else { foreach (var pen in new[] { halo, ring }) graphics.DrawEllipse(pen, center.X - radius, center.Y - radius, radius * 2, radius * 2); } var label = OverlapPairPresentation.Label(finding); var size = graphics.MeasureString(label, view.Font); labelRows.TryGetValue(center, out var row); labelRows[center] = row + 1; var x = center.X + radius + 3 * dpiScale; var y = center.Y - radius + row * size.Height; graphics.FillRectangle(Brushes.White, x, y, size.Width, size.Height); graphics.DrawString(label, view.Font, finding.OffPlate ? Brushes.DarkRed : spacingText, x, y); } } private void DrawStateLabel(Graphics graphics) { var saved = graphics.Save(); try { graphics.ResetTransform(); if (ShowsNoLabel) return; // While settling, the last findings stay put, dimmed, instead of status text flickering. var settling = IsSettling; var text = (settling ? state.SettledMessage : Message) + (state.DisplayMode == OverlapDisplayMode.Off ? " (display off)" : ""); var size = graphics.MeasureString(text, view.Font); using var background = new SolidBrush(Color.FromArgb(235, Color.White)); graphics.FillRectangle(background, 6, 6, size.Width + 8, size.Height + 6); graphics.DrawString(text, view.Font, settling ? Brushes.Gray : Brushes.DarkRed, 10, 9); } finally { graphics.Restore(saved); } } private void ReleasePath() { path?.Dispose(); path = null; pathPairs = null; } public void Dispose() { if (disposed) return; disposed = true; autoCheckTimer.Stop(); autoCheckTimer.Dispose(); Unsubscribe(); CancelWorker(); state.Reset(); ReleasePath(); ClearHover(); } }