diff --git a/OpenNest.Avalonia/Controls/PlateCanvas.Zoom.cs b/OpenNest.Avalonia/Controls/PlateCanvas.Zoom.cs
new file mode 100644
index 00000000..09fc3161
--- /dev/null
+++ b/OpenNest.Avalonia/Controls/PlateCanvas.Zoom.cs
@@ -0,0 +1,228 @@
+using Avalonia;
+using Avalonia.Input;
+using Avalonia.Threading;
+using OpenNest.Desktop.Interaction;
+using OpenNest.Desktop.Rendering;
+using OpenNest.Geometry;
+using SkiaSharp;
+
+namespace OpenNest.Avalonia.Controls
+{
+ ///
+ /// View > Zoom In, Zoom Out and Zoom To (Area, Plate, Selected), Tools > Measure Area and
+ /// the delayed hover tip, as the WinForms plate view: the zoom and measure tools are the
+ /// shared and , the tip the shared
+ /// on a dispatcher timer.
+ ///
+ public sealed partial class PlateCanvas
+ {
+ private readonly PartHoverTip hoverTip = new();
+ private DispatcherTimer hoverTimer;
+
+ /// View > Zoom In and the header's button: half again about the view center.
+ public void ZoomIn() => ZoomAboutCenter(ViewTransform.CommandZoomFactor);
+
+ /// View > Zoom Out and the header's button.
+ public void ZoomOut() => ZoomAboutCenter(1 / ViewTransform.CommandZoomFactor);
+
+ /// View > Zoom To > Plate: the sheet without parts outside it.
+ public void ZoomToPlate() => ZoomTo(PlateZoom.PlateArea(plate));
+
+ /// View > Zoom To > Selected: nothing happens with no part selected.
+ public void ZoomToSelected() => ZoomTo(PlateZoom.SelectedArea(plate, selection));
+
+ /// View > Zoom To > Area and the header's button: starts the Zoom Window tool.
+ public void StartZoomWindow()
+ {
+ if (plate != null)
+ tools.SetTool(new ZoomWindowTool(this, tools));
+ }
+
+ /// Tools > Measure Area: starts the tool that shows the largest clear box at the pointer.
+ public void StartMeasureArea()
+ {
+ if (plate != null)
+ tools.SetTool(new MeasureAreaTool(this));
+ }
+
+ private void ZoomAboutCenter(double factor)
+ {
+ if (plate == null || Bounds.Width <= 0 || Bounds.Height <= 0)
+ return;
+ view.Resize(Bounds.Width, Bounds.Height);
+ view.ZoomAboutCenter(factor);
+ fitPending = false;
+ InvalidateVisual();
+ ViewChanged?.Invoke(this, System.EventArgs.Empty);
+ }
+
+ private void ZoomTo(Box area)
+ {
+ if (area == null || Bounds.Width <= 0 || Bounds.Height <= 0)
+ return;
+ view.Resize(Bounds.Width, Bounds.Height);
+ if (!view.ZoomToArea(area))
+ return;
+ fitPending = false;
+ InvalidateVisual();
+ ViewChanged?.Invoke(this, System.EventArgs.Empty);
+ }
+
+ // Space, on release as in WinForms, turns the measured box.
+ protected override void OnKeyUp(KeyEventArgs e)
+ {
+ base.OnKeyUp(e);
+ if (e.Key == Key.Space && e.KeyModifiers == KeyModifiers.None && tools.Current is MeasureAreaTool measure)
+ {
+ measure.ToggleDirection();
+ e.Handled = true;
+ }
+ }
+
+ private void InitializeHoverTip()
+ {
+ hoverTimer = new DispatcherTimer { Interval = PartHoverTip.Delay };
+ hoverTimer.Tick += OnHoverTimer;
+ // As WinForms: any zoom, pan or resize hides the tip. No redraw is asked for here:
+ // a fit made while rendering changes the view, and the frame drawn next has no tip.
+ view.Changed += (_, _) => ClearHoverTip();
+ }
+
+ // As the WinForms view: in Select, with no button held and edits not locked, each move
+ // hides the tip and restarts the delay.
+ private void UpdateHoverTip(Point at, ToolButton button)
+ {
+ if (button != ToolButton.None || EditsLocked || tools.Current is not SelectTool)
+ {
+ if (ClearHoverTip())
+ InvalidateVisual();
+ return;
+ }
+ if (hoverTip.Move(new ScreenPoint(at.X, at.Y)))
+ InvalidateVisual();
+ hoverTimer.Stop();
+ hoverTimer.Start();
+ }
+
+ /// Whether a shown tip was hidden.
+ private bool ClearHoverTip()
+ {
+ hoverTimer?.Stop();
+ return hoverTip.Clear();
+ }
+
+ private void OnHoverTimer(object sender, System.EventArgs e)
+ {
+ hoverTimer.Stop();
+ if (hoverTip.Elapse(at => hitTester.PartAt(plate, ToWorld(new Point(at.X, at.Y)))))
+ InvalidateVisual();
+ }
+
+ private void BuildToolOverlays(Scene scene)
+ {
+ switch (tools.Current)
+ {
+ case ZoomWindowTool { Window: { } window }:
+ scene.ZoomWindow = window.Box;
+ break;
+ case MeasureAreaTool { Area: { } area } measure:
+ scene.MeasureArea = area;
+ scene.MeasureLabel = measure.Label;
+ break;
+ }
+ if (hoverTip.Text is { } tip)
+ {
+ scene.Tip = tip;
+ scene.TipAnchor = hoverTip.Anchor;
+ }
+ }
+
+ private sealed partial class Scene
+ {
+ public Box ZoomWindow;
+ public Box MeasureArea;
+ public string MeasureLabel;
+ public string Tip;
+ public ScreenPoint TipAnchor;
+ }
+
+ private sealed partial class PlatePainter
+ {
+ private static readonly SKColor ZoomWindowBorder = new(99, 162, 228);
+ private static readonly SKColor ZoomWindowFill = new(150, 200, 255, 90);
+ private static readonly SKColor MeasureBorder = new(50, 255, 50);
+ private static readonly SKColor MeasureFill = new(50, 255, 50, 50);
+ private static readonly SKColor MeasureText = new(0, 128, 0); // Green
+ private static readonly SKColor TipBack = new(255, 255, 255, 230);
+ private static readonly SKColor TipBorder = new(105, 105, 105); // DimGray
+
+ private void DrawToolOverlays()
+ {
+ DrawZoomWindow();
+ DrawMeasureArea();
+ DrawTip();
+ }
+
+ // The WinForms Zoom Window box: a blue rectangle with a cross at its center.
+ private void DrawZoomWindow()
+ {
+ if (scene.ZoomWindow is not { } box)
+ return;
+ var rect = Screen(box);
+ using var fill = Fill(ZoomWindowFill);
+ fill.IsAntialias = false;
+ canvas.DrawRect(rect, fill);
+ using var border = Stroke(ZoomWindowBorder);
+ border.IsAntialias = false;
+ canvas.DrawRect(rect, border);
+ const float halfWidth = 10;
+ canvas.DrawLine(rect.MidX, rect.MidY - halfWidth, rect.MidX, rect.MidY + halfWidth, border);
+ canvas.DrawLine(rect.MidX - halfWidth, rect.MidY, rect.MidX + halfWidth, rect.MidY, border);
+ }
+
+ // The measured box in green with its size centered in it, as WinForms (14 pt text).
+ private void DrawMeasureArea()
+ {
+ if (scene.MeasureArea is not { } box)
+ return;
+ var rect = Screen(box);
+ using var border = Stroke(MeasureBorder);
+ border.IsAntialias = false;
+ canvas.DrawRect(rect, border);
+ using var fill = Fill(MeasureFill);
+ fill.IsAntialias = false;
+ canvas.DrawRect(rect, fill);
+ if (string.IsNullOrEmpty(scene.MeasureLabel))
+ return;
+ using var text = new SKPaint
+ {
+ Color = MeasureText,
+ IsAntialias = true,
+ TextSize = 18.7f,
+ TextAlign = SKTextAlign.Center,
+ };
+ var metrics = text.FontMetrics;
+ canvas.DrawText(scene.MeasureLabel, rect.MidX, rect.MidY - (metrics.Ascent + metrics.Descent) / 2, text);
+ }
+
+ // The drawing name beside the pointer on a white box, placed as WinForms places it.
+ private void DrawTip()
+ {
+ if (string.IsNullOrEmpty(scene.Tip))
+ return;
+ using var text = new SKPaint { Color = SKColors.Black, IsAntialias = true, TextSize = 12 };
+ var metrics = text.FontMetrics;
+ var height = metrics.Descent - metrics.Ascent;
+ var (x, y, width, boxHeight) = PartHoverTip.Place(
+ scene.TipAnchor, text.MeasureText(scene.Tip), height, scene.Bounds.Width);
+ var rect = SKRect.Create((float)x, (float)y, (float)width, (float)boxHeight);
+ using var back = Fill(TipBack);
+ canvas.DrawRect(rect, back);
+ using var border = Stroke(TipBorder);
+ border.IsAntialias = false;
+ canvas.DrawRect(rect, border);
+ canvas.DrawText(scene.Tip, (float)x + 3, (float)y + 2 - metrics.Ascent, text);
+ }
+ }
+ }
+}
diff --git a/OpenNest.Avalonia/Controls/PlateCanvas.cs b/OpenNest.Avalonia/Controls/PlateCanvas.cs
index 80bd9e72..f4032449 100644
--- a/OpenNest.Avalonia/Controls/PlateCanvas.cs
+++ b/OpenNest.Avalonia/Controls/PlateCanvas.cs
@@ -31,7 +31,7 @@ namespace OpenNest.Avalonia.Controls
/// highlights the part under the cursor. Left and right clicks go to the active plate tool
/// (, Select by default); Escape steps out of it.
///
- public sealed class PlateCanvas : Control, IPlateToolHost
+ public sealed partial class PlateCanvas : Control, IPlateToolHost
{
// Paths are built once per part pose and only read afterwards, so the render thread may draw
// them while the UI thread builds others.
@@ -63,6 +63,7 @@ namespace OpenNest.Avalonia.Controls
var changed = !ReferenceEquals(plate, value);
plate = value;
HoveredPart = null;
+ ClearHoverTip();
if (changed)
{
selection.Plate = value;
@@ -172,6 +173,7 @@ namespace OpenNest.Avalonia.Controls
Focusable = true;
hitTester = new PlateHitTester(part => PathsFor(part).Geometry);
tools = new PlateToolManager(this);
+ InitializeHoverTip();
// While the place tool is active, edits move its copies.
Edits = new PlateEdits(this) { Tools = tools };
selection.Changed += (_, _) =>
@@ -371,6 +373,7 @@ namespace OpenNest.Avalonia.Controls
BuildCommonLines(scene);
if (options.DrawSupport)
BuildSupport(scene);
+ BuildToolOverlays(scene);
}
// A selected cut-off is drawn solid blue in place of its dashes, as in WinForms.
@@ -461,7 +464,8 @@ namespace OpenNest.Avalonia.Controls
return;
}
var at = e.GetPosition(this);
- view.ZoomAt(new ScreenPoint(at.X, at.Y), System.Math.Pow(1.2, e.Delta.Y));
+ // The WinForms step per wheel notch.
+ view.ZoomAt(new ScreenPoint(at.X, at.Y), System.Math.Pow(ViewTransform.ZoomInFactor, e.Delta.Y));
InvalidateVisual();
ViewChanged?.Invoke(this, EventArgs.Empty);
e.Handled = true;
@@ -505,6 +509,8 @@ namespace OpenNest.Avalonia.Controls
CursorWorld = ToWorld(at);
if (panStart is { } start)
{
+ // As WinForms: moving with a button held hides the hover highlight and tip.
+ ClearHover();
view.Pan(at.X - start.X, at.Y - start.Y);
panStart = at;
InvalidateVisual();
@@ -523,6 +529,7 @@ namespace OpenNest.Avalonia.Controls
HoveredPart = hovered;
InvalidateVisual();
}
+ UpdateHoverTip(at, button);
}
ViewChanged?.Invoke(this, EventArgs.Empty);
}
@@ -585,10 +592,10 @@ namespace OpenNest.Avalonia.Controls
private void ClearHover()
{
- if (HoveredPart == null)
- return;
+ var shown = ClearHoverTip() | HoveredPart != null;
HoveredPart = null;
- InvalidateVisual();
+ if (shown)
+ InvalidateVisual();
}
private ToolPointer ToolPointerAt(Point at, ToolButton button, KeyModifiers keys) =>
@@ -670,7 +677,7 @@ namespace OpenNest.Avalonia.Controls
Vector? Tab);
/// Everything one frame draws, built on the UI thread and only read on the render thread.
- private sealed class Scene
+ private sealed partial class Scene
{
public Rect Bounds;
public SkiaSchemePalette Palette;
@@ -738,7 +745,7 @@ namespace OpenNest.Avalonia.Controls
/// Paints a scene in the WinForms view's order and pen sizes: widths and dashes are screen
/// pixels, so parts drawn in world units scale them by the zoom.
///
- private sealed class PlatePainter
+ private sealed partial class PlatePainter
{
private static readonly SKColor LeadColor = new(255, 69, 0); // OrangeRed
private static readonly SKColor DisplayColor = new(70, 110, 140);
@@ -841,6 +848,7 @@ namespace OpenNest.Avalonia.Controls
DrawCommonLines();
DrawSupport();
DrawSelectionWindow();
+ DrawToolOverlays();
}
private void DrawSheet()
diff --git a/OpenNest.Avalonia/MainWindow.Zoom.cs b/OpenNest.Avalonia/MainWindow.Zoom.cs
new file mode 100644
index 00000000..3b631c65
--- /dev/null
+++ b/OpenNest.Avalonia/MainWindow.Zoom.cs
@@ -0,0 +1,65 @@
+using System;
+using Avalonia.Input;
+using Avalonia.Interactivity;
+using OpenNest.Avalonia.Controls;
+
+namespace OpenNest.Avalonia
+{
+ ///
+ /// View > Zoom To (Area, Fit, Plate, Selected), Zoom In (Ctrl+Plus) and Zoom Out
+ /// (Ctrl+Minus); Nest > First, Last, Next (Ctrl+Right) and Previous (Ctrl+Left) Plate; and
+ /// Tools > Measure Area, as the WinForms main form's menus.
+ ///
+ public partial class MainWindow
+ {
+ private void AddViewKeyBindings()
+ {
+ foreach (var (key, action) in new (Key, Action)[]
+ {
+ (Key.OemPlus, () => OnZoomIn(null, null)),
+ (Key.OemMinus, () => OnZoomOut(null, null)),
+ (Key.Right, () => StepPlate(1)),
+ (Key.Left, () => StepPlate(-1)),
+ })
+ {
+ KeyBindings.Add(new KeyBinding
+ {
+ Gesture = new KeyGesture(key, KeyModifiers.Control),
+ Command = new Command(action),
+ });
+ }
+ }
+
+ private void OnZoomIn(object sender, RoutedEventArgs e) => ActiveView?.PlateView.ZoomIn();
+
+ private void OnZoomOut(object sender, RoutedEventArgs e) => ActiveView?.PlateView.ZoomOut();
+
+ private void OnZoomToPlate(object sender, RoutedEventArgs e) => ActiveView?.PlateView.ZoomToPlate();
+
+ private void OnZoomToSelected(object sender, RoutedEventArgs e) => ActiveView?.PlateView.ZoomToSelected();
+
+ private void OnZoomToArea(object sender, RoutedEventArgs e) => StartTool(canvas => canvas.StartZoomWindow());
+
+ private void OnMeasureArea(object sender, RoutedEventArgs e) => StartTool(canvas => canvas.StartMeasureArea());
+
+ // The view takes the keyboard, so Escape (and Space for Measure Area) reach the tool after
+ // a menu click.
+ private void StartTool(Action start)
+ {
+ if (ActiveView is not { PlateView: { } canvas } view)
+ return;
+ start(canvas);
+ // Focusing the view would otherwise place a drawing picked up in the list.
+ view.CancelPickup();
+ canvas.Focus();
+ }
+
+ private void OnFirstPlate(object sender, RoutedEventArgs e) => ActiveView?.ShowPlate(0);
+
+ private void OnLastPlate(object sender, RoutedEventArgs e)
+ {
+ if (ActiveView is { } view)
+ view.ShowPlate(view.PlateCount - 1);
+ }
+ }
+}
diff --git a/OpenNest.Avalonia/MainWindow.axaml b/OpenNest.Avalonia/MainWindow.axaml
index d70d4cb0..45f3742a 100644
--- a/OpenNest.Avalonia/MainWindow.axaml
+++ b/OpenNest.Avalonia/MainWindow.axaml
@@ -35,6 +35,13 @@
@@ -54,14 +61,20 @@
-
-
-
+
+
+
+
+
+
+
+
+
diff --git a/OpenNest.Avalonia/MainWindow.axaml.cs b/OpenNest.Avalonia/MainWindow.axaml.cs
index 99ab51ad..6df96388 100644
--- a/OpenNest.Avalonia/MainWindow.axaml.cs
+++ b/OpenNest.Avalonia/MainWindow.axaml.cs
@@ -115,6 +115,7 @@ namespace OpenNest.Avalonia
Gesture = new KeyGesture(Key.F6),
Command = new Command(() => OnSetRotationIncrement(null, null)),
});
+ AddViewKeyBindings();
// Ctrl+Tab before focus navigation takes the Tab key.
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
// .nest files dropped anywhere on the window, the nest view included, open in tabs.
diff --git a/OpenNest.Avalonia/NestView.Zoom.cs b/OpenNest.Avalonia/NestView.Zoom.cs
new file mode 100644
index 00000000..a592e06a
--- /dev/null
+++ b/OpenNest.Avalonia/NestView.Zoom.cs
@@ -0,0 +1,23 @@
+using Avalonia.Interactivity;
+
+namespace OpenNest.Avalonia
+{
+ /// The nest header's zoom buttons, as the WinForms nest window's.
+ public partial class NestView
+ {
+ private void OnZoomOut(object sender, RoutedEventArgs e) => Canvas.ZoomOut();
+
+ private void OnZoomIn(object sender, RoutedEventArgs e) => Canvas.ZoomIn();
+
+ private void OnZoomToFit(object sender, RoutedEventArgs e) => Canvas.ZoomToFit();
+
+ // The view takes the keyboard so Escape reaches the tool; a drawing picked up in the
+ // list would otherwise be placed by that focus.
+ private void OnZoomToArea(object sender, RoutedEventArgs e)
+ {
+ Canvas.StartZoomWindow();
+ CancelPickup();
+ Canvas.Focus();
+ }
+ }
+}
diff --git a/OpenNest.Avalonia/NestView.axaml b/OpenNest.Avalonia/NestView.axaml
index 75ec11bf..c9bbf2bc 100644
--- a/OpenNest.Avalonia/NestView.axaml
+++ b/OpenNest.Avalonia/NestView.axaml
@@ -34,6 +34,12 @@
+
+
+
+
+
+
diff --git a/OpenNest.Desktop.Tests/Interaction/PartHoverTipTests.cs b/OpenNest.Desktop.Tests/Interaction/PartHoverTipTests.cs
new file mode 100644
index 00000000..d9f8459f
--- /dev/null
+++ b/OpenNest.Desktop.Tests/Interaction/PartHoverTipTests.cs
@@ -0,0 +1,73 @@
+using OpenNest.Desktop.Interaction;
+using OpenNest.Desktop.Rendering;
+
+namespace OpenNest.Desktop.Tests.Interaction;
+
+public class PartHoverTipTests
+{
+ private readonly Part part = new(new Drawing("bracket", InteractionFixtures.Rect(10, 10)), Geometry.Vector.Zero);
+
+ [Fact]
+ public void The_tip_shows_the_drawing_name_only_after_the_delay_at_the_rest_point()
+ {
+ var tip = new PartHoverTip();
+ ScreenPoint? asked = null;
+
+ Assert.False(tip.Elapse(_ => part));
+ Assert.False(tip.Move(new ScreenPoint(5, 6)));
+ Assert.True(tip.IsPending);
+ Assert.Null(tip.Text);
+
+ Assert.True(tip.Elapse(at =>
+ {
+ asked = at;
+ return part;
+ }));
+
+ Assert.Equal(new ScreenPoint(5, 6), asked);
+ Assert.Equal("bracket", tip.Text);
+ Assert.Same(part, tip.Part);
+ Assert.False(tip.IsPending);
+ // The timer elapsing again changes nothing.
+ Assert.False(tip.Elapse(_ => null));
+ Assert.Same(part, tip.Part);
+ }
+
+ [Fact]
+ public void A_move_or_clear_hides_the_tip_and_reports_a_redraw()
+ {
+ var tip = new PartHoverTip();
+ tip.Move(new ScreenPoint(1, 1));
+ tip.Elapse(_ => part);
+
+ Assert.True(tip.Move(new ScreenPoint(2, 2)));
+ Assert.Null(tip.Text);
+ Assert.False(tip.Move(new ScreenPoint(3, 3)));
+
+ tip.Elapse(_ => part);
+ Assert.True(tip.Clear());
+ Assert.False(tip.IsPending);
+ Assert.False(tip.Elapse(_ => part));
+ Assert.False(tip.Clear());
+ }
+
+ [Fact]
+ public void Over_bare_plate_no_tip_shows()
+ {
+ var tip = new PartHoverTip();
+ tip.Move(new ScreenPoint(1, 1));
+
+ Assert.False(tip.Elapse(_ => null));
+ Assert.Null(tip.Text);
+ }
+
+ [Fact]
+ public void The_tip_sits_above_right_and_flips_at_the_right_and_top_edges()
+ {
+ Assert.Equal((116.0, 74.0, 46.0, 24.0), PartHoverTip.Place(new ScreenPoint(100, 100), 40, 20, 1000));
+ // Past the right edge: to the left of the pointer.
+ Assert.Equal((52.0, 74.0, 46.0, 24.0), PartHoverTip.Place(new ScreenPoint(100, 100), 40, 20, 150));
+ // Past the top: below the pointer.
+ Assert.Equal((116.0, 30.0, 46.0, 24.0), PartHoverTip.Place(new ScreenPoint(100, 10), 40, 20, 1000));
+ }
+}
diff --git a/OpenNest.Desktop.Tests/Interaction/ZoomToolsTests.cs b/OpenNest.Desktop.Tests/Interaction/ZoomToolsTests.cs
new file mode 100644
index 00000000..b765b59b
--- /dev/null
+++ b/OpenNest.Desktop.Tests/Interaction/ZoomToolsTests.cs
@@ -0,0 +1,154 @@
+using OpenNest.Desktop.Interaction;
+using OpenNest.Desktop.Rendering;
+using OpenNest.Geometry;
+
+namespace OpenNest.Desktop.Tests.Interaction;
+
+public class ZoomToolsTests
+{
+ private readonly TestToolHost host = new(InteractionFixtures.Plate());
+
+ private ZoomWindowTool StartZoomWindow()
+ {
+ var tool = new ZoomWindowTool(host, host.Tools);
+ host.Tools.SetTool(tool);
+ return tool;
+ }
+
+ private void AssertFits(Box box)
+ {
+ var expected = new ViewTransform();
+ expected.Resize(host.View.ViewportWidth, host.View.ViewportHeight);
+ expected.ZoomToArea(box);
+ Assert.Equal(expected.Scale, host.View.Scale, 9);
+ Assert.Equal(expected.OriginX, host.View.OriginX, 9);
+ Assert.Equal(expected.OriginY, host.View.OriginY, 9);
+ }
+
+ [Fact]
+ public void Zoom_areas_are_the_plate_with_parts_the_sheet_and_the_selected_parts()
+ {
+ var plate = host.Plate;
+ plate.Parts.Add(new Part(new Drawing("outside", InteractionFixtures.Rect(10, 10)), new Vector(120, 0)));
+
+ Assert.Equal(130, PlateZoom.FitArea(plate).Right, 9);
+ Assert.Equal(100, PlateZoom.PlateArea(plate).Right, 9);
+ Assert.Null(PlateZoom.SelectedArea(plate, host.Selection));
+
+ host.Selection.Select(plate.Parts[1]);
+ host.Selection.Select(plate.Parts[4]);
+ var selected = PlateZoom.SelectedArea(plate, host.Selection);
+ Assert.Equal(20, selected.Left, 9);
+ Assert.Equal(0, selected.Bottom, 9);
+ Assert.Equal(30, selected.Right, 9);
+ Assert.Equal(30, selected.Top, 9);
+ Assert.Null(PlateZoom.FitArea(null));
+ }
+
+ [Fact]
+ public void A_long_drag_zooms_to_the_box_and_returns_to_select()
+ {
+ var tool = StartZoomWindow();
+
+ // 20 units at about ten pixels each: well past the 40-pixel drag.
+ host.Drag(10, 10, 30, 25);
+
+ AssertFits(new Box(10, 10, 20, 15));
+ Assert.IsType(host.Tools.Current);
+ Assert.Null(tool.Window);
+ // One zoom ends the tool for good: Escape from Select does not resume it.
+ host.Tools.Escape();
+ Assert.IsType(host.Tools.Current);
+ }
+
+ [Fact]
+ public void A_short_press_sets_the_first_corner_and_the_next_click_zooms()
+ {
+ var tool = StartZoomWindow();
+ var before = host.View.Capture();
+
+ host.Click(10, 10);
+
+ Assert.True(tool.IsBusy);
+ Assert.Same(tool, host.Tools.Current);
+ Assert.Equal(before, host.View.Capture());
+
+ // Without a button held, a move stretches the box toward the second corner.
+ tool.PointerMoved(host.At(40, 30, ToolButton.None));
+ Assert.Equal(new Vector(40, 30), tool.Window.Value.Second);
+
+ host.Click(50, 40);
+
+ AssertFits(new Box(10, 10, 40, 30));
+ Assert.IsType(host.Tools.Current);
+ }
+
+ [Fact]
+ public void A_right_press_cancels_the_box_and_Escape_cancels_then_ends()
+ {
+ var tool = StartZoomWindow();
+ host.Click(10, 10);
+
+ tool.PointerPressed(host.At(10, 10, ToolButton.Right));
+
+ Assert.Null(tool.Window);
+ Assert.False(tool.IsBusy);
+ Assert.Same(tool, host.Tools.Current);
+
+ host.Click(10, 10);
+ host.Tools.Escape();
+ Assert.Same(tool, host.Tools.Current);
+ Assert.Null(tool.Window);
+ host.Tools.Escape();
+ Assert.IsType(host.Tools.Current);
+ }
+
+ [Fact]
+ public void Losing_the_pointer_mid_drag_drops_the_box()
+ {
+ var tool = StartZoomWindow();
+ var before = host.View.Capture();
+ tool.PointerPressed(host.At(10, 10));
+ tool.PointerMoved(host.At(30, 30));
+
+ tool.PointerCaptureLost();
+
+ Assert.Null(tool.Window);
+ Assert.Equal(before, host.View.Capture());
+ Assert.Same(tool, host.Tools.Current);
+ }
+
+ [Fact]
+ public void Measure_area_finds_the_largest_clear_box_and_Space_turns_it()
+ {
+ var tool = new MeasureAreaTool(host);
+ host.Tools.SetTool(tool);
+
+ Assert.Null(tool.Area);
+ // Between the square at x 20..30 and the common-line pair from x 40.
+ tool.PointerMoved(host.At(35, 50, ToolButton.None));
+
+ Assert.Equal(new Box(30, 0, 10, 100).ToString(), tool.Area.ToString());
+ Assert.Equal(tool.Area.Size.ToString(2), tool.Label);
+
+ // Sideways first: from the left edge to the cut-off at x = 80, above the parts.
+ tool.ToggleDirection();
+ Assert.True(tool.Horizontal);
+ Assert.Equal(new Box(0, 30, 80, 70).ToString(), tool.Area.ToString());
+
+ Assert.False(tool.IsBusy);
+ host.Tools.Escape();
+ Assert.IsType(host.Tools.Current);
+ }
+
+ [Fact]
+ public void Measure_area_stays_clear_of_the_part_spacing()
+ {
+ host.Plate.PartSpacing = 1;
+ var tool = new MeasureAreaTool(host);
+
+ tool.PointerMoved(host.At(35, 50, ToolButton.None));
+
+ Assert.Equal(new Box(31, 0, 8, 100).ToString(), tool.Area.ToString());
+ }
+}
diff --git a/OpenNest.Desktop.Tests/Rendering/ViewTransformTests.cs b/OpenNest.Desktop.Tests/Rendering/ViewTransformTests.cs
index c3450992..d6c18c37 100644
--- a/OpenNest.Desktop.Tests/Rendering/ViewTransformTests.cs
+++ b/OpenNest.Desktop.Tests/Rendering/ViewTransformTests.cs
@@ -124,6 +124,75 @@ public class ViewTransformTests
Assert.Equal(250, moved.Y, 9);
}
+ [Fact]
+ public void Resizing_scales_with_the_usable_size_as_the_desktop_view()
+ {
+ var view = Sized(800, 600);
+ view.ZoomToArea(new Box(0, 0, 100, 100));
+ var scale = view.Scale;
+
+ // Narrower: the width limits, (500 - 50) / (800 - 50).
+ view.Resize(500, 600);
+ Assert.Equal(scale * 450 / 750, view.Scale, 9);
+
+ // Back to the size at the last zoom: exactly the zoom the narrowing took away.
+ view.Resize(800, 600);
+ Assert.Equal(scale, view.Scale, 9);
+ var fitted = new ViewTransform();
+ fitted.Resize(800, 600);
+ fitted.ZoomToArea(new Box(0, 0, 100, 100));
+ Assert.Equal(fitted.OriginX, view.OriginX, 9);
+ Assert.Equal(fitted.OriginY, view.OriginY, 9);
+ }
+
+ [Fact]
+ public void Resizing_measures_from_the_size_at_the_last_zoom()
+ {
+ var view = Sized(800, 600);
+ view.ZoomToArea(new Box(0, 0, 100, 100));
+ view.Resize(500, 600);
+ // A zoom at the narrow size makes it the reference.
+ view.ZoomAboutCenter(2);
+ var scale = view.Scale;
+
+ view.Resize(800, 600);
+
+ Assert.Equal(scale * System.Math.Min(750.0 / 450, 550.0 / 550), view.Scale, 9);
+ }
+
+ [Fact]
+ public void Resizing_from_or_to_a_tiny_viewport_only_moves_the_origin()
+ {
+ var view = Sized(800, 600);
+ view.ZoomToArea(new Box(0, 0, 100, 100));
+ var scale = view.Scale;
+ var originX = view.OriginX;
+
+ view.Resize(40, 600);
+ Assert.Equal(scale, view.Scale, 9);
+ Assert.Equal(originX - 380, view.OriginX, 9);
+ view.Resize(800, 600);
+ Assert.Equal(scale, view.Scale, 9);
+ Assert.Equal(originX, view.OriginX, 9);
+ }
+
+ [Fact]
+ public void Command_zoom_is_half_again_about_the_center()
+ {
+ var view = Sized(800, 600);
+ view.ZoomToArea(new Box(0, 0, 100, 100));
+ var scale = view.Scale;
+ var center = view.ScreenToWorld(400, 300);
+
+ view.ZoomAboutCenter(ViewTransform.CommandZoomFactor);
+ Assert.Equal(scale * 1.5, view.Scale, 9);
+ view.ZoomAboutCenter(1 / ViewTransform.CommandZoomFactor);
+ Assert.Equal(scale, view.Scale, 9);
+ var after = view.WorldToScreen(center);
+ Assert.Equal(400, after.X, 6);
+ Assert.Equal(300, after.Y, 6);
+ }
+
[Fact]
public void Panning_moves_the_origin_and_the_visible_area_follows()
{
diff --git a/OpenNest.Desktop/Interaction/MeasureAreaTool.cs b/OpenNest.Desktop/Interaction/MeasureAreaTool.cs
new file mode 100644
index 00000000..089b2713
--- /dev/null
+++ b/OpenNest.Desktop/Interaction/MeasureAreaTool.cs
@@ -0,0 +1,94 @@
+using System.Collections.Generic;
+using OpenNest.CutOffs;
+using OpenNest.Geometry;
+
+namespace OpenNest.Desktop.Interaction;
+
+///
+/// The WinForms Select Area action behind Tools > Measure Area, toolkit-neutral: as the pointer
+/// moves, is the largest empty box around it inside the plate's work area,
+/// clear of the parts (their bounding boxes grown by the part spacing) and the cut-off lines.
+/// The box grows up and down first, then sideways; Space () grows
+/// it sideways first instead. The tool stays active until Escape.
+///
+public sealed class MeasureAreaTool : PlateTool
+{
+ private readonly List obstacles = new();
+ private Box bounds;
+ private Vector? lastPoint;
+
+ public MeasureAreaTool(IPlateToolHost host)
+ : base(host)
+ {
+ Collect();
+ }
+
+ public override string Name => "Measure Area";
+
+ public override bool IsBusy => false;
+
+ /// Whether the box grows sideways first (Space toggles it).
+ public bool Horizontal { get; private set; }
+
+ /// The box measured at the pointer, or null when there is none.
+ public Box Area { get; private set; }
+
+ /// The box's size as WinForms labels it (its to two decimals), or null.
+ public string Label => Area?.Size.ToString(2);
+
+ public override void Cancel() => Host.Invalidate();
+
+ public override bool PointerMoved(ToolPointer pointer)
+ {
+ lastPoint = pointer.World;
+ Update();
+ return true;
+ }
+
+ /// Space: switches which way the box grows first, at the pointer's last point.
+ public void ToggleDirection()
+ {
+ Horizontal = !Horizontal;
+ Update();
+ }
+
+ private void Update()
+ {
+ if (bounds == null || lastPoint is not { } point)
+ Area = null;
+ else
+ {
+ var area = Horizontal
+ ? SpatialQuery.GetLargestBoxHorizontally(point, bounds, obstacles)
+ : SpatialQuery.GetLargestBoxVertically(point, bounds, obstacles);
+ Area = ReferenceEquals(area, Box.Empty) ? null : area;
+ }
+ Host.Invalidate();
+ }
+
+ // Read once when the tool starts, as WinForms: the parts and cut-offs the box must clear.
+ private void Collect()
+ {
+ var plate = Host.Plate;
+ if (plate == null)
+ return;
+ foreach (var part in plate.Parts)
+ {
+ if (part.BaseDrawing.IsCutOff)
+ continue;
+ obstacles.Add(part.BoundingBox.Offset(plate.PartSpacing));
+ }
+
+ // A cut-off part's bounds span from the plate origin (its program is absolute), so each
+ // cut-off is a thin box along its line, from its definition.
+ var plateBounds = plate.BoundingBox(includeParts: false);
+ foreach (var cutOff in plate.CutOffs)
+ {
+ var line = cutOff.Axis == CutOffAxis.Vertical
+ ? new Box(cutOff.Position.X, plateBounds.Y, 0, plateBounds.Width)
+ : new Box(plateBounds.X, cutOff.Position.Y, plateBounds.Length, 0);
+ obstacles.Add(line.Offset(plate.PartSpacing));
+ }
+ bounds = plate.WorkArea();
+ }
+}
diff --git a/OpenNest.Desktop/Interaction/PartHoverTip.cs b/OpenNest.Desktop/Interaction/PartHoverTip.cs
new file mode 100644
index 00000000..7018e2ea
--- /dev/null
+++ b/OpenNest.Desktop/Interaction/PartHoverTip.cs
@@ -0,0 +1,88 @@
+using System;
+using OpenNest.Desktop.Rendering;
+
+namespace OpenNest.Desktop.Interaction;
+
+///
+/// The WinForms plate view's hover tooltip, toolkit-neutral: each pointer move (in Select, no
+/// button held) hides the tip and restarts a timer; when the timer elapses
+/// the part under the point last moved to, if any, has its drawing name shown beside the
+/// pointer. The host owns the timer: it calls , and
+/// , and redraws when they return true.
+///
+public sealed class PartHoverTip
+{
+ /// How long the pointer must rest before the tip shows, as the WinForms hover timer.
+ public static readonly TimeSpan Delay = TimeSpan.FromSeconds(1);
+
+ private bool pending;
+
+ /// The part whose tip is shown, or null.
+ public Part Part { get; private set; }
+
+ /// Where the pointer rested, in screen pixels.
+ public ScreenPoint Anchor { get; private set; }
+
+ /// The tip's text, the part's drawing name, or null while no tip shows.
+ public string Text => Part?.BaseDrawing.Name;
+
+ /// Whether a move started the delay and the timer has not elapsed since.
+ public bool IsPending => pending;
+
+ /// The pointer moved: the tip hides and the delay starts again.
+ /// Whether a shown tip was hidden, so the view must redraw.
+ public bool Move(ScreenPoint at)
+ {
+ Anchor = at;
+ pending = true;
+ return Hide();
+ }
+
+ /// The pointer left, pressed a button or the view changed: no tip until the next move.
+ /// Whether a shown tip was hidden.
+ public bool Clear()
+ {
+ pending = false;
+ return Hide();
+ }
+
+ ///
+ /// The delay elapsed: shows the tip for the part finds at the
+ /// anchor. Nothing happens unless a move is pending.
+ ///
+ /// Whether a tip is now shown.
+ public bool Elapse(Func partAt)
+ {
+ ArgumentNullException.ThrowIfNull(partAt);
+ if (!pending)
+ return false;
+ pending = false;
+ Part = partAt(Anchor);
+ return Part != null;
+ }
+
+ ///
+ /// Where the tip's box goes for text of the given size, as WinForms places it: above and to
+ /// the right of the anchor, flipped to the left when it would pass the view's right edge and
+ /// below when it would pass the top. The box is the text plus a 3 by 2 pixel padding.
+ ///
+ public static (double X, double Y, double Width, double Height) Place(
+ ScreenPoint anchor, double textWidth, double textHeight, double viewWidth)
+ {
+ var x = anchor.X + 16;
+ var y = anchor.Y - textHeight - 6;
+ if (x + textWidth + 8 > viewWidth)
+ x = anchor.X - textWidth - 8;
+ if (y < 0)
+ y = anchor.Y + 20;
+ return (x, y, textWidth + 6, textHeight + 4);
+ }
+
+ private bool Hide()
+ {
+ if (Part == null)
+ return false;
+ Part = null;
+ return true;
+ }
+}
diff --git a/OpenNest.Desktop/Interaction/PlateZoom.cs b/OpenNest.Desktop/Interaction/PlateZoom.cs
new file mode 100644
index 00000000..a351c4b3
--- /dev/null
+++ b/OpenNest.Desktop/Interaction/PlateZoom.cs
@@ -0,0 +1,29 @@
+using System.Linq;
+using OpenNest.Geometry;
+
+namespace OpenNest.Desktop.Interaction;
+
+///
+/// The areas View > Zoom To fits, as the WinForms plate view's: Fit takes the plate with its
+/// parts, Plate the sheet alone and Selected the selected parts.
+///
+public static class PlateZoom
+{
+ /// Zoom To > Fit (and the F key): the plate and every part on it, or null.
+ public static Box FitArea(Plate plate) => plate?.BoundingBox(true);
+
+ /// Zoom To > Plate: the sheet without its parts, or null.
+ public static Box PlateArea(Plate plate) => plate?.BoundingBox(false);
+
+ ///
+ /// Zoom To > Selected: the selected parts on the plate (cut-offs left out, as WinForms),
+ /// or null when no part is selected.
+ ///
+ public static Box SelectedArea(Plate plate, PlateSelection selection)
+ {
+ if (plate == null || selection == null)
+ return null;
+ var parts = selection.Parts.Where(plate.Parts.Contains).ToList();
+ return parts.Count == 0 ? null : parts.GetBoundingBox();
+ }
+}
diff --git a/OpenNest.Desktop/Interaction/ZoomWindowTool.cs b/OpenNest.Desktop/Interaction/ZoomWindowTool.cs
new file mode 100644
index 00000000..64d760bc
--- /dev/null
+++ b/OpenNest.Desktop/Interaction/ZoomWindowTool.cs
@@ -0,0 +1,105 @@
+using System;
+using OpenNest.Geometry;
+
+namespace OpenNest.Desktop.Interaction;
+
+///
+/// The WinForms Zoom Window action (View > Zoom To > Area), toolkit-neutral: a left drag of
+/// more than zooms to the box dragged; a shorter press sets the first
+/// corner, and the next click sets the second and zooms. A right press cancels the box. One zoom
+/// ends the tool, and Escape from Select does not bring it back.
+///
+public sealed class ZoomWindowTool : PlateTool
+{
+ /// A drag longer than this, in pixels, zooms on release; a shorter one waits for a second click.
+ public const double DragPixels = 40;
+
+ private readonly PlateToolManager tools;
+ private bool awaitingSecondCorner;
+
+ /// The manager hosting the tool, which returns to Select after the zoom.
+ public ZoomWindowTool(IPlateToolHost host, PlateToolManager tools)
+ : base(host)
+ {
+ this.tools = tools ?? throw new ArgumentNullException(nameof(tools));
+ }
+
+ public override string Name => "Zoom Window";
+
+ // One zoom ends this tool; Escape from Select must not bring it back.
+ public override bool ResumeOnEscape => false;
+
+ /// Busy once the first corner is set and the tool waits for the second click.
+ public override bool IsBusy => awaitingSecondCorner;
+
+ /// The box between the corners so far, or null before the first press.
+ public SelectionWindow? Window { get; private set; }
+
+ public override void Cancel()
+ {
+ Window = null;
+ awaitingSecondCorner = false;
+ Host.Invalidate();
+ }
+
+ public override bool PointerPressed(ToolPointer pointer)
+ {
+ if (pointer.Button == ToolButton.Right)
+ {
+ Cancel();
+ return true;
+ }
+ if (pointer.Button != ToolButton.Left)
+ return false;
+ if (!awaitingSecondCorner)
+ {
+ Window = new SelectionWindow(pointer.World, pointer.World);
+ Host.Invalidate();
+ }
+ return true;
+ }
+
+ public override bool PointerMoved(ToolPointer pointer)
+ {
+ if (Window is not { } window || !(awaitingSecondCorner || pointer.Button == ToolButton.Left))
+ return false;
+ Window = window with { Second = pointer.World };
+ Host.Invalidate();
+ return true;
+ }
+
+ public override bool PointerReleased(ToolPointer pointer)
+ {
+ if (pointer.Button != ToolButton.Left || Window is not { } window)
+ return false;
+ window = window with { Second = pointer.World };
+ Window = window;
+ if (!awaitingSecondCorner
+ && Host.View.LengthToScreen(window.First.DistanceTo(window.Second)) <= DragPixels)
+ {
+ awaitingSecondCorner = true;
+ Host.Invalidate();
+ return true;
+ }
+ ZoomAndFinish(window);
+ return true;
+ }
+
+ // A drag cut short (Alt+Tab, say) drops the box; a box waiting for its second click stays.
+ public override void PointerCaptureLost()
+ {
+ if (awaitingSecondCorner)
+ return;
+ Window = null;
+ Host.Invalidate();
+ }
+
+ private void ZoomAndFinish(SelectionWindow window)
+ {
+ // A box with no width or height zooms nothing, as WinForms, but still ends the tool.
+ Host.View.ZoomToArea(window.Box);
+ Window = null;
+ awaitingSecondCorner = false;
+ tools.Select();
+ }
+}
diff --git a/OpenNest.Desktop/Rendering/ViewTransform.cs b/OpenNest.Desktop/Rendering/ViewTransform.cs
index b7dda14d..9692ef35 100644
--- a/OpenNest.Desktop/Rendering/ViewTransform.cs
+++ b/OpenNest.Desktop/Rendering/ViewTransform.cs
@@ -15,9 +15,15 @@ public readonly record struct ScreenPoint(double X, double Y);
///
public sealed class ViewTransform
{
- /// The DrawControl's zoom step for one Zoom In.
+ /// The DrawControl's zoom step for one Zoom In and one notch of the wheel.
public const double ZoomInFactor = 1.15;
+ ///
+ /// The step of View > Zoom In and the nest header's zoom buttons (the WinForms main form's
+ /// and nest window's factor), larger than a wheel notch.
+ ///
+ public const double CommandZoomFactor = 1.5;
+
/// Total pixels left around a fitted area (half on each side).
public const double FitBorder = 50;
@@ -57,21 +63,57 @@ public sealed class ViewTransform
return new Box(bottomLeft.X, bottomLeft.Y, ViewportWidth / Scale, ViewportHeight / Scale);
}
+ // The view the resize scaling is measured from: the viewport and scale when the user last
+ // zoomed. Measuring from it, not from the previous size, lets a panel that opens and closes
+ // beside the view hand back exactly the zoom it took away.
+ private double referenceWidth;
+ private double referenceHeight;
+ private double referenceScale;
+ private double appliedScale = double.NaN;
+
///
- /// Sets the viewport size. After the first size, a resize keeps the view centred by moving
- /// the origin half the change, as the WinForms view does.
+ /// Sets the viewport size, as the WinForms view resizes: while both the old and new sizes
+ /// are larger than , the world point at the center stays at the center
+ /// and the scale follows the usable size (measured from the size at the last zoom), so a view
+ /// that fit the plate still fits it when a side panel takes part of the width. From or to a
+ /// smaller size, the origin moves half the change, keeping the view centered.
///
public void Resize(double width, double height)
{
if (width == ViewportWidth && height == ViewportHeight)
return;
- OriginX += (width - ViewportWidth) * 0.5;
- OriginY += (height - ViewportHeight) * 0.5;
+ if (CanScaleOnResize(ViewportWidth, ViewportHeight) && CanScaleOnResize(width, height))
+ ScaleToSize(width, height);
+ else
+ {
+ OriginX += (width - ViewportWidth) * 0.5;
+ OriginY += (height - ViewportHeight) * 0.5;
+ }
ViewportWidth = width;
ViewportHeight = height;
OnChanged();
}
+ private static bool CanScaleOnResize(double width, double height) => width > FitBorder && height > FitBorder;
+
+ private void ScaleToSize(double width, double height)
+ {
+ if (Scale != appliedScale || !CanScaleOnResize(referenceWidth, referenceHeight))
+ {
+ referenceWidth = ViewportWidth;
+ referenceHeight = ViewportHeight;
+ referenceScale = Scale;
+ }
+ var center = ScreenToWorld(ViewportWidth / 2, ViewportHeight / 2);
+ var ratio = System.Math.Min(
+ (width - FitBorder) / (referenceWidth - FitBorder),
+ (height - FitBorder) / (referenceHeight - FitBorder));
+ Scale = System.Math.Clamp(referenceScale * ratio, MinScale, MaxScale);
+ OriginX = width * 0.5 - center.X * Scale;
+ OriginY = height * 0.5 + center.Y * Scale;
+ appliedScale = Scale;
+ }
+
/// Moves the view by a screen offset.
public void Pan(double dx, double dy)
{
@@ -103,12 +145,18 @@ public sealed class ViewTransform
OnChanged();
}
- /// Zooms in or out by one step about the viewport centre.
- public void ZoomStep(bool zoomIn) =>
- ZoomAt(new ScreenPoint(ViewportWidth / 2, ViewportHeight / 2), zoomIn ? ZoomInFactor : 1 / ZoomInFactor);
+ /// Zooms in or out by one step about the viewport center.
+ public void ZoomStep(bool zoomIn) => ZoomAboutCenter(zoomIn ? ZoomInFactor : 1 / ZoomInFactor);
///
- /// Fits in the viewport, centred, with pixels of
+ /// Zooms by about the viewport center, as View > Zoom In and Zoom
+ /// Out do with .
+ ///
+ public void ZoomAboutCenter(double factor) =>
+ ZoomAt(new ScreenPoint(ViewportWidth / 2, ViewportHeight / 2), factor);
+
+ ///
+ /// Fits in the viewport, centered, with pixels of
/// margin in all; an empty area or viewport changes nothing. Returns whether it changed the view.
///
public bool ZoomToArea(Box area)