11 Commits
Author SHA1 Message Date
aj fd15c13d88 test(library): ignore machine-dependent slow-timing reports in the grid check
DrawingLibraryGridFormTests.CheckAllPages_ShowsEveryDrawing_AndListsTheOnesThatFail
failed on the hosted windows-desktop runner (Cross-platform tests run 44221112563)
because one tile's paint took 1078 ms there and the form listed it as "Slow paint"
beside the expected missing revision. Slow-paint and slow-label-search reports are
wall-clock diagnostics, so the test now asserts only the real failures; a hung
label search is still reported as "Hangs: ..." and would fail it.
2026-11-17 21:31:39 -05:00
ajandClaude Opus 5.5 4f1779376b feat(drawing-library): confirm each add with a banner and list it at once
Adding from the Drawing Library now shows a slim green banner naming what
was added (or how many more, with the new required quantity). Each add or
In This Nest quantity edit raises NestChanged, so the main window lists the
drawing on its Drawings tab behind the dialog right away, brings that tab
forward and selects it, instead of waiting for the dialog to close.

The library form tests restore the WinForms synchronization context before
each add: DoEvents leaves a plain one behind, which sent the add's awaits to
the thread pool and created the banner's window there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:08:39 -05:00
aj 04c0e3bca3 fix(server-ci): recognize GitHub's real package-not-found response
The first v0.7.0 publish stopped at preflight because GitHub answers a
missing user package with 404 "Package not found." (documentation_url
.../rest/packages/packages#get-a-package-for-a-user), while the check
only accepted "Not Found", a shape the tests had assumed. Accept that
message too, require the packages documentation URL, and pin the real
body in the tests. Other 404 shapes still stop the job, and the registry
must still report the repository unknown.
2026-11-17 19:51:52 -05:00
aj 244f946912 ci(server): take the publication policy from master, not the tag
The publish job checks out the tag and ran that tree's release helper for
preflight and readback, so an older tag (v0.7.0 requires a private
package) could never publish under the current public policy. Copy
master's helper before checking out the tag and run preflight/readback
from it; the tag's tree is still what gets built, tested and smoked. The
helper is stdlib-only and its local identity stamp is unchanged since
v0.7.0, so the two copies agree on it.
2026-11-17 18:48:42 -05:00
aj 480efb2893 ci(server): let the first publication create the public package
The repository is public and the image carries its source label, so the
first GITHUB_TOKEN push creates a public package linked to the repo and
no manual bootstrap is needed. Preflight accepts GitHub's own package
Not Found only when the registry also reports the repository unknown (a
package hidden from the token still has one); every other error still
stops the job. Readback refuses a package still missing after upload,
and the anonymous pull proves it is public.
2026-11-17 18:47:21 -05:00
aj 6f7d8049a7 ci(server): publish the server image as a public package
The repository is public, so a private image only made every deployment
host log in to ghcr.io. Publication now requires the existing package to
be public and linked to ajisaacs/OpenNest (private or wrong association
stops before upload and is rechecked after it), and the clean-runner
verification pulls the returned digest without logging in, proving
anonymous pulls work. Docs describe the one-time package setup and drop
the deployment-host login; the server itself stays LAN-only.
2026-11-17 18:45:47 -05:00
aj f11f77f879 feat(avalonia): add parts from the drawing list
As in the WinForms nest window, a part can be added from the Drawings
tab two ways. Pressing a drawing picks it up: when the pointer then
enters the plate view, the place tool starts with one part of the
drawing selected in the list, placed by a click, Enter or F1 like a
copy. Dragging a drawing onto the plate adds one part centred where it
is dropped, as one Add Part step.

A drop is refused while Auto Nest runs on the nest and for a drawing of
another nest. A double-click, a drop (at once, before the pointer can
re-enter the plate on X11 and macOS), Edit > Cut or Copy, or an Undo
puts the pick-up down, and the plate takes it only once. The list
selects one drawing at a time and keeps it selected when rebuilt.

As in WinForms, the pointer entering the plate view gives it the
keyboard, and a dropped part leaves the cut-offs as they are.
2026-11-17 17:36:19 -05:00
aj 810cc1ed01 feat(desktop): share adding parts from the drawing list
DrawingPlacement.AddPart is the WinForms drop of a dragged drawing on the
plate: one part with its bounding box centred on the drop point, as one
Add Part step, refused without a plate or while edits are locked. As in
WinForms it leaves the cut-offs as they are. CreatePlaceTool starts the
place tool with one new part of a drawing.

DrawingPickup is the drawing list's pick-up: a single press arms it, the
plate view taking the keyboard takes the drawing then selected (staying
armed when none is), and a drop, double-click or Undo puts it down.
2026-11-17 17:36:19 -05:00
ajandClaude Opus 5.5 587613ff89 feat(shapes): add angle, channel and rolled plate to the Shape Library
Each makes the flat blank of a part bent or rolled along its length,
sized with the bend allowance at the K-factor. Angle and channel bends
are saved on the drawing as 90 degree up bends and etched as an
imported DXF's up bends are. The preview draws each part's section
beside the blank, dimensioned with the formed sizes; a long part's
section is enlarged so it stays readable. K-factor is a plain number,
not a length, in the form.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:28:58 -05:00
aj d7f550dda4 feat(avalonia): cut and copy parts into the place tool
Edit > Cut (Ctrl+X) and Copy (Ctrl+C) start the shared place tool with
the selected parts, as the WinForms Clone Parts action: the copy follows
the pointer, drawn selected and unnumbered, and a left click, Enter or
F1 places it as one Add Part/Add Parts step. Shift settles it toward the
plate's corner on geometry and Ctrl alone on bounding boxes, in the
order saved in Tools > Options > Clone push placement, read at each
placement. Arrow keys, X/Y, a middle click and Shift+wheel move or turn
the copy without an undo step; a middle double-click turns it rather
than fitting the view. Delete removes the copied parts. Escape returns
to Select. Cut also removes the parts as one Cut step.

As in WinForms, the part under the cursor is highlighted only in Select,
nothing is copied or placed while Auto Nest runs on the nest (a middle
double-click then fits the view), and Undo or Redo ends the tool, which
holds the old nest's parts, so Escape cannot bring it back. An ended
tool's copies leave the drawing cache. The view keeps the keyboard after
a menu click so Enter and the arrows reach the tool.
2026-11-17 16:11:14 -05:00
aj c00ae58ac0 feat(desktop): share the place tool for cut and copied parts
Port the WinForms Clone Parts action as the toolkit-neutral PlaceTool:
copies of the sources follow the pointer by their lower-left corner (a
move to the same screen point is ignored, keeping arrow-key nudges), and
each left click places another copy as one Add Part/Add Parts step.
Shift settles toward the quadrant corner on geometry, Ctrl alone on
bounding boxes, reading the placement order at each click. Copied
common-line groups are joined again among the copies and cut-offs are
rebuilt. Delete removes the sources plus selected plate parts in one
Delete step, recorded (and cut-offs rebuilt) only when any were on the
plate. Settling runs before the step opens, so a failure there leaves
nothing to roll back; the copy does not follow the pointer while edits
are locked, as WinForms raises no mouse move then.

PlateClipboard.Copy/Cut start the tool with the selected parts; Cut then
removes the sources as one Cut step without rebuilding cut-offs, as
WinForms does.

While placing, PlateEdits nudges, steps, pushes and rotates the previews
instead of the selection. Unlike WinForms, which records an empty undo
step there, these edits open no undo step, and they never rebuild
cut-offs since the previews are not on the plate.
2026-11-17 16:11:14 -05:00
39 changed files with 2581 additions and 145 deletions

No files matched your search

+12 -15
View File
@@ -141,8 +141,8 @@ jobs:
steps:
- name: Isolate logs, safe metadata and ephemeral auth
run: |
printf 'METADATA_DIR=%s/server-image-metadata\nRESULTS=%s/server-image-results\nDOCKER_CONFIG=%s/server-image-auth\n' \
"$RUNNER_TEMP" "$RUNNER_TEMP" "$RUNNER_TEMP" >> "$GITHUB_ENV"
printf 'METADATA_DIR=%s/server-image-metadata\nRESULTS=%s/server-image-results\nDOCKER_CONFIG=%s/server-image-auth\nRELEASE_POLICY=%s/release-policy/server_image_release.py\n' \
"$RUNNER_TEMP" "$RUNNER_TEMP" "$RUNNER_TEMP" "$RUNNER_TEMP" >> "$GITHUB_ENV"
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
ref: master
@@ -153,6 +153,10 @@ jobs:
env:
TAG: ${{ github.event.release.tag_name || inputs.tag }}
run: python3 scripts/server_image_release.py source
- name: Keep master's publication policy (an older tag's helper must not decide visibility)
run: |
mkdir -p "$(dirname "$RELEASE_POLICY")"
cp scripts/server_image_release.py "$RELEASE_POLICY"
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
ref: ${{ steps.source.outputs.source_sha }}
@@ -203,7 +207,7 @@ jobs:
- name: Refuse unknown visibility, wrong association, and both existing tags
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: python3 scripts/server_image_release.py preflight
run: python3 "$RELEASE_POLICY" preflight
- name: Login and publish only the two immutable tags (no rebuild)
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -219,7 +223,7 @@ jobs:
id: readback
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: python3 scripts/server_image_release.py readback
run: python3 "$RELEASE_POLICY" readback
- name: Remove ephemeral Docker credentials
if: always()
run: rm -rf -- "$DOCKER_CONFIG"
@@ -244,16 +248,15 @@ jobs:
timeout-minutes: 25
permissions:
contents: read
packages: read
env:
VERSION: ${{ needs.publish.outputs.version }}
SOURCE_SHA: ${{ needs.publish.outputs.source_sha }}
MANIFEST_DIGEST: ${{ needs.publish.outputs.manifest_digest }}
CONFIG_DIGEST: ${{ needs.publish.outputs.config_digest }}
steps:
- name: Isolate logs, safe metadata and ephemeral auth
- name: Isolate logs, safe metadata and an empty Docker config
run: |
printf 'METADATA_DIR=%s/server-image-metadata\nRESULTS=%s/server-image-results\nDOCKER_CONFIG=%s/server-image-auth\n' \
printf 'METADATA_DIR=%s/server-image-metadata\nRESULTS=%s/server-image-results\nDOCKER_CONFIG=%s/server-image-anonymous\n' \
"$RUNNER_TEMP" "$RUNNER_TEMP" "$RUNNER_TEMP" >> "$GITHUB_ENV"
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
@@ -264,25 +267,19 @@ jobs:
DOTNET_INSTALL_DIR: ${{ runner.temp }}/dotnet8
with:
dotnet-version: '8.0.x'
- name: Pull returned digest on a clean runner
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Pull returned digest anonymously on a clean runner
run: |
python3 -c 'import os,sys; sys.path.insert(0,"scripts"); from server_image_release import sha256,commit,version; sha256(os.environ["MANIFEST_DIGEST"]); sha256(os.environ["CONFIG_DIGEST"]); commit(os.environ["SOURCE_SHA"]); version("v"+os.environ["VERSION"])'
mkdir -m 700 -p "$DOCKER_CONFIG"
printf '%s' "$GITHUB_TOKEN" | docker login ghcr.io -u "$GITHUB_ACTOR" --password-stdin
image="ghcr.io/ajisaacs/opennest-server@$MANIFEST_DIGEST"
docker pull --platform linux/amd64 "$image"
printf 'LOCAL_IMAGE=%s\n' "$image" >> "$GITHUB_ENV"
- name: Remove ephemeral Docker credentials
if: always()
run: rm -rf -- "$DOCKER_CONFIG"
- name: Verify pulled digest, config, platform and provenance
run: python3 scripts/server_image_release.py pulled
- name: Real-client persistence smoke of pulled digest
run: scripts/Test-ServerContainer.sh --image "$LOCAL_IMAGE" --results "$RESULTS/smoke"
- name: Mark verified only after pulled-image smoke passes
run: printf 'Verified private server image `%s` from `%s`.\n' "$LOCAL_IMAGE" "$SOURCE_SHA" >> "$GITHUB_STEP_SUMMARY"
run: printf 'Verified public server image `%s` from `%s`.\n' "$LOCAL_IMAGE" "$SOURCE_SHA" >> "$GITHUB_STEP_SUMMARY"
- name: Retain logs and safe pulled-image provenance only
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+90 -11
View File
@@ -14,6 +14,7 @@ using OpenNest.CommonLines;
using OpenNest.CutOffs;
using OpenNest.Desktop.Interaction;
using OpenNest.Desktop.Rendering;
using OpenNest.Engine.Fill;
using OpenNest.Geometry;
using OpenNest.Support;
using SkiaSharp;
@@ -117,6 +118,40 @@ namespace OpenNest.Avalonia.Controls
/// <summary>No edits while Auto Nest works on the nest (WinForms EditsLocked).</summary>
public bool EditsLocked { get; set; }
/// <summary>
/// Which way Shift+click and Ctrl+click settle a placed copy (Tools &gt; Options &gt; Clone
/// push placement), read at each click.
/// </summary>
public Func<SettleOrder> PlacementOrder { get; set; } = () => SettleOrder.ClosestToCorner;
/// <summary>
/// Edit &gt; Copy: places copies of the selected parts with the place tool; false when
/// nothing is selected or edits are locked.
/// </summary>
public bool CopySelection() => PlateClipboard.Copy(this, tools, ReadPlacementOrder) != null;
/// <summary>
/// Edit &gt; Cut: as <see cref="CopySelection"/>, then removes the parts as one Cut step.
/// </summary>
public bool CutSelection() => PlateClipboard.Cut(this, tools, ReadPlacementOrder) != null;
/// <summary>
/// A drawing picked in the drawing list and carried into the view: the place tool with one
/// new part of it.
/// </summary>
public void PlaceDrawing(Drawing drawing) =>
tools.SetTool(DrawingPlacement.CreatePlaceTool(this, drawing, ReadPlacementOrder));
/// <summary>
/// A drawing dragged from the drawing list and dropped at <paramref name="at"/> (view
/// coordinates): one part centred there, or null while edits are locked.
/// </summary>
public Part DropDrawing(Drawing drawing, Point at) =>
DrawingPlacement.AddPart(this, drawing, ToWorld(at));
private SettleOrder ReadPlacementOrder() =>
PlacementOrder?.Invoke() ?? SettleOrder.ClosestToCorner;
Undo.ChangeScope IPlateToolHost.BeginChange(string label, object coalesceKey) =>
BeginChangeHandler?.Invoke(label, coalesceKey) ?? Undo.ChangeScope.Detached();
@@ -137,13 +172,19 @@ namespace OpenNest.Avalonia.Controls
Focusable = true;
hitTester = new PlateHitTester(part => PathsFor(part).Geometry);
tools = new PlateToolManager(this);
Edits = new PlateEdits(this);
// While the place tool is active, edits move its copies.
Edits = new PlateEdits(this) { Tools = tools };
selection.Changed += (_, _) =>
{
InvalidateVisual();
ViewChanged?.Invoke(this, EventArgs.Empty);
};
tools.StatusChanged += (_, _) => ViewChanged?.Invoke(this, EventArgs.Empty);
tools.StatusChanged += (_, _) =>
{
// A place tool's copies leave the cache when the tool ends.
TrimCache();
ViewChanged?.Invoke(this, EventArgs.Empty);
};
}
void IPlateToolHost.Invalidate() => InvalidateVisual();
@@ -158,7 +199,8 @@ namespace OpenNest.Avalonia.Controls
commonLineChecks.Clear();
}
// Keeps only the shown plate's parts, so closed plates do not hold their paths.
// Keeps only the shown plate's parts and the place tool's copies, so closed plates and
// ended tools do not hold their paths.
private void TrimCache()
{
if (plate == null)
@@ -168,6 +210,8 @@ namespace OpenNest.Avalonia.Controls
return;
}
var shown = new HashSet<Part>(plate.Parts);
if (tools?.Current is PlaceTool place)
shown.UnionWith(place.Previews);
foreach (var stale in paths.Keys.Where(part => !shown.Contains(part)).ToList())
paths.Remove(stale);
var drawings = new HashSet<Drawing>(plate.Parts.Select(part => part.BaseDrawing));
@@ -289,6 +333,21 @@ namespace OpenNest.Avalonia.Controls
(i + 1).ToString(), LabelPoint(part), selection.Contains(part),
ReferenceEquals(part, HoveredPart), part.BaseDrawing.IsCutOff));
}
// The place tool's copies, drawn selected and unnumbered over the plate, as WinForms.
if (tools.Current is PlaceTool { Previews: var previews })
{
foreach (var preview in previews)
{
var bounds = PathsFor(preview).StrokeBounds;
if (bounds == null)
continue;
var placed = bounds.Translate(preview.Location.X, preview.Location.Y);
var color = ToSkColor(preview.BaseDrawing.Color);
scene.Parts.Add(new PartItem(PathsFor(preview), preview.Location, placed, color,
palette.PartOutline(color), Label: null, preview.Location, Selected: true,
Hovered: false, IsCutOff: false));
}
}
if (options.DrawOffset && plate.PartSpacing > 0)
{
@@ -392,7 +451,7 @@ namespace OpenNest.Avalonia.Controls
{
// As WinForms: Shift+wheel turns the selection (Ctrl+Shift by a tenth); without a
// selection the wheel zooms. Some platforms report Shift+wheel as horizontal.
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift) && selection.Parts.Count > 0
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift) && Edits.HasPartsToEdit
&& !EditsLocked)
{
var delta = e.Delta.Y != 0 ? e.Delta.Y : e.Delta.X;
@@ -417,7 +476,7 @@ namespace OpenNest.Avalonia.Controls
{
// As WinForms: a middle double-click fits only with nothing selected; with a
// selection each click turns it, so a double-click turns it 180 degrees.
if (e.ClickCount == 2 && selection.Parts.Count == 0)
if (e.ClickCount == 2 && (EditsLocked || !Edits.HasPartsToEdit))
{
ZoomToFit();
return;
@@ -455,8 +514,10 @@ namespace OpenNest.Avalonia.Controls
var button = point.Properties.IsLeftButtonPressed ? ToolButton.Left
: point.Properties.IsRightButtonPressed ? ToolButton.Right : ToolButton.None;
tools.Current.PointerMoved(ToolPointerAt(at, button, e.KeyModifiers));
// As WinForms: the part under the cursor is highlighted only while no button is held.
var hovered = button == ToolButton.None ? hitTester.PartAt(plate, CursorWorld.Value) : null;
// As WinForms: the part under the cursor is highlighted only in Select, while no
// button is held.
var hovered = button == ToolButton.None && tools.Current is SelectTool
? hitTester.PartAt(plate, CursorWorld.Value) : null;
if (!ReferenceEquals(hovered, HoveredPart))
{
HoveredPart = hovered;
@@ -480,7 +541,7 @@ namespace OpenNest.Avalonia.Controls
panStart = null;
// A middle click, not a drag, turns the selection 90 degrees.
var at = e.GetPosition(this);
if (middleDown is { } down && selection.Parts.Count > 0
if (middleDown is { } down && Edits.HasPartsToEdit
&& (at.X - down.X) * (at.X - down.X) + (at.Y - down.Y) * (at.Y - down.Y) < 25)
Edits.RotateQuarterTurn();
middleDown = null;
@@ -506,6 +567,15 @@ namespace OpenNest.Avalonia.Controls
tools.Current.PointerCaptureLost();
}
// As the WinForms plate view: the pointer entering the view gives it the keyboard, which
// also places a drawing picked up in the drawing list.
protected override void OnPointerEntered(PointerEventArgs e)
{
base.OnPointerEntered(e);
if (!IsFocused)
Focus();
}
protected override void OnPointerExited(PointerEventArgs e)
{
CursorWorld = null;
@@ -521,7 +591,10 @@ namespace OpenNest.Avalonia.Controls
InvalidateVisual();
}
private ToolPointer ToolPointerAt(Point at, ToolButton button, KeyModifiers keys)
private ToolPointer ToolPointerAt(Point at, ToolButton button, KeyModifiers keys) =>
new(ToWorld(at), new ScreenPoint(at.X, at.Y), button, ModifiersOf(keys));
private static ToolModifiers ModifiersOf(KeyModifiers keys)
{
var modifiers = ToolModifiers.None;
if (keys.HasFlag(KeyModifiers.Shift))
@@ -531,7 +604,7 @@ namespace OpenNest.Avalonia.Controls
modifiers |= ToolModifiers.Control;
if (keys.HasFlag(KeyModifiers.Alt))
modifiers |= ToolModifiers.Alt;
return new ToolPointer(ToWorld(at), new ScreenPoint(at.X, at.Y), button, modifiers);
return modifiers;
}
protected override void OnKeyDown(KeyEventArgs e)
@@ -546,6 +619,12 @@ namespace OpenNest.Avalonia.Controls
ZoomToFit();
e.Handled = true;
}
else if (e.Key is Key.Enter or Key.F1 && tools.Current is PlaceTool place)
{
// As WinForms: Enter and F1 place a copy, Shift or Ctrl held settling it.
place.Apply(ModifiersOf(e.KeyModifiers));
e.Handled = true;
}
else if (EditFor(e.Key, e.KeyModifiers) is { } edit)
{
edit();
@@ -879,7 +958,7 @@ namespace OpenNest.Avalonia.Controls
canvas.Restore();
// A number shows only once the part is big enough on screen to hold it.
if (item.IsCutOff)
if (item.IsCutOff || item.Label == null)
continue;
var bounds = Screen(item.Bounds);
var width = text.MeasureText(item.Label);
+4
View File
@@ -28,6 +28,10 @@
<MenuItem x:Name="UndoMenuItem" Header="_Undo" InputGesture="Ctrl+Z" Click="OnUndo" />
<MenuItem x:Name="RedoMenuItem" Header="_Redo" InputGesture="Ctrl+Y" Click="OnRedo" />
<Separator />
<!-- Into the place tool, not the system clipboard, as WinForms. -->
<MenuItem x:Name="CutMenuItem" Header="Cu_t" InputGesture="Ctrl+X" Click="OnCut" />
<MenuItem x:Name="CopyMenuItem" Header="_Copy" InputGesture="Ctrl+C" Click="OnCopy" />
<Separator />
<MenuItem x:Name="SelectAllMenuItem" Header="Select _All" InputGesture="Ctrl+A" Click="OnSelectAll" />
</MenuItem>
<MenuItem Header="_Nest">
+40
View File
@@ -89,6 +89,16 @@ namespace OpenNest.Avalonia
Command = new Command(() => OnExit(null, null)),
});
KeyBindings.Add(new KeyBinding
{
Gesture = new KeyGesture(Key.X, KeyModifiers.Control),
Command = new Command(() => OnCut(null, null)),
});
KeyBindings.Add(new KeyBinding
{
Gesture = new KeyGesture(Key.C, KeyModifiers.Control),
Command = new Command(() => OnCopy(null, null)),
});
KeyBindings.Add(new KeyBinding
{
Gesture = new KeyGesture(Key.A, KeyModifiers.Control),
Command = new Command(() => OnSelectAll(null, null)),
@@ -202,6 +212,7 @@ namespace OpenNest.Avalonia
private void AddView(NestTab tab)
{
var view = new NestView(tab);
view.PlateView.PlacementOrder = ReadClonePlacementOrder;
RestoreViewToggles(view);
view.ViewChanged += (_, _) => { if (view == ActiveView) UpdateStatus(); };
views[tab] = view;
@@ -307,6 +318,8 @@ namespace OpenNest.Avalonia
CloseAllMenuItem.IsEnabled = view != null;
SetOffsetIncrementMenuItem.IsEnabled = view != null;
SetRotationIncrementMenuItem.IsEnabled = view != null;
CutMenuItem.IsEnabled = view != null;
CopyMenuItem.IsEnabled = view != null;
UpdateExportCommands(view != null);
Title = view == null
? "OpenNest (Avalonia prototype)"
@@ -855,6 +868,33 @@ namespace OpenNest.Avalonia
private void OnSelectAll(object sender, RoutedEventArgs e) => ActiveView?.PlateView.SelectAll();
// Edit > Cut and Copy, as WinForms: the selected parts go to the place tool (not the
// system clipboard); Cut also removes them from the plate. The view keeps the keyboard,
// so Enter, arrows and Delete reach the tool after a menu click.
private void OnCut(object sender, RoutedEventArgs e)
{
if (ActiveView is { PlateView: { } canvas } view && canvas.CutSelection())
{
// Focusing the view would otherwise place a drawing picked up in the list.
view.CancelPickup();
canvas.Focus();
}
}
private void OnCopy(object sender, RoutedEventArgs e)
{
if (ActiveView is { PlateView: { } canvas } view && canvas.CopySelection())
{
view.CancelPickup();
canvas.Focus();
}
}
// Read at each click, as WinForms reads its setting, so a change in Options applies now.
private static Engine.Fill.SettleOrder ReadClonePlacementOrder() =>
DesktopOptions.Read(Data.UserSettingsFile.Read(Data.UserSettingsFile.DefaultPath))
.ClonePlacementOrder;
private void OnPreviousPlate(object sender, RoutedEventArgs e) => StepPlate(-1);
private void OnNextPlate(object sender, RoutedEventArgs e) => StepPlate(1);
+1
View File
@@ -11,6 +11,7 @@
</TabItem>
<TabItem Header="Drawings" FontSize="14" MinHeight="34">
<DataGrid x:Name="DrawingGrid" x:DataType="local:DrawingRow" IsReadOnly="True"
SelectionMode="Single"
FontSize="13" AutoGenerateColumns="False"
GridLinesVisibility="Horizontal" CanUserSortColumns="True">
<DataGrid.Columns>
+136 -2
View File
@@ -1,14 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.VisualTree;
using OpenNest.Avalonia.Controls;
using OpenNest.Desktop;
using OpenNest.Desktop.Interaction;
namespace OpenNest.Avalonia
{
public sealed record DrawingRow(string Name, int Nested, int Required);
public sealed record DrawingRow(string Name, int Nested, int Required, Drawing Drawing);
/// <summary>
/// One open nest: Plates and Drawings tabs on the left, the plate header and plate view on
@@ -35,6 +39,126 @@ namespace OpenNest.Avalonia
// Starts watching the last two plates (the tab already put the empty plate there).
plates.EnsureSentinel();
Refresh(0);
// Adding parts from the drawing list, as the WinForms nest window: a press picks a
// drawing up for the plate view, a drag drops one part on the plate.
DrawingGrid.AddHandler(PointerPressedEvent, OnDrawingPressed, RoutingStrategies.Tunnel,
handledEventsToo: true);
DrawingGrid.AddHandler(PointerMovedEvent, OnDrawingDragged, RoutingStrategies.Tunnel,
handledEventsToo: true);
DrawingGrid.AddHandler(PointerReleasedEvent, (_, _) => pressedDrawing = null,
RoutingStrategies.Tunnel, handledEventsToo: true);
Canvas.GotFocus += OnCanvasFocused;
DragDrop.SetAllowDrop(Canvas, true);
Canvas.AddHandler(DragDrop.DragEnterEvent, OnDrawingDragOver);
Canvas.AddHandler(DragDrop.DragOverEvent, OnDrawingDragOver);
Canvas.AddHandler(DragDrop.DropEvent, OnDrawingDrop);
}
/// <summary>The drag format carrying a <see cref="Drawing"/> from the list.</summary>
public const string DrawingFormat = "OpenNest.Drawing";
private readonly DrawingPickup pickup = new();
private Drawing pressedDrawing;
private Point pressPoint;
private static Drawing DrawingUnder(PointerEventArgs e) =>
(e.Source as Visual)?.FindAncestorOfType<DataGridRow>(includeSelf: true)
?.DataContext is DrawingRow row
? row.Drawing
: null;
// As the WinForms list: a single left press picks the drawing up (a drag can start from
// it); a double-click puts it down.
private void OnDrawingPressed(object sender, PointerPressedEventArgs e)
{
var point = e.GetCurrentPoint(DrawingGrid);
pressPoint = point.Position;
pressedDrawing = null;
if (!point.Properties.IsLeftButtonPressed)
return;
if (e.ClickCount != 1)
{
pickup.PutDown();
return;
}
pressedDrawing = DrawingUnder(e);
if (pressedDrawing != null)
pickup.PickUp();
}
// A press moved more than 3 pixels drags the drawing; a drop on the plate puts it down.
private async void OnDrawingDragged(object sender, PointerEventArgs e)
{
var drawing = pressedDrawing;
var point = e.GetCurrentPoint(DrawingGrid);
if (drawing == null || !point.Properties.IsLeftButtonPressed)
return;
var dx = point.Position.X - pressPoint.X;
var dy = point.Position.Y - pressPoint.Y;
if (dx * dx + dy * dy <= 9)
return;
pressedDrawing = null;
var data = new DataObject();
data.Set(DrawingFormat, drawing);
try
{
var result = await DragDrop.DoDragDrop(e, data, DragDropEffects.Copy);
if (result != DragDropEffects.None)
pickup.PutDown();
}
catch (Exception ex)
{
// A platform drag failure leaves the drawing picked up, as a cancelled drag does.
System.Diagnostics.Debug.WriteLine($"Drawing drag failed: {ex}");
}
}
/// <summary>
/// Puts a picked-up drawing down: Edit &gt; Cut and Copy start their own place tool and
/// then focus the view, which would otherwise swap in the picked drawing.
/// </summary>
public void CancelPickup()
{
pickup.PutDown();
pressedDrawing = null;
}
private void OnCanvasFocused(object sender, GotFocusEventArgs e)
{
var selected = (DrawingGrid.SelectedItem as DrawingRow)?.Drawing;
if (pickup.TakeOnPlateEnter(selected) is { } drawing)
Canvas.PlaceDrawing(drawing);
}
// Only this nest's drawings, and none while edits are locked (WinForms refuses the drop).
private Drawing DroppedDrawing(DragEventArgs e) =>
e.Data.Get(DrawingFormat) is Drawing drawing
&& Tab.Document.Nest.Drawings.Any(d => ReferenceEquals(d, drawing))
&& !Canvas.EditsLocked
? drawing
: null;
private void OnDrawingDragOver(object sender, DragEventArgs e)
{
if (!e.Data.Contains(DrawingFormat))
return;
e.DragEffects = DroppedDrawing(e) != null ? DragDropEffects.Copy : DragDropEffects.None;
e.Handled = true;
}
private void OnDrawingDrop(object sender, DragEventArgs e)
{
if (!e.Data.Contains(DrawingFormat))
return;
var drawing = DroppedDrawing(e);
var dropped = drawing != null
&& Canvas.DropDrawing(drawing, e.GetPosition(Canvas)) != null;
// Put down now, not when the drag returns: on X11 and macOS the pointer can enter the
// plate (and focus it) before the awaiting drag source resumes.
if (dropped)
pickup.PutDown();
e.DragEffects = dropped ? DragDropEffects.Copy : DragDropEffects.None;
e.Handled = true;
}
// Undo and Redo: puts the copy read back from the history in the document and shows it
@@ -49,6 +173,11 @@ namespace OpenNest.Avalonia
: (Array.Empty<int>(), -1);
// Read first: a throw here leaves the live nest in place, as the recorder expects.
var cutOffSettings = CutOffSettingsFor(restored);
// As WinForms (EditNestForm EndAction): a tool holds the old nest's parts, so it ends
// and Escape cannot bring it back.
Canvas.Tools.EndTool();
pickup.PutDown();
pressedDrawing = null;
Tab.Document.Nest = restored;
Canvas.CutOffSettings = cutOffSettings;
plates.Dispose();
@@ -103,10 +232,15 @@ namespace OpenNest.Avalonia
PlateList.SelectedIndex = nest.Plates.Count > 0
? System.Math.Clamp(selectIndex, 0, nest.Plates.Count - 1)
: -1;
// As the WinForms list: the selected drawing stays selected when the list is rebuilt,
// matched as WinForms matches it (by name), so it survives an Undo's new objects.
var selected = (DrawingGrid.SelectedItem as DrawingRow)?.Drawing;
DrawingGrid.ItemsSource = nest.Drawings
.Where(d => !d.IsCutOff)
.Select(d => new DrawingRow(d.Name, d.Quantity.Nested, d.Quantity.Required))
.Select(d => new DrawingRow(d.Name, d.Quantity.Nested, d.Quantity.Required, d))
.ToList();
DrawingGrid.SelectedItem = ((IEnumerable<DrawingRow>)DrawingGrid.ItemsSource)
.FirstOrDefault(row => Equals(row.Drawing, selected));
shownCounts = CountsText(nest);
ShowPlate();
}
+13
View File
@@ -0,0 +1,13 @@
namespace OpenNest.Bending
{
public static class BendMath
{
/// <summary>
/// The length of the neutral axis through a bend: the arc at the inside radius plus
/// <paramref name="kFactor"/> of the thickness.
/// </summary>
/// <param name="angle">The bend angle in radians.</param>
public static double Allowance(double angle, double insideRadius, double thickness, double kFactor) =>
angle * (insideRadius + kFactor * thickness);
}
}
+73
View File
@@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using OpenNest.Geometry;
namespace OpenNest.Shapes
{
/// <summary>
/// The flat blank of a formed angle: two legs and one 90° bend, sized from the outside
/// dimensions with the bend allowance at <see cref="KFactor"/>.
/// </summary>
public class AngleShape : ShapeDefinition
{
public double OutsideWidth { get; set; }
public double OutsideHeight { get; set; }
public double Thickness { get; set; }
public double InsideRadius { get; set; }
[Unitless]
[DisplayName("K-Factor")]
public double KFactor { get; set; }
public double Length { get; set; }
public double InsideWidth => OutsideWidth - Thickness;
public double InsideHeight => OutsideHeight - Thickness;
public double BendAllowance => SheetMetal.BendAllowance(InsideRadius, Thickness, KFactor);
/// <summary>The developed width of the blank: both legs' flats plus the bend.</summary>
public double FlatLength => InsideHeight - InsideRadius + InsideWidth - InsideRadius + BendAllowance;
/// <summary>The bend line's distance from the edge of the shorter leg.</summary>
public double BendLineDim => System.Math.Min(InsideWidth, InsideHeight) - InsideRadius + BendAllowance / 2;
public override string GenerateName() =>
$"Angle {Dim(OutsideWidth)}x{Dim(OutsideHeight)}x{Dim(Thickness)} x {Dim(Length)}";
public override void SetPreviewDefaults()
{
OutsideWidth = 4;
OutsideHeight = 2;
Thickness = 0.125;
InsideRadius = 0.3125;
KFactor = 0.42;
Length = 12;
}
public override IReadOnlyList<ShapeDimension> GetDimensions() =>
new[]
{
ShapeDimension.Linear(nameof(Length), new Vector(0, 0), new Vector(Length, 0), ShapeDimension.Down),
};
public override ShapeSideView GetSideView() =>
SheetMetal.Section(false, OutsideWidth, OutsideHeight, Thickness, InsideRadius,
nameof(OutsideWidth), nameof(OutsideHeight), nameof(Thickness), nameof(InsideRadius));
public override Drawing GetDrawing()
{
SheetMetal.Validate(Thickness, Length, KFactor);
if (!(InsideHeight - InsideRadius > 0) || !(InsideWidth - InsideRadius > 0))
throw new InvalidOperationException("Each leg must be longer than the thickness plus the inside radius.");
// The shorter leg runs along the bottom edge, so the bend line sits BendLineDim up.
var entities = SheetMetal.Entities(Length, FlatLength, new[] { BendLineDim }, InsideRadius, out var bends);
var drawing = CreateDrawing(entities);
drawing.Bends.AddRange(bends);
return drawing;
}
}
}
+77
View File
@@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using OpenNest.Geometry;
namespace OpenNest.Shapes
{
/// <summary>
/// The flat blank of a formed channel: two equal sides, a bottom and two 90° bends, sized
/// from the outside dimensions with the bend allowance at <see cref="KFactor"/>.
/// </summary>
public class ChannelShape : ShapeDefinition
{
public double OutsideWidth { get; set; }
public double OutsideHeight { get; set; }
public double Thickness { get; set; }
public double InsideRadius { get; set; }
[Unitless]
[DisplayName("K-Factor")]
public double KFactor { get; set; }
public double Length { get; set; }
public double InsideWidth => OutsideWidth - Thickness * 2;
public double InsideHeight => OutsideHeight - Thickness;
public double BendAllowance => SheetMetal.BendAllowance(InsideRadius, Thickness, KFactor);
/// <summary>The developed width of the blank: both sides' and the bottom's flats plus the bends.</summary>
public double FlatLength =>
(InsideHeight - InsideRadius) * 2 + InsideWidth - InsideRadius * 2 + BendAllowance * 2;
/// <summary>Each bend line's distance from its side's edge.</summary>
public double BendLineDim => InsideHeight - InsideRadius + BendAllowance / 2;
public override string GenerateName() =>
$"Channel {Dim(OutsideWidth)}x{Dim(OutsideHeight)}x{Dim(Thickness)} x {Dim(Length)}";
public override void SetPreviewDefaults()
{
OutsideWidth = 4;
OutsideHeight = 2;
Thickness = 0.125;
InsideRadius = 0.3125;
KFactor = 0.42;
Length = 12;
}
public override IReadOnlyList<ShapeDimension> GetDimensions() =>
new[]
{
ShapeDimension.Linear(nameof(Length), new Vector(0, 0), new Vector(Length, 0), ShapeDimension.Down),
};
public override ShapeSideView GetSideView() =>
SheetMetal.Section(true, OutsideWidth, OutsideHeight, Thickness, InsideRadius,
nameof(OutsideWidth), nameof(OutsideHeight), nameof(Thickness), nameof(InsideRadius));
public override Drawing GetDrawing()
{
SheetMetal.Validate(Thickness, Length, KFactor);
if (!(InsideHeight - InsideRadius > 0))
throw new InvalidOperationException("The sides must be longer than the thickness plus the inside radius.");
if (InsideWidth - InsideRadius * 2 < 0)
throw new InvalidOperationException("The width must fit both sides' thickness and inside radius.");
var flat = FlatLength;
var bendLine = BendLineDim;
var entities = SheetMetal.Entities(Length, flat, new[] { bendLine, flat - bendLine }, InsideRadius, out var bends);
var drawing = CreateDrawing(entities);
drawing.Bends.AddRange(bends);
return drawing;
}
}
}
+72
View File
@@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using OpenNest.Geometry;
namespace OpenNest.Shapes
{
/// <summary>
/// The flat blank of a plate rolled into a cylinder: <see cref="Length"/> by the
/// circumference of the neutral axis, <see cref="KFactor"/> of the thickness out from the
/// inside diameter.
/// </summary>
public class RolledPlateShape : ShapeDefinition
{
public double InsideDiameter { get; set; }
public double Thickness { get; set; }
[Unitless]
[DisplayName("K-Factor")]
public double KFactor { get; set; }
public double Length { get; set; }
public double InsideRadius => InsideDiameter / 2;
public double OutsideDiameter => InsideDiameter + Thickness * 2;
/// <summary>The developed width of the blank: the neutral axis's circumference.</summary>
public double FlatLength => System.Math.PI * 2 * (InsideRadius + Thickness * KFactor);
public override string GenerateName() =>
$"Rolled Plate {Dim(InsideDiameter)} ID x {Dim(Thickness)} x {Dim(Length)}";
public override void SetPreviewDefaults()
{
InsideDiameter = 10;
Thickness = 0.1875;
KFactor = 0.42;
Length = 12;
}
public override IReadOnlyList<ShapeDimension> GetDimensions() =>
new[]
{
ShapeDimension.Linear(nameof(Length), new Vector(0, 0), new Vector(Length, 0), ShapeDimension.Down),
};
/// <summary>The rolled ring, with its inside diameter across the middle and a leader from its wall to the thickness.</summary>
public override ShapeSideView GetSideView()
{
var inside = InsideRadius;
var outside = InsideRadius + Thickness;
return new ShapeSideView(
new Entity[] { new Circle(0, 0, outside), new Circle(0, 0, inside) },
new[]
{
ShapeDimension.Inline(nameof(InsideDiameter), new Vector(-inside, 0), new Vector(inside, 0), "Ø"),
ShapeDimension.Leader(nameof(Thickness), new Vector(outside * System.Math.Sqrt(0.5), outside * System.Math.Sqrt(0.5)), new Vector(1, 1)),
});
}
public override Drawing GetDrawing()
{
SheetMetal.Validate(Thickness, Length, KFactor);
if (!(InsideDiameter > 0))
throw new InvalidOperationException("The inside diameter must be more than zero.");
var entities = SheetMetal.Entities(Length, FlatLength, Array.Empty<double>(), 0, out _);
return CreateDrawing(entities);
}
}
}
+6
View File
@@ -42,6 +42,12 @@ namespace OpenNest.Shapes
/// </summary>
public virtual IReadOnlyList<ShapeDimension> GetDimensions() => Array.Empty<ShapeDimension>();
/// <summary>
/// A sheet metal part's cross-section that the Shape Library draws beside the flat blank,
/// with the dimensions of parameters the blank cannot show; null for a flat shape.
/// </summary>
public virtual ShapeSideView GetSideView() => null;
public static List<T> LoadFromJson<T>(string path)
where T : ShapeDefinition
{
+24
View File
@@ -0,0 +1,24 @@
using System.Collections.Generic;
using OpenNest.Geometry;
namespace OpenNest.Shapes
{
/// <summary>
/// A sheet metal part's cross-section, which the Shape Library draws beside the flat blank with
/// its own dimensions. Annotation only: it never affects the drawing.
/// </summary>
public sealed class ShapeSideView
{
public ShapeSideView(IReadOnlyList<Entity> entities, IReadOnlyList<ShapeDimension> dimensions)
{
Entities = entities;
Dimensions = dimensions;
}
/// <summary>The section's closed outlines, in the view's own coordinates.</summary>
public IReadOnlyList<Entity> Entities { get; }
/// <summary>The section's dimensions, in the same coordinates as <see cref="Entities"/>.</summary>
public IReadOnlyList<ShapeDimension> Dimensions { get; }
}
}
+119
View File
@@ -0,0 +1,119 @@
using System;
using System.Collections.Generic;
using System.Linq;
using OpenNest.Bending;
using OpenNest.Geometry;
namespace OpenNest.Shapes
{
/// <summary>
/// Flat blanks and sections for the sheet metal shapes: parts bent or rolled along their
/// length, cut as a rectangle <c>length</c> along X by the developed width along Y.
/// </summary>
internal static class SheetMetal
{
public const double BendAngle = 90;
public static void Validate(double thickness, double length, double kFactor)
{
if (!(thickness > 0))
throw new InvalidOperationException("The thickness must be more than zero.");
if (!(length > 0))
throw new InvalidOperationException("The length must be more than zero.");
if (!(kFactor >= 0 && kFactor <= 1))
throw new InvalidOperationException("The K-factor must be from 0 to 1.");
}
public static double BendAllowance(double insideRadius, double thickness, double kFactor) =>
BendMath.Allowance(Math.Angle.ToRadians(BendAngle), insideRadius, thickness, kFactor);
/// <summary>The blank's outline, with a 90° up bend across it, etched, at each bend line.</summary>
/// <param name="bendLines">Each bend line's distance from the blank's bottom edge.</param>
public static List<Entity> Entities(double length, double width, IReadOnlyList<double> bendLines, double insideRadius, out List<Bend> bends)
{
var entities = new List<Entity>
{
new Line(0, 0, length, 0),
new Line(length, 0, length, width),
new Line(length, width, 0, width),
new Line(0, width, 0, 0),
};
bends = bendLines
.Select(y => new Bend
{
StartPoint = new Vector(0, y),
EndPoint = new Vector(length, y),
Direction = BendDirection.Up,
Angle = BendAngle,
Radius = insideRadius,
})
.ToList();
foreach (var bend in bends)
entities.AddRange(bend.GetEtchEntities());
return entities;
}
/// <summary>
/// The section of a part bent up 90° at its right end (an angle, "_|") or at both ends
/// (a channel, "U"): the bottom on Y = 0 from X = 0 to <paramref name="outsideWidth"/>,
/// the sides up to <paramref name="outsideHeight"/>, every bend at
/// <paramref name="insideRadius"/>. Dimensioned with the outside sizes, the thickness
/// across the right side's top and the inside radius of its bend.
/// </summary>
public static ShapeSideView Section(
bool bothSides, double outsideWidth, double outsideHeight, double thickness, double insideRadius,
string widthProperty, string heightProperty, string thicknessProperty, string radiusProperty)
{
const double quarter = System.Math.PI / 2;
var outsideRadius = insideRadius + thickness;
var right = new Vector(outsideWidth - outsideRadius, outsideRadius);
var left = new Vector(outsideRadius, outsideRadius);
var w = outsideWidth;
var h = outsideHeight;
var t = thickness;
// Round the outside, counterclockwise from the bottom's left end, then back inside
// (a reversed arc runs clockwise from its start angle to its end angle).
var entities = new List<Entity>();
if (bothSides)
{
entities.Add(new Line(0, h, 0, outsideRadius));
entities.Add(new Arc(left, outsideRadius, 2 * quarter, 3 * quarter));
entities.Add(new Line(outsideRadius, 0, right.X, 0));
}
else
{
entities.Add(new Line(0, 0, right.X, 0));
}
entities.Add(new Arc(right, outsideRadius, 3 * quarter, 4 * quarter));
entities.Add(new Line(w, outsideRadius, w, h));
entities.Add(new Line(w, h, w - t, h));
entities.Add(new Line(w - t, h, w - t, outsideRadius));
entities.Add(new Arc(right, insideRadius, 0, 3 * quarter, true));
if (bothSides)
{
entities.Add(new Line(right.X, t, outsideRadius, t));
entities.Add(new Arc(left, insideRadius, 3 * quarter, 2 * quarter, true));
entities.Add(new Line(t, outsideRadius, t, h));
entities.Add(new Line(t, h, 0, h));
}
else
{
entities.Add(new Line(right.X, t, 0, t));
entities.Add(new Line(0, t, 0, 0));
}
var dimensions = new[]
{
ShapeDimension.Linear(widthProperty, new Vector(0, 0), new Vector(w, 0), ShapeDimension.Down),
ShapeDimension.Linear(heightProperty, new Vector(w, 0), new Vector(w, h), ShapeDimension.Right),
ShapeDimension.Linear(thicknessProperty, new Vector(w - t, h), new Vector(w, h), ShapeDimension.Up),
ShapeDimension.ArcLeader(radiusProperty, right, insideRadius, 3 * quarter, 4 * quarter, "R"),
};
return new ShapeSideView(entities, dimensions);
}
}
}
+13
View File
@@ -0,0 +1,13 @@
using System;
namespace OpenNest.Shapes
{
/// <summary>
/// Marks a <see cref="double"/> shape parameter that is a plain number, such as a K-factor,
/// rather than a length: the Shape Library shows it without fractions or an inch mark.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public sealed class UnitlessAttribute : Attribute
{
}
}
@@ -0,0 +1,177 @@
using System.Linq;
using OpenNest.Desktop.Interaction;
using OpenNest.Engine.Fill;
using OpenNest.Geometry;
namespace OpenNest.Desktop.Tests.Interaction;
public class DrawingPlacementTests
{
private readonly Plate plate = InteractionFixtures.Plate();
private readonly TestToolHost host;
private readonly Drawing drawing = new("dropped", InteractionFixtures.Rect(10, 6));
public DrawingPlacementTests()
{
host = new TestToolHost(plate);
}
private static SettleOrder Order() => SettleOrder.ClosestToCorner;
[Fact]
public void A_drop_adds_one_part_centred_on_the_drop_point_as_one_step()
{
var recorder = host.RecordHistory();
var count = plate.Parts.Count;
var part = DrawingPlacement.AddPart(host, drawing, new Vector(60, 50));
Assert.NotNull(part);
Assert.Equal(count + 1, plate.Parts.Count);
Assert.Same(part, plate.Parts[^1]);
Assert.Same(drawing, part.BaseDrawing);
Assert.True(part.BoundingBox.Center.DistanceTo(new Vector(60, 50)) < 1e-9,
$"centred at {part.BoundingBox.Center}");
Assert.Equal(new[] { "Add Part" }, host.ChangeLabels);
Assert.Equal(1, recorder.History.UndoCount);
}
[Fact]
public void A_drop_keeps_the_cut_offs_as_they_are()
{
var crossing = new Part(plate.Parts[1].BaseDrawing, new Vector(75, 40));
plate.Parts.Add(crossing);
plate.RegenerateCutOffs(host.CutOffSettings);
var strokes = PlateEditsTests.CutOffStrokes(plate);
host.ThrowOnCutOffSettings = true;
DrawingPlacement.AddPart(host, drawing, new Vector(20, 80));
Assert.Equal(strokes, PlateEditsTests.CutOffStrokes(plate));
}
[Fact]
public void A_drop_does_nothing_while_locked()
{
var count = plate.Parts.Count;
host.EditsLocked = true;
Assert.Null(DrawingPlacement.AddPart(host, drawing, new Vector(60, 50)));
Assert.Equal(count, plate.Parts.Count);
Assert.Empty(host.ChangeLabels);
}
[Fact]
public void A_drop_does_nothing_without_a_plate()
{
var count = plate.Parts.Count;
host.Plate = null;
Assert.Null(DrawingPlacement.AddPart(host, drawing, new Vector(60, 50)));
Assert.Equal(count, plate.Parts.Count);
Assert.Empty(host.ChangeLabels);
}
[Fact]
public void Undo_takes_a_dropped_part_off_and_redo_puts_it_back()
{
var recorder = host.RecordHistory();
// The list offers the nest's own drawings.
recorder.Document.Nest.Drawings.Add(drawing);
recorder.Reset();
static int Real(Plate p) => p.Parts.Count(part => !part.BaseDrawing.IsCutOff);
DrawingPlacement.AddPart(host, drawing, new Vector(60, 50));
recorder.Undo();
var undone = recorder.Document.Nest.Plates[0];
Assert.DoesNotContain(undone.Parts, p => p.BaseDrawing.Name == "dropped");
var count = Real(undone);
recorder.Redo();
var restored = recorder.Document.Nest.Plates[0];
Assert.Equal(count + 1, Real(restored));
var dropped = restored.Parts.Single(p => p.BaseDrawing.Name == "dropped");
Assert.True(dropped.BoundingBox.Center.DistanceTo(new Vector(60, 50)) < 1e-9);
}
[Fact]
public void An_off_centre_drawing_is_centred_on_its_bounding_box()
{
// A drawing whose program does not start at its bounding box's corner.
var offset = new Drawing("offset", InteractionFixtures.Rect(8, 4, 3, 7));
var part = DrawingPlacement.AddPart(host, offset, new Vector(40, 30));
Assert.True(part.BoundingBox.Center.DistanceTo(new Vector(40, 30)) < 1e-9,
$"centred at {part.BoundingBox.Center}");
}
[Fact]
public void The_place_tool_for_a_drawing_places_a_new_part_of_it()
{
var tool = DrawingPlacement.CreatePlaceTool(host, drawing, Order);
host.Tools.SetTool(tool);
var count = plate.Parts.Count;
tool.PointerMoved(host.At(30, 60));
tool.Apply(ToolModifiers.None);
Assert.Single(tool.Previews);
Assert.Equal(count + 1, plate.Parts.Count);
Assert.Same(drawing, plate.Parts[^1].BaseDrawing);
Assert.True(plate.Parts[^1].BoundingBox.Location.DistanceTo(new Vector(30, 60)) < 1e-9);
Assert.Equal(new[] { "Add Part" }, host.ChangeLabels);
}
[Fact]
public void Delete_with_a_drawing_tool_removes_nothing()
{
var tool = DrawingPlacement.CreatePlaceTool(host, drawing, Order);
host.Tools.SetTool(tool);
var count = plate.Parts.Count;
var recorder = host.RecordHistory();
tool.DeleteSources();
Assert.Equal(count, plate.Parts.Count);
Assert.Equal(0, recorder.History.UndoCount);
}
[Fact]
public void A_pick_up_is_taken_once_by_the_plate()
{
var pickup = new DrawingPickup();
Assert.Null(pickup.TakeOnPlateEnter(drawing));
pickup.PickUp();
Assert.Same(drawing, pickup.TakeOnPlateEnter(drawing));
Assert.Null(pickup.TakeOnPlateEnter(drawing));
}
[Fact]
public void A_pick_up_with_nothing_selected_stays_armed()
{
var pickup = new DrawingPickup();
pickup.PickUp();
Assert.Null(pickup.TakeOnPlateEnter(null));
Assert.True(pickup.IsArmed);
Assert.Same(drawing, pickup.TakeOnPlateEnter(drawing));
}
[Fact]
public void Putting_down_disarms_the_pick_up()
{
var pickup = new DrawingPickup();
pickup.PickUp();
pickup.PutDown();
Assert.False(pickup.IsArmed);
Assert.Null(pickup.TakeOnPlateEnter(drawing));
}
}
@@ -0,0 +1,548 @@
using System.Collections.Generic;
using System.Linq;
using OpenNest.CNC;
using OpenNest.CutOffs;
using OpenNest.Desktop.Interaction;
using OpenNest.Engine.Fill;
using OpenNest.Geometry;
namespace OpenNest.Desktop.Tests.Interaction;
public class PlaceToolTests
{
private readonly Plate plate = InteractionFixtures.Plate();
private readonly TestToolHost host;
private readonly PlateEdits edits;
private int orderReads;
public PlaceToolTests()
{
host = new TestToolHost(plate);
edits = new PlateEdits(host) { Tools = host.Tools };
}
private SettleOrder Order()
{
orderReads++;
return SettleOrder.ClosestToCorner;
}
private static void AssertAt(Vector expected, Vector actual) =>
Assert.True(expected.DistanceTo(actual) < 1e-9, $"expected {expected}, was {actual}");
private List<Part> RealParts() => plate.Parts.Where(p => !p.BaseDrawing.IsCutOff).ToList();
private PlaceTool Copy(params Part[] parts)
{
host.Selection.Clear();
host.Selection.Select(parts);
return PlateClipboard.Copy(host, host.Tools, Order);
}
private static Part Triangle(double x, double y)
{
var program = new Program();
program.Codes.Add(new RapidMove(new Vector(0, 0)));
program.Codes.Add(new LinearMove(new Vector(40, 0)));
program.Codes.Add(new LinearMove(new Vector(0, 40)));
program.Codes.Add(new LinearMove(new Vector(0, 0)));
return new Part(new Drawing("triangle", program), new Vector(x, y));
}
private static Part Square(double size, double x, double y) =>
new(new Drawing("square", InteractionFixtures.Rect(size, size)), new Vector(x, y));
[Fact]
public void Previews_follow_the_pointer_by_their_lower_left_corner()
{
var tool = Copy(plate.Parts[2]);
Assert.Same(tool, host.Tools.Current);
Assert.Equal("Clone Parts", host.Tools.Status);
Assert.True(tool.PointerMoved(host.At(30, 60, ToolButton.None)));
Assert.Equal(2, tool.Previews.Count);
AssertAt(new Vector(30, 60), tool.Previews.GetBoundingBox().Location);
AssertAt(new Vector(30, 60), tool.Previews[0].Location);
AssertAt(new Vector(40.05, 60), tool.Previews[1].Location);
AssertAt(new Vector(40, 0), plate.Parts[2].Location);
Assert.True(host.Invalidations > 0);
}
[Fact]
public void A_move_to_the_same_screen_point_keeps_a_nudge()
{
var tool = Copy(plate.Parts[1]);
tool.PointerMoved(host.At(30, 60));
edits.NudgeBy(5, 0);
AssertAt(new Vector(35, 60), tool.Previews[0].Location);
tool.PointerMoved(host.At(30, 60));
AssertAt(new Vector(35, 60), tool.Previews[0].Location);
tool.PointerMoved(host.At(31, 60));
AssertAt(new Vector(31, 60), tool.Previews[0].Location);
}
[Fact]
public void A_click_adds_copies_and_one_undo_removes_them()
{
var recorder = host.RecordHistory();
var source = plate.Parts[1];
var tool = Copy(source);
var count = plate.Parts.Count;
tool.PointerMoved(host.At(30, 60));
Assert.True(tool.PointerPressed(host.At(30, 60)));
tool.PointerMoved(host.At(60, 60));
Assert.True(tool.PointerPressed(host.At(60, 60)));
Assert.Equal(count + 2, plate.Parts.Count);
AssertAt(new Vector(20, 0), source.Location);
AssertAt(new Vector(30, 60), plate.Parts[count].Location);
AssertAt(new Vector(60, 60), plate.Parts[count + 1].Location);
Assert.DoesNotContain(tool.Previews[0], plate.Parts);
Assert.Equal(new[] { "Add Part", "Add Part" }, host.ChangeLabels);
Assert.Same(tool, host.Tools.Current);
recorder.Undo();
Assert.Equal(count + 1, recorder.Document.Nest.Plates[0].Parts.Count);
}
[Fact]
public void Placing_several_parts_is_labelled_add_parts()
{
var tool = Copy(plate.Parts[1], plate.Parts[4]);
tool.PointerMoved(host.At(30, 60));
tool.Apply(ToolModifiers.None);
Assert.Equal(new[] { "Add Parts" }, host.ChangeLabels);
}
[Fact]
public void Other_buttons_do_not_place()
{
var tool = Copy(plate.Parts[1]);
var count = plate.Parts.Count;
Assert.False(tool.PointerPressed(host.At(30, 60, ToolButton.Right)));
Assert.False(tool.PointerPressed(host.At(30, 60, ToolButton.Middle)));
Assert.Equal(count, plate.Parts.Count);
}
[Theory]
[InlineData(1, false, false)]
[InlineData(2, true, false)]
[InlineData(3, true, true)]
[InlineData(4, false, true)]
public void Shift_settles_toward_the_quadrant_corner(int quadrant, bool right, bool up)
{
var empty = new Plate(new Size(100, 100)) { Quadrant = quadrant };
var emptyHost = new TestToolHost(empty);
var tool = new PlaceTool(emptyHost, new[] { Square(10, 0, 0) }, Order);
var center = empty.WorkArea().Center;
tool.PointerMoved(emptyHost.At(center.X, center.Y));
tool.Apply(ToolModifiers.Shift);
var area = empty.WorkArea();
var box = empty.Parts.Single().BoundingBox;
Assert.Equal(right ? area.Right : area.Left, right ? box.Right : box.Left, 9);
Assert.Equal(up ? area.Top : area.Bottom, up ? box.Top : box.Bottom, 9);
}
[Fact]
public void Shift_settles_on_geometry_and_ctrl_on_bounding_boxes()
{
var shiftLocation = SettleBesideTriangle(ToolModifiers.Shift, out var shiftPlate);
var ctrlLocation = SettleBesideTriangle(ToolModifiers.Control, out _);
var bothLocation = SettleBesideTriangle(ToolModifiers.Shift | ToolModifiers.Control, out _);
// Pushed left onto the hypotenuse x + y = 40, inside the triangle's box but clear of it.
AssertAt(new Vector(10, 30), shiftLocation);
// Boxes only: it starts inside the triangle's box, so it never nests into the shape.
AssertAt(new Vector(30, 30), ctrlLocation);
AssertAt(shiftLocation, bothLocation);
Assert.Equal(2, shiftPlate.Parts.Count);
Assert.Equal(3, orderReads);
}
private Vector SettleBesideTriangle(ToolModifiers modifiers, out Plate triangles)
{
triangles = new Plate(new Size(100, 100));
triangles.Parts.Add(Triangle(0, 0));
var trianglesHost = new TestToolHost(triangles);
var tool = new PlaceTool(trianglesHost, new[] { Square(10, 0, 0) }, Order);
tool.PointerMoved(trianglesHost.At(30, 30));
tool.Apply(modifiers);
AssertAt(triangles.Parts[1].Location, tool.Previews[0].Location);
return triangles.Parts[1].Location;
}
[Fact]
public void The_placement_order_is_read_at_each_settling_click()
{
var tool = Copy(plate.Parts[1]);
Assert.Equal(0, orderReads);
tool.PointerMoved(host.At(30, 60));
tool.Apply(ToolModifiers.None);
Assert.Equal(0, orderReads);
tool.Apply(ToolModifiers.Shift);
tool.Apply(ToolModifiers.Control);
Assert.Equal(2, orderReads);
}
[Fact]
public void Copied_common_lines_join_the_placed_copies_with_the_source_kerf()
{
var tool = Copy(plate.Parts[2]);
tool.PointerMoved(host.At(20, 60));
tool.Apply(ToolModifiers.None);
var placed = plate.Parts.Skip(plate.Parts.Count - 2).ToList();
var group = plate.CommonLineGroupOf(placed[0]);
Assert.NotNull(group);
Assert.True(group.Contains(placed[1]));
Assert.Equal(0.05, group.Kerf, 12);
Assert.Equal(2, plate.CommonLines.Count);
}
[Fact]
public void A_click_rebuilds_the_cut_offs_around_the_copy()
{
var before = PlateEditsTests.CutOffStrokes(plate);
var tool = Copy(plate.Parts[1]);
tool.PointerMoved(host.At(75, 40));
tool.Apply(ToolModifiers.None);
Assert.NotEqual(before, PlateEditsTests.CutOffStrokes(plate));
var twin = InteractionFixtures.Plate();
twin.Parts.Add(new Part(plate.Parts[1].BaseDrawing, new Vector(75, 40)));
twin.RegenerateCutOffs(new CutOffSettings());
Assert.Equal(PlateEditsTests.CutOffStrokes(twin), PlateEditsTests.CutOffStrokes(plate));
}
[Fact]
public void Delete_removes_the_sources_and_selected_parts_as_one_step()
{
var recorder = host.RecordHistory();
var source = plate.Parts[1];
var other = plate.Parts[4];
var tool = Copy(source);
host.Selection.Select(other);
edits.Delete();
Assert.DoesNotContain(source, plate.Parts);
Assert.DoesNotContain(other, plate.Parts);
Assert.Equal(3, RealParts().Count);
Assert.True(host.Selection.IsEmpty);
Assert.Equal(new[] { "Delete" }, host.ChangeLabels);
Assert.Equal(1, recorder.History.UndoCount);
Assert.Single(tool.Previews);
Assert.Same(tool, host.Tools.Current);
}
[Fact]
public void Delete_after_a_cut_records_nothing()
{
var recorder = host.RecordHistory();
host.Selection.Select(plate.Parts[1]);
var tool = PlateClipboard.Cut(host, host.Tools, Order);
Assert.Equal(1, recorder.History.UndoCount);
tool.DeleteSources();
Assert.Equal(1, recorder.History.UndoCount);
Assert.Equal("Cut", recorder.History.UndoLabel);
}
[Fact]
public void Delete_with_no_source_left_keeps_the_cut_offs()
{
var crossing = new Part(plate.Parts[1].BaseDrawing, new Vector(75, 40));
plate.Parts.Add(crossing);
plate.RegenerateCutOffs(host.CutOffSettings);
host.Selection.Select(crossing);
var tool = PlateClipboard.Cut(host, host.Tools, Order);
var strokes = PlateEditsTests.CutOffStrokes(plate);
// A rebuild now would give the cut-offs new programs: an unrecorded change.
host.ThrowOnCutOffSettings = true;
tool.DeleteSources();
Assert.Equal(strokes, PlateEditsTests.CutOffStrokes(plate));
}
[Fact]
public void Delete_rebuilds_the_cut_offs()
{
var crossing = new Part(plate.Parts[1].BaseDrawing, new Vector(75, 40));
var expected = PlateEditsTests.CutOffStrokes(plate);
plate.Parts.Add(crossing);
plate.RegenerateCutOffs(host.CutOffSettings);
var tool = Copy(crossing);
tool.DeleteSources();
Assert.Equal(expected, PlateEditsTests.CutOffStrokes(plate));
}
[Fact]
public void Cut_removes_the_sources_in_one_step_without_rebuilding_cut_offs()
{
var recorder = host.RecordHistory();
var crossing = new Part(plate.Parts[1].BaseDrawing, new Vector(75, 40));
plate.Parts.Add(crossing);
plate.RegenerateCutOffs(host.CutOffSettings);
var strokes = PlateEditsTests.CutOffStrokes(plate);
recorder.Reset();
host.Selection.Select(crossing);
host.Selection.Select(plate.Parts[2]);
var tool = PlateClipboard.Cut(host, host.Tools, Order);
Assert.Same(tool, host.Tools.Current);
Assert.Equal(3, tool.Previews.Count);
Assert.DoesNotContain(crossing, plate.Parts);
Assert.Equal(3, RealParts().Count);
Assert.Equal(strokes, PlateEditsTests.CutOffStrokes(plate));
Assert.True(host.Selection.IsEmpty);
Assert.Equal(new[] { "Cut" }, host.ChangeLabels);
Assert.Equal(1, recorder.History.UndoCount);
// The cut group is joined again among its copies.
tool.PointerMoved(host.At(10, 60));
tool.Apply(ToolModifiers.None);
Assert.Single(plate.CommonLines);
recorder.Undo();
recorder.Undo();
Assert.Equal(6, recorder.Document.Nest.Plates[0].Parts.Count(p => !p.BaseDrawing.IsCutOff));
}
[Fact]
public void Copy_and_cut_need_selected_parts_on_the_plate()
{
Assert.Null(PlateClipboard.Copy(host, host.Tools, Order));
Assert.Null(PlateClipboard.Cut(host, host.Tools, Order));
host.Selection.Select(plate.Parts[1]);
plate.Parts.RemoveAt(1);
Assert.Null(PlateClipboard.Cut(host, host.Tools, Order));
Assert.IsType<SelectTool>(host.Tools.Current);
Assert.Empty(host.ChangeLabels);
}
[Fact]
public void Copy_keeps_the_sources_on_the_plate()
{
var count = plate.Parts.Count;
var tool = Copy(plate.Parts[1], plate.Parts[4]);
Assert.Equal(count, plate.Parts.Count);
Assert.Equal(2, tool.Previews.Count);
Assert.Empty(host.ChangeLabels);
}
[Fact]
public void Edits_move_the_previews_without_an_undo_step()
{
var recorder = host.RecordHistory();
var tool = Copy(plate.Parts[1]);
tool.PointerMoved(host.At(30, 60));
var before = RealParts().Select(p => p.Location).ToList();
var strokes = PlateEditsTests.CutOffStrokes(plate);
Assert.True(edits.HasPartsToEdit);
edits.Nudge(PushDirection.Right);
AssertAt(new Vector(40, 60), tool.Previews[0].Location);
edits.Push(PushDirection.Down);
AssertAt(new Vector(40, 10), tool.Previews[0].Location);
edits.Step(PushDirection.Up);
// A step adds a hair over the part's height.
Assert.True(new Vector(40, 20).DistanceTo(tool.Previews[0].Location) < 1e-4);
tool.Previews[0].Offset(new Vector(36, 0));
// Rebuilding cut-offs would throw: previews are not on the plate.
host.ThrowOnCutOffSettings = true;
edits.RotateQuarterTurn();
edits.RotateByWheel(1, fine: false);
Assert.True(new Vector(76, 20).DistanceTo(tool.Previews[0].BoundingBox.Location) < 1e-4);
Assert.NotEqual(0, tool.Previews[0].Rotation, 6);
Assert.Equal(before, RealParts().Select(p => p.Location).ToList());
Assert.Equal(strokes, PlateEditsTests.CutOffStrokes(plate));
Assert.Empty(host.ChangeLabels);
Assert.False(recorder.CanUndo);
}
[Fact]
public void Without_tools_or_a_place_tool_edits_move_the_selection()
{
Assert.False(edits.HasPartsToEdit);
host.Selection.Select(plate.Parts[4]);
Assert.True(edits.HasPartsToEdit);
edits.NudgeBy(1, 0);
AssertAt(new Vector(21, 20), plate.Parts[4].Location);
Assert.Equal(new[] { "Nudge" }, host.ChangeLabels);
}
[Fact]
public void Locked_edits_refuse_placing_deleting_cutting_and_copying()
{
var tool = Copy(plate.Parts[1]);
tool.PointerMoved(host.At(30, 60));
var count = plate.Parts.Count;
host.Selection.Select(plate.Parts[4]);
host.EditsLocked = true;
Assert.False(tool.PointerPressed(host.At(30, 60)));
// WinForms raises no mouse move while locked, so the copy stays put.
Assert.False(tool.PointerMoved(host.At(50, 20)));
tool.Apply(ToolModifiers.None);
tool.DeleteSources();
edits.Delete();
edits.NudgeBy(5, 0);
Assert.Null(PlateClipboard.Copy(host, host.Tools, Order));
Assert.Null(PlateClipboard.Cut(host, host.Tools, Order));
Assert.Equal(count, plate.Parts.Count);
AssertAt(new Vector(30, 60), tool.Previews[0].Location);
Assert.Same(tool, host.Tools.Current);
Assert.Empty(host.ChangeLabels);
}
[Fact]
public void Without_a_plate_a_click_does_nothing()
{
var tool = Copy(plate.Parts[1]);
host.Plate = null;
Assert.False(tool.PointerPressed(host.At(30, 60)));
tool.Apply(ToolModifiers.None);
tool.DeleteSources();
Assert.Empty(host.ChangeLabels);
}
[Fact]
public void The_tool_survives_a_plate_change_with_its_previews()
{
var tool = Copy(plate.Parts[2]);
var other = new Plate(new Size(100, 100));
host.Plate = other;
host.Selection.Plate = other;
host.Tools.OnPlateChanged();
Assert.Same(tool, host.Tools.Current);
Assert.Equal(2, tool.Previews.Count);
tool.PointerMoved(host.At(10, 10));
tool.Apply(ToolModifiers.None);
Assert.Equal(2, other.Parts.Count);
Assert.Single(other.CommonLines);
}
[Fact]
public void A_failing_settle_opens_no_step()
{
host.RecordHistory();
host.Selection.Select(plate.Parts[1]);
var tool = new PlaceTool(host, host.Selection.Parts.ToList(),
() => throw new System.InvalidOperationException("settings unreadable"));
host.Tools.SetTool(tool);
var count = RealParts().Count;
Assert.Throws<System.InvalidOperationException>(() => tool.Apply(ToolModifiers.Shift));
// Nothing touched the nest, so no step opened and no restore replaced its objects.
Assert.Empty(host.ChangeLabels);
Assert.Same(plate, host.Recorder.Document.Nest.Plates[0]);
Assert.Equal(count, RealParts().Count);
}
[Fact]
public void A_failing_cut_off_rebuild_rolls_the_placement_back()
{
var crossing = new Part(plate.Parts[1].BaseDrawing, new Vector(75, 40));
plate.Parts.Add(crossing);
plate.RegenerateCutOffs(host.CutOffSettings);
var recorder = host.RecordHistory();
var count = RealParts().Count;
var tool = Copy(plate.Parts[2]);
host.ThrowOnCutOffSettings = true;
Assert.ThrowsAny<System.Exception>(() => tool.Apply(ToolModifiers.None));
Assert.Equal(0, recorder.History.UndoCount);
Assert.Equal(count,
recorder.Document.Nest.Plates[0].Parts.Count(p => !p.BaseDrawing.IsCutOff));
// Whether the tool survives is the view's call: a rollback swaps the nest in, and the
// Avalonia view then ends the tool, as WinForms does.
}
[Fact]
public void A_failing_cut_off_rebuild_rolls_the_delete_back()
{
var crossing = new Part(plate.Parts[1].BaseDrawing, new Vector(75, 40));
plate.Parts.Add(crossing);
plate.RegenerateCutOffs(host.CutOffSettings);
var recorder = host.RecordHistory();
var count = RealParts().Count;
var tool = Copy(crossing);
host.ThrowOnCutOffSettings = true;
Assert.ThrowsAny<System.Exception>(() => tool.DeleteSources());
Assert.Equal(0, recorder.History.UndoCount);
Assert.Equal(count,
recorder.Document.Nest.Plates[0].Parts.Count(p => !p.BaseDrawing.IsCutOff));
}
[Fact]
public void Turning_the_copy_after_a_click_leaves_the_placed_part()
{
var tool = Copy(plate.Parts[2]);
tool.PointerMoved(host.At(60, 60));
tool.Apply(ToolModifiers.None);
var placed = plate.Parts[^1];
var rotation = placed.Rotation;
var location = placed.Location;
edits.RotateQuarterTurn();
edits.NudgeBy(5, 0);
Assert.Equal(rotation, placed.Rotation);
AssertAt(location, placed.Location);
}
[Fact]
public void A_second_escape_resumes_the_tool()
{
var tool = Copy(plate.Parts[1]);
host.Tools.Escape();
host.Tools.Escape();
Assert.Same(tool, host.Tools.Current);
}
[Fact]
public void Escape_ends_the_tool()
{
Copy(plate.Parts[1]);
host.Tools.Escape();
Assert.IsType<SelectTool>(host.Tools.Current);
}
}
@@ -0,0 +1,31 @@
namespace OpenNest.Desktop.Interaction;
/// <summary>
/// The drawing list's pick-up, as WinForms arms it: a single left press on a drawing picks it
/// up, and the next time the plate view takes the keyboard (the pointer entering it focuses
/// it) the drawing then selected in the list starts the place tool. A drop of the dragged
/// drawing on the plate, a double-click and an Undo or Redo put it down.
/// </summary>
public sealed class DrawingPickup
{
/// <summary>Whether a drawing is picked up.</summary>
public bool IsArmed { get; private set; }
/// <summary>A single left press on a drawing in the list.</summary>
public void PickUp() => IsArmed = true;
/// <summary>A drop on the plate, a double-click or an Undo: nothing left to place.</summary>
public void PutDown() => IsArmed = false;
/// <summary>
/// The plate view took the keyboard: the drawing to place, the one selected in the list,
/// or null. As in WinForms, a pick-up with nothing selected stays armed.
/// </summary>
public Drawing TakeOnPlateEnter(Drawing selected)
{
if (!IsArmed || selected == null)
return null;
IsArmed = false;
return selected;
}
}
@@ -0,0 +1,47 @@
using System;
using OpenNest.Engine.Fill;
using OpenNest.Geometry;
namespace OpenNest.Desktop.Interaction;
/// <summary>
/// Adding a part from the nest's drawing list, as the WinForms nest window does: dropping a
/// dragged drawing on the plate adds one part centred where it was dropped, and a drawing
/// picked in the list then carried into the plate view starts the place tool with it.
/// </summary>
public static class DrawingPlacement
{
/// <summary>
/// A drawing dropped on the plate: one part with its bounding box centred on
/// <paramref name="at"/>, as one "Add Part" undo step; null without a plate or while edits
/// are locked. As in WinForms, the plate's cut-offs are not rebuilt.
/// </summary>
public static Part AddPart(IPlateToolHost host, Drawing drawing, Vector at)
{
ArgumentNullException.ThrowIfNull(host);
ArgumentNullException.ThrowIfNull(drawing);
var plate = host.Plate;
if (plate == null || host.EditsLocked)
return null;
var part = new Part(drawing, at);
var center = part.BoundingBox.Center;
part.Offset(at.X - center.X, at.Y - center.Y);
using var change = host.BeginChange("Add Part");
change.MarkChanged();
plate.Parts.Add(part);
host.Invalidate();
change.Complete();
return part;
}
/// <summary>The place tool with one new part of <paramref name="drawing"/>.</summary>
public static PlaceTool CreatePlaceTool(
IPlateToolHost host, Drawing drawing, Func<SettleOrder> placementOrder)
{
ArgumentNullException.ThrowIfNull(host);
ArgumentNullException.ThrowIfNull(drawing);
return new PlaceTool(host, new[] { new Part(drawing) }, placementOrder);
}
}
+186
View File
@@ -0,0 +1,186 @@
using System;
using System.Collections.Generic;
using System.Linq;
using OpenNest.Desktop.Rendering;
using OpenNest.Engine.Fill;
using OpenNest.Geometry;
namespace OpenNest.Desktop.Interaction;
/// <summary>
/// The WinForms Clone Parts action, toolkit-neutral: copies of the source parts follow the
/// pointer (their combined lower-left corner at it) and each left click places another copy on
/// the plate, as one "Add Part"/"Add Parts" undo step. Shift settles the copy toward the plate's
/// quadrant corner on the parts' geometry; Ctrl alone settles it on bounding boxes only. Copied
/// common-line groups are joined again among the placed copies, and cut-offs are rebuilt. The
/// tool stays active until Escape and survives a plate change; <see cref="PlateEdits"/> nudges,
/// pushes and rotates its <see cref="Previews"/> while it is active, and its Delete removes the
/// sources (<see cref="DeleteSources"/>).
/// </summary>
public sealed class PlaceTool : PlateTool
{
private readonly List<Part> previews;
private readonly List<Part> sources;
private readonly List<(int[] Members, double Kerf)> commonLines;
private readonly Func<SettleOrder> placementOrder;
private ScreenPoint? restingPoint;
/// <param name="sources">The parts copied; kept so Delete can remove them.</param>
/// <param name="placementOrder">
/// Which way Shift+click and Ctrl+click settle the copy, read at each click so a changed
/// setting applies without restarting the tool.
/// </param>
public PlaceTool(
IPlateToolHost host, IReadOnlyList<Part> sources, Func<SettleOrder> placementOrder)
: base(host)
{
ArgumentNullException.ThrowIfNull(sources);
ArgumentNullException.ThrowIfNull(placementOrder);
this.placementOrder = placementOrder;
this.sources = sources.ToList();
previews = this.sources.Select(source => source.Clone() as Part).ToList();
commonLines = CopiedCommonLines(host.Plate, this.sources);
}
public override string Name => "Clone Parts";
public override bool IsBusy => false;
public override bool SurvivesPlateChange => true;
/// <summary>The copies following the pointer; they are not on the plate.</summary>
public IReadOnlyList<Part> Previews => previews;
public override void Cancel() { }
public override void OnPlateChanged() => Host.Invalidate();
// The common-line groups among the copied parts, by index into the copy, so each placement
// joins its copies the same way. Read now: Cut removes the sources, and their groups, next.
private static List<(int[] Members, double Kerf)> CopiedCommonLines(
Plate plate, List<Part> copied)
{
var groups = new List<(int[] Members, double Kerf)>();
if (plate == null)
return groups;
foreach (var group in plate.CommonLines)
{
var members = Enumerable.Range(0, copied.Count)
.Where(i => group.Contains(copied[i]))
.ToArray();
if (members.Length >= 2)
groups.Add((members, group.Kerf));
}
return groups;
}
/// <summary>
/// Moves the previews' lower-left corner to the pointer. A move to the screen point last seen
/// is ignored, as WinForms ignores the mouse moves posted when a dialog opens or closes, so
/// an arrow-key nudge of the previews is not thrown away.
/// </summary>
public override bool PointerMoved(ToolPointer pointer)
{
// The WinForms view raises no mouse move while its edits are locked.
if (Host.EditsLocked)
return false;
if (restingPoint == pointer.Screen)
return true;
restingPoint = pointer.Screen;
if (previews.Count > 0)
{
var offset = pointer.World - previews.GetBoundingBox().Location;
foreach (var preview in previews)
preview.Offset(offset);
}
Host.Invalidate();
return true;
}
public override bool PointerPressed(ToolPointer pointer)
{
if (pointer.Button != ToolButton.Left || Host.Plate == null || Host.EditsLocked)
return false;
Apply(pointer.Modifiers);
return true;
}
/// <summary>
/// Places a copy of the previews on the plate (see the class summary); the previews stay
/// where they settled, so the next click places another copy beside this one.
/// </summary>
public void Apply(ToolModifiers modifiers)
{
var plate = Host.Plate;
if (plate == null || Host.EditsLocked || previews.Count == 0)
return;
// Settling moves only the previews, which are not on the nest, so it runs before the
// step opens: if reading the order or settling throws, there is nothing to roll back.
var shift = (modifiers & ToolModifiers.Shift) == ToolModifiers.Shift;
var boxesOnly = !shift && (modifiers & ToolModifiers.Control) == ToolModifiers.Control;
if (shift || boxesOnly)
{
var (horizontal, vertical) = SettleDirections(plate.Quadrant);
Compactor.SettlePlacement(previews, plate, horizontal, vertical,
order: placementOrder(), boundingBoxesOnly: boxesOnly);
Host.Invalidate();
}
using var change = Host.BeginChange(previews.Count == 1 ? "Add Part" : "Add Parts");
change.MarkChanged();
var placed = previews.Select(preview => preview.Clone() as Part).ToList();
foreach (var part in placed)
plate.Parts.Add(part);
foreach (var (members, kerf) in commonLines)
plate.JoinCommonLine(members.Select(i => placed[i]), kerf);
if (plate.CutOffs.Count > 0)
plate.RegenerateCutOffs(Host.CutOffSettings);
Host.Invalidate();
change.Complete();
}
/// <summary>
/// Removes the source parts, and any parts selected on the plate (Select All while placing),
/// as one "Delete" undo step; the previews stay. Recorded only when any of them was still on
/// the plate.
/// </summary>
public void DeleteSources()
{
var plate = Host.Plate;
if (plate == null || Host.EditsLocked)
return;
var doomed = sources.Concat(Host.Selection.Parts).ToList();
using var change = Host.BeginChange("Delete");
var removing = doomed.Any(plate.Parts.Contains);
if (removing)
change.MarkChanged();
foreach (var part in doomed)
plate.Parts.Remove(part);
// Only after a removal: a rebuild gives the cut-offs new programs, which would count as
// an unrecorded change (WinForms rebuilds either way).
if (removing && plate.CutOffs.Count > 0)
plate.RegenerateCutOffs(Host.CutOffSettings);
Host.Selection.Clear();
Host.Invalidate();
change.Complete();
}
// Toward the quadrant's origin corner, as WinForms: 1 lower-left, 2 lower-right,
// 3 upper-right, 4 upper-left.
private static (PushDirection Horizontal, PushDirection Vertical) SettleDirections(
int quadrant) =>
quadrant switch
{
2 => (PushDirection.Right, PushDirection.Down),
3 => (PushDirection.Right, PushDirection.Up),
4 => (PushDirection.Left, PushDirection.Up),
_ => (PushDirection.Left, PushDirection.Down),
};
}
@@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Linq;
using OpenNest.Engine.Fill;
namespace OpenNest.Desktop.Interaction;
/// <summary>
/// Edit &gt; Cut and Copy, toolkit-neutral: both start a <see cref="PlaceTool"/> with the parts
/// selected on the plate, in selection order. Neither does anything without a plate or selected
/// parts, or while the host's edits are locked.
/// </summary>
public static class PlateClipboard
{
/// <summary>
/// Starts placing copies of the selected parts; null when nothing was started.
/// </summary>
public static PlaceTool Copy(
IPlateToolHost host, PlateToolManager tools, Func<SettleOrder> order)
{
var sources = Sources(host, tools);
if (sources == null)
return null;
var tool = new PlaceTool(host, sources, order);
tools.SetTool(tool);
return tool;
}
/// <summary>
/// Starts placing copies of the selected parts, then removes them from the plate as one
/// "Cut" undo step. As in WinForms, the plate's cut-offs are not rebuilt here.
/// </summary>
public static PlaceTool Cut(
IPlateToolHost host, PlateToolManager tools, Func<SettleOrder> order)
{
var sources = Sources(host, tools);
if (sources == null)
return null;
// The tool reads the sources' common-line groups, which their removal ends.
var tool = new PlaceTool(host, sources, order);
tools.SetTool(tool);
var plate = host.Plate;
using var change = host.BeginChange("Cut");
change.MarkChanged();
foreach (var part in sources)
plate.Parts.Remove(part);
host.Selection.Clear();
host.Invalidate();
change.Complete();
return tool;
}
private static List<Part> Sources(IPlateToolHost host, PlateToolManager tools)
{
ArgumentNullException.ThrowIfNull(host);
ArgumentNullException.ThrowIfNull(tools);
if (host.Plate == null || host.EditsLocked)
return null;
host.Selection.Prune();
var sources = host.Selection.Parts.ToList();
return sources.Count == 0 ? null : sources;
}
}
+49 -10
View File
@@ -5,6 +5,7 @@ using System.Runtime.CompilerServices;
using OpenNest.Engine.Fill;
using OpenNest.Geometry;
using OpenNest.Math;
using OpenNest.Undo;
namespace OpenNest.Desktop.Interaction;
@@ -14,6 +15,12 @@ namespace OpenNest.Desktop.Interaction;
/// same parts, and wheel rotations, undo as one. Every edit does nothing without a plate or
/// selected parts (Delete also acts on selected cut-offs alone) and redraws the view, and nothing
/// at all while the host's edits are locked (<see cref="IPlateToolHost.EditsLocked"/>).
/// <para>
/// While a <see cref="PlaceTool"/> is active in <see cref="Tools"/>, nudge, step, push and rotate
/// move its previews instead, which are not on the plate: no undo step is opened (WinForms
/// records an empty one) and cut-offs are not rebuilt. Delete then removes the tool's sources
/// (<see cref="PlaceTool.DeleteSources"/>).
/// </para>
/// </summary>
public sealed class PlateEdits
{
@@ -24,6 +31,21 @@ public sealed class PlateEdits
public IPlateToolHost Host { get; }
/// <summary>
/// The view's tools, so edits can act on a place tool's previews; null for none.
/// </summary>
public PlateToolManager Tools { get; set; }
/// <summary>
/// Whether nudge, push and rotate have parts to move: a place tool's previews, or selected
/// parts still on the plate. The view checks it before a middle click or Shift+wheel rotates.
/// </summary>
public bool HasPartsToEdit =>
Placing is { Previews.Count: > 0 }
|| (Host.Plate != null && Host.Selection.Parts.Any(Host.Plate.Parts.Contains));
private PlaceTool Placing => Tools?.Current as PlaceTool;
/// <summary>How far an arrow-key nudge moves the selection, in plate units.</summary>
public double OffsetIncrement { get; set; } = 10;
@@ -45,6 +67,11 @@ public sealed class PlateEdits
var plate = Host.Plate;
if (plate == null || Host.EditsLocked)
return;
if (Placing is { } placing)
{
placing.DeleteSources();
return;
}
var selection = Host.Selection;
selection.Prune();
var parts = selection.Parts.ToList();
@@ -85,10 +112,10 @@ public sealed class PlateEdits
/// <summary>Moves the selection by (<paramref name="dx"/>, <paramref name="dy"/>).</summary>
public void NudgeBy(double dx, double dy)
{
if (!TryGetSelectedParts(out var plate, out var parts))
if (!TryGetEditParts(out var plate, out var parts, out var previews))
return;
using var change = Host.BeginChange("Nudge", new SelectionKey("Nudge", plate, parts));
using var change = BeginEdit(previews, "Nudge", new SelectionKey("Nudge", plate, parts));
change.MarkChanged();
foreach (var part in parts)
part.Offset(dx, dy);
@@ -102,10 +129,10 @@ public sealed class PlateEdits
/// </summary>
public void Step(PushDirection direction)
{
if (!TryGetSelectedParts(out var plate, out var parts))
if (!TryGetEditParts(out var plate, out var parts, out var previews))
return;
using var change = Host.BeginChange("Nudge", new SelectionKey("Nudge", plate, parts));
using var change = BeginEdit(previews, "Nudge", new SelectionKey("Nudge", plate, parts));
if (Compactor.Step(parts, plate, direction) > 0)
change.MarkChanged();
Host.Invalidate();
@@ -117,10 +144,10 @@ public sealed class PlateEdits
/// </summary>
public void Push(PushDirection direction)
{
if (!TryGetSelectedParts(out var plate, out var parts))
if (!TryGetEditParts(out var plate, out var parts, out var previews))
return;
using var change = Host.BeginChange("Push");
using var change = BeginEdit(previews, "Push");
change.MarkChanged();
Compactor.Push(parts, plate, direction);
Host.Invalidate();
@@ -133,10 +160,10 @@ public sealed class PlateEdits
/// </summary>
public void Rotate(double radians, bool coalesce = false)
{
if (!TryGetSelectedParts(out var plate, out var parts))
if (!TryGetEditParts(out var plate, out var parts, out var previews))
return;
using var change = Host.BeginChange("Rotate",
using var change = BeginEdit(previews, "Rotate",
coalesce ? new SelectionKey("Rotate", plate, parts) : null);
change.MarkChanged();
var bounds = parts.GetBoundingBox();
@@ -149,7 +176,7 @@ public sealed class PlateEdits
foreach (var part in parts)
part.Offset(diff);
if (plate.CutOffs.Count > 0)
if (!previews && plate.CutOffs.Count > 0)
plate.RegenerateCutOffs(Host.CutOffSettings);
Host.Invalidate();
change.Complete();
@@ -173,17 +200,29 @@ public sealed class PlateEdits
Rotate(angle, coalesce: true);
}
private bool TryGetSelectedParts(out Plate plate, out List<Part> parts)
// The parts an edit moves: a place tool's previews (previews is true), else the selection.
private bool TryGetEditParts(out Plate plate, out List<Part> parts, out bool previews)
{
plate = Host.Plate;
parts = null;
previews = false;
if (plate == null || Host.EditsLocked)
return false;
if (Placing is { } placing)
{
previews = true;
parts = placing.Previews.ToList();
return parts.Count > 0;
}
Host.Selection.Prune();
parts = Host.Selection.Parts.ToList();
return parts.Count > 0;
}
// Previews are not on the nest, so moving them opens no undo step.
private ChangeScope BeginEdit(bool previews, string label, object coalesceKey = null) =>
previews ? ChangeScope.Detached() : Host.BeginChange(label, coalesceKey);
/// <summary>
/// Equal for the same edit of the same parts, in the same order, on the same plate, so
/// repeated nudges or wheel turns coalesce into one undo entry.
@@ -17,6 +17,8 @@ public class ShapeCutDirectionTests
{
var shapes = new ShapeDefinition[]
{
new AngleShape(),
new ChannelShape(),
new CircleShape(),
new IsoscelesTriangleShape(),
new LShape(),
@@ -26,6 +28,7 @@ public class ShapeCutDirectionTests
new RectangleShape(),
new RightTriangleShape(),
new RingShape(),
new RolledPlateShape(),
new RoundedRectangleShape(),
new TShape(),
new TrapezoidShape(),
@@ -75,6 +78,9 @@ public class ShapeCutDirectionTests
Assert.True(perimeter >= 0, $"{name}: no perimeter");
for (var i = 0; i < contours.Count; i++)
{
// Marks such as etched bend lines are open: they have no winding.
if (contours[i].IsMark)
continue;
var area = ContourWinding.SignedArea(contours[i]);
if (i == perimeter)
Assert.True(area < 0, $"{name}: outside is not clockwise");
@@ -86,6 +92,7 @@ public class ShapeCutDirectionTests
/// <summary>Each contour's winding sign, in a stable order so reordering does not matter.</summary>
private static List<int> Directions(Program program) =>
PostContours.Extract(program, Vector.Zero)
.Where(c => !c.IsMark)
.Select(c => System.Math.Sign(ContourWinding.SignedArea(c)))
.OrderBy(s => s)
.ToList();
+4 -1
View File
@@ -20,7 +20,10 @@ public class ShapeDimensionTests
{
var shape = (ShapeDefinition)Activator.CreateInstance(shapeType)!;
shape.SetPreviewDefaults();
var dimensions = shape.GetDimensions();
// A side view's dimensions show parameters too, each once across both views.
var dimensions = shape.GetDimensions()
.Concat(shape.GetSideView()?.Dimensions ?? Array.Empty<ShapeDimension>())
.ToList();
Assert.NotEmpty(dimensions);
Assert.Equal(dimensions.Count, dimensions.Select(d => d.Property).Distinct().Count());
@@ -0,0 +1,182 @@
using OpenNest.Bending;
using OpenNest.CNC;
using OpenNest.Geometry;
using OpenNest.Shapes;
namespace OpenNest.Tests.Shapes;
public class SheetMetalShapeTests
{
// 90° bend at 5/16 inside radius, 1/8 thick, K 0.42.
private static readonly double Allowance = System.Math.PI / 2 * (0.3125 + 0.42 * 0.125);
[Fact]
public void Angle_BlankIsTheDevelopedWidthByTheLength()
{
var shape = new AngleShape();
shape.SetPreviewDefaults();
var box = shape.GetDrawing().Program.BoundingBox();
// Legs' flats: 2 - 1/8 - 5/16 and 4 - 1/8 - 5/16.
var expected = 1.5625 + 3.5625 + Allowance;
Assert.Equal(expected, shape.FlatLength, 9);
Assert.Equal(12, box.Length, 6);
Assert.Equal(expected, box.Width, 6);
}
[Fact]
public void Angle_BendsUpAcrossTheBlankFromTheShorterLeg()
{
var shape = new AngleShape();
shape.SetPreviewDefaults();
var bend = Assert.Single(shape.GetDrawing().Bends);
var y = 1.5625 + Allowance / 2;
Assert.Equal(y, shape.BendLineDim, 9);
Assert.Equal(new Vector(0, y), bend.StartPoint);
Assert.Equal(new Vector(12, y), bend.EndPoint);
Assert.Equal(BendDirection.Up, bend.Direction);
Assert.Equal(90, bend.Angle);
Assert.Equal(0.3125, bend.Radius);
}
[Fact]
public void Channel_BlankHasTwoBendsInFromEachSide()
{
var shape = new ChannelShape();
shape.SetPreviewDefaults();
var drawing = shape.GetDrawing();
var box = drawing.Program.BoundingBox();
// Sides' flats: 2 - 1/8 - 5/16 each; bottom: 4 - 2(1/8) - 2(5/16).
var expected = 1.5625 * 2 + 3.125 + Allowance * 2;
Assert.Equal(expected, shape.FlatLength, 9);
Assert.Equal(expected, box.Width, 6);
var lines = drawing.Bends.Select(b => b.StartPoint.Y).OrderBy(y => y).ToList();
var inset = 1.5625 + Allowance / 2;
Assert.Equal(2, lines.Count);
Assert.Equal(inset, lines[0], 9);
Assert.Equal(expected - inset, lines[1], 9);
}
[Fact]
public void RolledPlate_BlankIsTheNeutralCircumference()
{
var shape = new RolledPlateShape { InsideDiameter = 10, Thickness = 0.25, KFactor = 0.5, Length = 24 };
var drawing = shape.GetDrawing();
var box = drawing.Program.BoundingBox();
var expected = System.Math.PI * 2 * (5 + 0.125);
Assert.Equal(expected, shape.FlatLength, 9);
Assert.Equal(24, box.Length, 6);
Assert.Equal(expected, box.Width, 6);
Assert.Empty(drawing.Bends);
Assert.Equal(10.5, shape.OutsideDiameter, 9);
}
[Fact]
public void BendLines_AreEtchedOnTheBlank()
{
var shape = new ChannelShape();
shape.SetPreviewDefaults();
var etches = shape.GetDrawing().Program.Codes
.OfType<LinearMove>()
.Count(m => m.Layer == LayerType.Scribe);
// Each 12" bend line gets a 1" dash at either end.
Assert.Equal(4, etches);
}
[Fact]
public void Angle_LegNoLongerThanThicknessPlusRadius_DoesNotMakeAShape()
{
var shape = new AngleShape { OutsideWidth = 4, OutsideHeight = 0.4, Thickness = 0.125, InsideRadius = 0.3125, KFactor = 0.42, Length = 12 };
Assert.Throws<InvalidOperationException>(() => shape.GetDrawing());
}
[Fact]
public void KFactorAboveOne_DoesNotMakeAShape()
{
var shape = new ChannelShape();
shape.SetPreviewDefaults();
shape.KFactor = 1.5;
Assert.Throws<InvalidOperationException>(() => shape.GetDrawing());
}
[Fact]
public void AngleSideView_IsOneClosedSectionOfTheFormedAngle()
{
var shape = new AngleShape();
shape.SetPreviewDefaults();
var section = Assert.Single(ShapeBuilder.GetShapes(shape.GetSideView().Entities));
// Two legs' flats and a quarter annulus at the bend.
const double t = 0.125, ir = 0.3125, or = ir + t;
var expected = t * (4 - or) + t * (2 - or) + System.Math.PI / 4 * (or * or - ir * ir);
Assert.True(section.IsClosed());
Assert.Equal(expected, section.Area(), 1e-4);
var box = section.BoundingBox;
Assert.Equal(4, box.Length, 6);
Assert.Equal(2, box.Width, 6);
}
[Fact]
public void ChannelSideView_IsOneClosedSectionOfTheFormedChannel()
{
var shape = new ChannelShape();
shape.SetPreviewDefaults();
var section = Assert.Single(ShapeBuilder.GetShapes(shape.GetSideView().Entities));
// Two sides' and the bottom's flats and two quarter annuli at the bends.
const double t = 0.125, ir = 0.3125, or = ir + t;
var expected = t * (2 - or) * 2 + t * (4 - 2 * or) + System.Math.PI / 2 * (or * or - ir * ir);
Assert.True(section.IsClosed());
Assert.Equal(expected, section.Area(), 1e-4);
}
[Fact]
public void SideViews_DimensionTheSizesTheBlankCannotShow()
{
var angle = new AngleShape();
angle.SetPreviewDefaults();
var rolled = new RolledPlateShape();
rolled.SetPreviewDefaults();
Assert.Equal(
new[] { nameof(AngleShape.OutsideWidth), nameof(AngleShape.OutsideHeight), nameof(AngleShape.Thickness), nameof(AngleShape.InsideRadius) },
angle.GetSideView().Dimensions.Select(d => d.Property));
var radius = angle.GetSideView().Dimensions.Single(d => d.Property == nameof(AngleShape.InsideRadius));
Assert.Equal(0.3125, radius.ArcRadius, 9);
Assert.Equal("R", radius.Prefix);
Assert.Equal(
new[] { nameof(RolledPlateShape.InsideDiameter), nameof(RolledPlateShape.Thickness) },
rolled.GetSideView().Dimensions.Select(d => d.Property));
}
[Fact]
public void FlatShapes_HaveNoSideView()
{
Assert.Null(new RectangleShape { Length = 10, Width = 5 }.GetSideView());
}
[Fact]
public void GeneratedNames_DescribeThePart()
{
var angle = new AngleShape();
angle.SetPreviewDefaults();
var rolled = new RolledPlateShape();
rolled.SetPreviewDefaults();
Assert.Equal("Angle 4x2x0.125 x 12", angle.GenerateName());
Assert.Equal("Rolled Plate 10 ID x 0.188 x 12", rolled.GenerateName());
}
}
@@ -42,9 +42,9 @@ public class DrawingLibraryFormTests
Assert.Equal("Deburr both sides", notes.Text);
quantity.Value = 3;
Run(form.View.AddSelectedAsync());
Add(form);
quantity.Value = 2;
Run(form.View.AddSelectedAsync());
Add(form);
Assert.Empty(messages);
var drawing = Assert.Single(nest.Drawings);
@@ -57,6 +57,86 @@ public class DrawingLibraryFormTests
"The drawing library dialog test did not complete.");
}
[Fact]
public void EachAdd_ShowsTheBannerAndRaisesNestChangedWhileTheDialogIsOpen()
{
StaTestThread.Run(
() =>
{
var library = new FakeLibrary();
var record = library.Add("SYN-111", "Synthetic Steel", "Grade A", 0.25, Units.Inches, "");
var nest = MatchingNest();
var changed = new List<Drawing>();
using var form = new DrawingLibraryForm(library, Server, nest);
form.View.ShowMessage = (text, _, _) => throw new Xunit.Sdk.XunitException(text);
form.View.LoadPreview = (_, _) => Task.FromResult<Drawing>(null!);
form.NestChanged += (_, drawing) => changed.Add(drawing);
form.Show();
var grid = Field<DataGridView>(form, "drawingGrid");
var banner = Field<OpenNest.Controls.NoticeBanner>(form, "addedBanner");
var quantity = Field<NumericUpDown>(form, "quantityBox");
PumpUntilListed(grid, "the library page");
Assert.False(banner.Visible);
quantity.Value = 3;
Add(form);
var drawing = Assert.Single(nest.Drawings);
Assert.False(banner.InvokeRequired);
Assert.True(banner.Visible);
Assert.Equal($"Added 'SYN-111' revision {record.Revision} to the nest, quantity 3.", banner.Message);
Assert.Same(drawing, Assert.Single(changed));
quantity.Value = 2;
Add(form);
Assert.Equal("Added 2 more of 'SYN-111' to the nest (now 5 required).", banner.Message);
Assert.Equal(new[] { drawing, drawing }, changed);
// The In This Nest tab's quantity edits are listed behind the dialog too.
var nestGrid = Field<DataGridView>(form, "nestGrid");
Field<TabControl>(form, "tabControl").SelectedTab = Field<TabPage>(form, "nestTab");
nestGrid.CurrentCell = nestGrid.Rows[0].Cells["nestRequiredColumn"];
Assert.True(nestGrid.BeginEdit(true));
nestGrid.EditingControl!.Text = "7";
nestGrid.NotifyCurrentCellDirty(true);
Assert.True(nestGrid.EndEdit());
Assert.Equal(3, changed.Count);
Assert.Equal(7, drawing.Quantity.Required);
},
TestTimeout,
"The drawing library banner test did not complete.");
}
[Fact]
public void RefusedAdd_ShowsNoBannerAndRaisesNothing()
{
StaTestThread.Run(
() =>
{
var library = new FakeLibrary();
library.Add("SYN-313", "Synthetic Steel", "Grade A", 0.25, Units.Millimeters, "");
var nest = MatchingNest();
var changed = 0;
using var form = new DrawingLibraryForm(library, Server, nest);
form.View.ShowMessage = (_, _, _) => DialogResult.OK;
form.View.LoadPreview = (_, _) => Task.FromResult<Drawing>(null!);
form.NestChanged += (_, _) => changed++;
form.Show();
var grid = Field<DataGridView>(form, "drawingGrid");
PumpUntilListed(grid, "the library page");
Add(form);
Assert.Empty(nest.Drawings);
Assert.False(Field<OpenNest.Controls.NoticeBanner>(form, "addedBanner").Visible);
Assert.Equal(0, changed);
},
TestTimeout,
"The drawing library refused-add banner test did not complete.");
}
[Fact]
public void SelectingADrawing_ShowsItsDetailsAndPreviewsItsGeometry()
{
@@ -122,7 +202,7 @@ public class DrawingLibraryFormTests
PumpUntilListed(grid, "the library page");
Field<NumericUpDown>(form, "quantityBox").Value = 2;
Run(form.View.AddSelectedAsync());
Add(form);
Assert.Equal("In This Nest (2)", nestTab.Text);
Assert.Equal($"Revision {record.Revision}", nestGrid.Rows[1].Cells["nestLibraryColumn"].Value);
Assert.Equal(2, nestGrid.Rows[1].Cells["nestRequiredColumn"].Value);
@@ -183,9 +263,9 @@ public class DrawingLibraryFormTests
PumpUntilListed(grid, "the unfiltered page");
Assert.Equal(("", "", (double?)null), (library.Queries[^1].MaterialName, library.Queries[^1].MaterialGrade, library.Queries[^1].Thickness));
Run(form.View.AddSelectedAsync());
Add(form);
Assert.Empty(nest.Drawings);
Run(form.View.AddSelectedAsync());
Add(form);
Assert.Equal(2, messages.Count);
Assert.Contains("thickness 0.1875 (nest 0.25)", messages[0]);
@@ -213,7 +293,7 @@ public class DrawingLibraryFormTests
var grid = Field<DataGridView>(form, "drawingGrid");
PumpUntilListed(grid, "the library page");
Run(form.View.AddSelectedAsync());
Add(form);
Assert.Contains("millimeters", Assert.Single(messages));
Assert.Empty(nest.Drawings);
@@ -262,7 +342,7 @@ public class DrawingLibraryFormTests
Assert.Equal("Yes", grid.Rows[0].Cells["cutFirstColumn"].Value);
SelectFirstRow(grid);
Run(form.View.AddSelectedAsync());
Add(form);
Assert.True(Assert.Single(nest.Drawings).CutFirst);
},
TestTimeout,
@@ -524,7 +604,7 @@ public class DrawingLibraryFormTests
Assert.DoesNotContain(Field<TabPage>(form, "nestTab"), Field<TabControl>(form, "tabControl").TabPages.Cast<TabPage>());
Assert.False(Field<Button>(form, "addButton").Visible);
Assert.Equal("Edit Drawing...", Field<Button>(form, "editButton").Text);
Run(form.View.AddSelectedAsync());
Add(form);
Assert.Empty(library.Downloads);
typeof(DataGridView).GetMethod("OnCellDoubleClick", BindingFlags.Instance | BindingFlags.NonPublic)!
@@ -635,6 +715,17 @@ public class DrawingLibraryFormTests
Material = new Material("Synthetic Steel", "Grade A"),
};
/// <summary>
/// Adds the selected drawing and waits for it. Each DoEvents leaves a plain synchronization
/// context on the thread, so the WinForms one is put back first: as in the dialog's own
/// message loop, the add's awaits then return to the UI thread rather than the thread pool.
/// </summary>
private static void Add(DrawingLibraryForm form)
{
SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());
Run(form.View.AddSelectedAsync());
}
// A faulted task rethrows here, so a failed step reports its own error instead of a later timeout.
private static void Run(Task task)
{
@@ -27,7 +27,11 @@ public class DrawingLibraryGridFormTests
Run(form.CheckAllPagesAsync());
Assert.Equal(DrawingLibraryGridForm.PageSize + 1, form.DrawingsShown);
var problem = Assert.Single(form.Problems);
// Slow-timing reports depend on the machine (a loaded CI runner paints a tile
// past 500 ms); a hang is still reported as a failure.
var failures = form.Problems.Where(
p => !p.Problem.StartsWith("Slow ", StringComparison.Ordinal));
var problem = Assert.Single(failures);
Assert.Same(missing, problem.Record);
Assert.Equal("Revision not on the server", problem.Problem);
Assert.Equal(new[] { 0, DrawingLibraryGridForm.PageSize }, library.Offsets.Skip(library.Offsets.Count - 2));
@@ -0,0 +1,48 @@
using System.Reflection;
using System.Windows.Forms;
using OpenNest.Controls;
using OpenNest.Forms;
using OpenNest.Shapes;
namespace OpenNest.WinForms.Tests.Forms;
[Collection("Fill operation lifetime")]
public class EditNestLibraryChangeTests
{
[Fact]
public void ALibraryAdd_IsListedOnTheDrawingsTabAndSelectedThere() => RunSta(() =>
{
var nest = new Nest("library add");
var existing = new RectangleShape { Name = "A-EXISTING", Length = 3, Width = 1 }.GetDrawing();
existing.Quantity.Required = 1;
nest.Drawings.Add(existing);
using var form = new EditNestForm(nest) { Width = 1100, Height = 700 };
form.PlateView.SetOverlapAutoCheck(null);
form.Show();
Application.DoEvents();
var tabs = Field<TabControl>(form, "tabControl1");
var drawingsTab = Field<TabPage>(form, "tabPage2");
var list = Field<DrawingListBox>(form, "drawingListBox1");
tabs.SelectedTab = Field<TabPage>(form, "tabPage1");
// What the Drawing Library dialog does to the nest before it raises NestChanged.
var added = new RectangleShape { Name = "B-LIBRARY", Length = 4, Width = 2 }.GetDrawing();
added.Quantity.Required = 3;
nest.Drawings.Add(added);
form.ShowLibraryChange(added);
Assert.Same(drawingsTab, tabs.SelectedTab);
Assert.Equal(new object[] { existing, added }, list.Items.Cast<object>());
Assert.Same(added, list.SelectedItem);
});
private static T Field<T>(EditNestForm form, string name) =>
(T)typeof(EditNestForm)
.GetField(name, BindingFlags.Instance | BindingFlags.NonPublic)!
.GetValue(form)!;
private static void RunSta(System.Action action) =>
StaTestThread.Run(action, TimeSpan.FromMinutes(3), "The STA test did not complete.");
}
@@ -101,6 +101,52 @@ public class ShapeLibraryFormTests
Assert.True(Find<Button>(form, "addButton").Enabled);
});
[Fact]
public void KFactorIsAPlainNumberNotALength() => ArchUnitsTests.RunSta(() =>
{
using var form = new ShapeLibraryForm();
SelectShape(form, typeof(ChannelShape));
var preview = Find<ShapePreviewControl>(form, "previewBox");
var width = preview.Plate.Parts.Single().BoundingBox.Width;
Assert.Equal("K-Factor: 0.42", preview.LabelText("KFactor"));
var box = OpenEditor(form, "KFactor");
box.Text = "1.5";
Press(box, Keys.Enter);
Assert.Same(box, form.ActiveEditor);
box.Text = "0.5";
Press(box, Keys.Enter);
Assert.Null(form.ActiveEditor);
Assert.Equal("K-Factor: 0.5", preview.LabelText("KFactor"));
// Two bends' allowance grows by 90° x 0.08 of the 1/8" thickness each.
Assert.Equal(width + System.Math.PI * 0.08 * 0.125, preview.Plate.Parts.Single().BoundingBox.Width, 6);
});
[Fact]
public void ASheetMetalPartsSideViewDimensionsItsSection() => ArchUnitsTests.RunSta(() =>
{
using var form = new ShapeLibraryForm();
SelectShape(form, typeof(AngleShape));
var preview = Find<ShapePreviewControl>(form, "previewBox");
var blank = preview.Plate.Parts.Single().BoundingBox;
Assert.Equal(new[] { "Length", "OutsideWidth", "OutsideHeight", "Thickness", "InsideRadius", "KFactor" }, preview.LabelKeys);
Assert.Equal("4\"", preview.LabelText("OutsideWidth"));
Assert.Equal("R5/16\"", preview.LabelText("InsideRadius"));
// The section sits to the right of the blank, its dimensions with it.
Assert.True(preview.LabelBounds("OutsideWidth")!.Value.Left > preview.LabelBounds("Length")!.Value.Right);
var box = OpenEditor(form, "OutsideWidth");
box.Text = "6";
Press(box, Keys.Enter);
Assert.Null(form.ActiveEditor);
Assert.Equal("6\"", preview.LabelText("OutsideWidth"));
Assert.Equal(blank.Width + 2, preview.Plate.Parts.Single().BoundingBox.Width, 6);
});
[Fact]
public void TabCommitsAndMovesToTheNextDimension() => ArchUnitsTests.RunSta(() =>
{
+14 -3
View File
@@ -86,6 +86,7 @@ namespace OpenNest.Controls
editButton = new System.Windows.Forms.Button();
exportButton = new System.Windows.Forms.Button();
statusLabel = new System.Windows.Forms.Label();
addedBanner = new OpenNest.Controls.NoticeBanner();
searchTimer = new System.Windows.Forms.Timer(components);
previewTimer = new System.Windows.Forms.Timer(components);
drawingMenu = new System.Windows.Forms.ContextMenuStrip(components);
@@ -263,13 +264,15 @@ namespace OpenNest.Controls
layoutTable.ColumnCount = 1;
layoutTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
layoutTable.Controls.Add(filterTable, 0, 0);
layoutTable.Controls.Add(splitContainer, 0, 1);
layoutTable.Controls.Add(statusLabel, 0, 2);
layoutTable.Controls.Add(addedBanner, 0, 1);
layoutTable.Controls.Add(splitContainer, 0, 2);
layoutTable.Controls.Add(statusLabel, 0, 3);
layoutTable.Dock = System.Windows.Forms.DockStyle.Fill;
layoutTable.Margin = new System.Windows.Forms.Padding(0);
layoutTable.Padding = new System.Windows.Forms.Padding(8);
layoutTable.Name = "layoutTable";
layoutTable.RowCount = 3;
layoutTable.RowCount = 4;
layoutTable.RowStyles.Add(new System.Windows.Forms.RowStyle());
layoutTable.RowStyles.Add(new System.Windows.Forms.RowStyle());
layoutTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
layoutTable.RowStyles.Add(new System.Windows.Forms.RowStyle());
@@ -788,6 +791,13 @@ namespace OpenNest.Controls
statusLabel.Size = new System.Drawing.Size(100, 20);
statusLabel.TabIndex = 2;
//
// addedBanner
//
addedBanner.Dock = System.Windows.Forms.DockStyle.Top;
addedBanner.Margin = new System.Windows.Forms.Padding(0, 0, 0, 6);
addedBanner.Name = "addedBanner";
addedBanner.TabIndex = 3;
//
// searchTimer
//
searchTimer.Interval = 300;
@@ -988,6 +998,7 @@ namespace OpenNest.Controls
private System.Windows.Forms.Button addButton;
private System.Windows.Forms.Button editButton;
private System.Windows.Forms.Label statusLabel;
private OpenNest.Controls.NoticeBanner addedBanner;
private System.Windows.Forms.Timer searchTimer;
private System.Windows.Forms.Timer previewTimer;
private System.Windows.Forms.ContextMenuStrip drawingMenu;
+16 -5
View File
@@ -20,8 +20,9 @@ namespace OpenNest.Controls
/// <see cref="DrawingLibraryBrowseSession"/>, filtered to the nest's material and thickness
/// unless Show all is ticked. Add downloads the listed revision's exact package, plans it
/// with <see cref="LibraryDrawingInsert"/>, shows any warning or refusal first and only then
/// changes the nest. Opened without a nest, it lists every active drawing and has no In This
/// Nest tab; as the Library tab of <see cref="DrawingSetsForm"/> a double-click, Enter or Add
/// changes the nest; a green banner confirms each add and <see cref="NestChanged"/> lets the
/// host list it behind the dialog at once. Opened without a nest, it lists every active
/// drawing and has no In This Nest tab; as the Library tab of <see cref="DrawingSetsForm"/> a double-click, Enter or Add
/// to Release adds the drawing on its own, at the entered quantity, to the window's
/// <see cref="ReleasePanel"/>, and elsewhere a double-click edits it. Edit Drawing changes the
/// selected drawing's details, notes and nesting settings (Cut first, priority, rotation,
@@ -116,6 +117,12 @@ namespace OpenNest.Controls
/// </summary>
public bool QuantitiesChanged { get; private set; }
/// <summary>
/// Raised each time an add or an In This Nest quantity edit changes the nest, while the
/// dialog is still open, so the host can show the change behind it at once.
/// </summary>
public event EventHandler<Drawing> NestChanged;
/// <summary>
/// The window that owns this view's dialogs. A dialog owned by a child control is not kept
/// above its top-level window, so it can fall behind it.
@@ -853,6 +860,7 @@ namespace OpenNest.Controls
adding = true;
UpdateCommands();
addedBanner.Hide();
statusLabel.Text = $"Downloading '{record.Name}' revision {record.Revision}...";
var quantity = (int)quantityBox.Value;
try
@@ -895,9 +903,11 @@ namespace OpenNest.Controls
if (!AddedDrawings.Contains(insert.Drawing))
AddedDrawings.Add(insert.Drawing);
RefreshNestTab();
statusLabel.Text = insert.Kind == LibraryInsertKind.AddQuantity
? $"Added {quantity} to '{insert.Drawing.Name}' (now {insert.Drawing.Quantity.Required})."
: $"Added '{insert.Drawing.Name}' revision {record.Revision}, quantity {quantity}.";
statusLabel.Text = "";
addedBanner.Show(insert.Kind == LibraryInsertKind.AddQuantity
? $"Added {quantity:N0} more of '{insert.Drawing.Name}' to the nest (now {insert.Drawing.Quantity.Required:N0} required)."
: $"Added '{insert.Drawing.Name}' revision {record.Revision} to the nest, quantity {quantity:N0}.");
NestChanged?.Invoke(this, insert.Drawing);
}
catch (ServerTooOldException ex)
{
@@ -1101,6 +1111,7 @@ namespace OpenNest.Controls
statusLabel.Text = $"'{drawing.Name}' now requires {value:N0} (was {before:N0}).";
UpdateNestSummary();
NestChanged?.Invoke(this, drawing);
}
private void UpdateNestSummary()
+75
View File
@@ -0,0 +1,75 @@
using System.Drawing;
using System.Windows.Forms;
namespace OpenNest.Controls
{
/// <summary>
/// A slim green confirmation strip, one line of text 30 pixels high (scaled with the form):
/// a pale tint with dark text and a border in the same hue, and a close button. A message
/// longer than the strip ends in an ellipsis. Hidden until <see cref="Show(string)"/>; it
/// stays until the next message replaces it or the operator closes it.
/// </summary>
public sealed class NoticeBanner : Panel
{
private static readonly Color Tint = Color.FromArgb(221, 240, 214);
private static readonly Color Ink = Color.FromArgb(28, 88, 28);
private readonly Label messageLabel;
private readonly Button closeButton;
private string message = "";
public NoticeBanner()
{
BackColor = Tint;
Height = 30;
Padding = new Padding(8, 1, 1, 1);
DoubleBuffered = true;
ResizeRedraw = true;
Visible = false;
messageLabel = new Label
{
AutoEllipsis = true,
AutoSize = false,
Dock = DockStyle.Fill,
ForeColor = Ink,
Name = "messageLabel",
TextAlign = ContentAlignment.MiddleLeft,
};
closeButton = new Button
{
Dock = DockStyle.Right,
FlatStyle = FlatStyle.Flat,
ForeColor = Ink,
AccessibleName = "Close",
Name = "closeButton",
TabStop = false,
Text = "✕",
Width = 26,
};
closeButton.FlatAppearance.BorderSize = 0;
closeButton.Click += (_, _) => Hide();
// Fill is laid out last, so the label takes what the button leaves.
Controls.Add(messageLabel);
Controls.Add(closeButton);
}
/// <summary>The message shown, or empty while hidden.</summary>
public string Message => Visible ? message : "";
/// <summary>Shows <paramref name="message"/>, replacing whatever was there.</summary>
public void Show(string message)
{
this.message = message ?? "";
messageLabel.Text = this.message;
Visible = true;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
ControlPaint.DrawBorder(e.Graphics, ClientRectangle, Ink, ButtonBorderStyle.Solid);
}
}
}
+131 -16
View File
@@ -58,6 +58,16 @@ namespace OpenNest.Controls
// The shown drawing's cut geometry, in its own coordinates (as dimension points are).
private List<Entity> profile = new();
// A sheet metal part's section beside the blank, in its own coordinates, and where it is
// shown: view = offset + point * scale. Empty when the shape has none.
private List<Entity> sideProfile = new();
private List<Polygon> sideOutlines = new();
private Vector sideOffset;
private double sideScale = 1;
// The view the dimension being laid out belongs to.
private Frame frame;
private IReadOnlyList<Annotation> annotations = Array.Empty<Annotation>();
private IReadOnlyList<Note> notes = Array.Empty<Note>();
private AnnotationLayout layout;
@@ -97,7 +107,7 @@ namespace OpenNest.Controls
internal bool IsUserView => userView;
/// <summary>A dimension to draw: its text, and the count text after it when it has one.</summary>
public sealed record Annotation(ShapeDimension Dimension, string Text, string CountText = null);
public sealed record Annotation(ShapeDimension Dimension, string Text, string CountText = null, bool OnSideView = false);
/// <summary>A parameter with no place on the drawing, shown as a chip along the bottom.</summary>
public sealed record Note(string Key, string Text, bool Enabled = true);
@@ -134,6 +144,9 @@ namespace OpenNest.Controls
/// <summary>The keys of the labels on screen, in drawing order (dimensions, then notes).</summary>
internal IReadOnlyList<string> LabelKeys => CurrentLayout().Labels.Select(l => l.Key).ToList();
/// <summary>The text of the label for <paramref name="key"/>, or null when none is shown.</summary>
internal string LabelText(string key) => CurrentLayout().Labels.FirstOrDefault(l => l.Key == key)?.Text;
/// <summary>Where the label for <paramref name="key"/> is on the control, or null when none is shown.</summary>
public Rectangle? LabelBounds(string key)
{
@@ -142,11 +155,17 @@ namespace OpenNest.Controls
}
/// <summary>
/// Shows <paramref name="drawing"/>. A new shape (<paramref name="newShape"/>) fits the
/// view and puts dragged dimensions back; a changed parameter keeps a hand-set view.
/// Shows <paramref name="drawing"/>, and to its right <paramref name="sideView"/>, a sheet metal
/// part's section, enlarged when it would be too small to read beside the blank. A new
/// shape (<paramref name="newShape"/>) fits the view and puts dragged dimensions back; a
/// changed parameter keeps a hand-set view.
/// </summary>
public void ShowDrawing(Drawing drawing, bool newShape = true)
public void ShowDrawing(Drawing drawing, bool newShape = true, IReadOnlyList<Entity> sideView = null)
{
sideProfile = drawing?.Program != null && sideView != null ? sideView.ToList() : new List<Entity>();
sideOutlines = sideProfile.Count == 0
? new List<Polygon>()
: ShapeBuilder.GetShapes(sideProfile).Select(s => s.ToPolygon()).ToList();
if (newShape)
{
userView = false;
@@ -167,6 +186,7 @@ namespace OpenNest.Controls
var shown = Plate.Parts[0].BoundingBox;
var source = drawing.Program.BoundingBox();
shapeOffset = new Vector(shown.X - source.X, shown.Y - source.Y);
PlaceSideView(shown);
FitUnlessUserView();
}
else
@@ -176,6 +196,54 @@ namespace OpenNest.Controls
}
}
/// <summary>
/// Puts the side view to the right of the blank, centered on it, a quarter of the blank's
/// larger size away. A section under 35% of that size is enlarged to it, so a long part's
/// section stays readable; its dimensions show the true sizes.
/// </summary>
private void PlaceSideView(Box blank)
{
sideScale = 1;
sideOffset = Vector.Zero;
var section = SideBounds();
if (section == null)
return;
var blankSize = System.Math.Max(blank.Length, blank.Width);
var sectionSize = System.Math.Max(section.Length, section.Width);
if (sectionSize > 0)
sideScale = System.Math.Max(1, 0.35 * blankSize / sectionSize);
var gap = 0.25 * blankSize;
sideOffset = new Vector(
blank.Right + gap - section.X * sideScale,
blank.Center.Y - (section.Y + section.Width / 2) * sideScale);
}
/// <summary>The side view's bounds in its own coordinates; null when there is none.</summary>
private Box SideBounds()
{
if (sideProfile.Count == 0)
return null;
var boxes = sideProfile.Select(e => e.BoundingBox).ToList();
var left = boxes.Min(b => b.Left);
var bottom = boxes.Min(b => b.Bottom);
return new Box(left, bottom, boxes.Max(b => b.Right) - left, boxes.Max(b => b.Top) - bottom);
}
/// <summary>The blank's and the side view's bounds together, in view coordinates.</summary>
private Box ViewBounds()
{
var blank = Plate.Parts[0].BoundingBox;
var section = SideBounds();
if (section == null)
return blank;
var left = System.Math.Min(blank.Left, sideOffset.X + section.Left * sideScale);
var bottom = System.Math.Min(blank.Bottom, sideOffset.Y + section.Bottom * sideScale);
var right = System.Math.Max(blank.Right, sideOffset.X + section.Right * sideScale);
var top = System.Math.Max(blank.Top, sideOffset.Y + section.Top * sideScale);
return new Box(left, bottom, right - left, top - bottom);
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
@@ -217,7 +285,7 @@ namespace OpenNest.Controls
return;
}
var box = Plate.Parts[0].BoundingBox;
var box = ViewBounds();
if (box.Length <= 0 || box.Width <= 0)
{
base.ZoomToFit(redraw);
@@ -251,7 +319,7 @@ namespace OpenNest.Controls
UpdateMatrix();
layout = BuildLayout();
var shape = ShapeRect();
var shape = GuiRect(box);
var reach = layout.DimensionBounds;
if (reach.IsEmpty)
break;
@@ -438,12 +506,34 @@ namespace OpenNest.Controls
Renderer.DrawPlate(e.Graphics);
Renderer.DrawLibraryParts(e.Graphics, ColorScheme.Default);
e.Graphics.ResetTransform();
PaintSideView(e.Graphics);
layout = BuildLayout();
PaintAnnotations(e.Graphics, layout);
PaintInfo(e.Graphics);
}
/// <summary>Fills and outlines the side view's section as the blank is drawn.</summary>
private void PaintSideView(Graphics g)
{
if (sideOutlines.Count == 0 || Plate.Parts.Count == 0)
return;
frame = SideFrame();
using var path = new GraphicsPath(FillMode.Alternate);
foreach (var outline in sideOutlines)
{
var points = outline.Vertices.Select(ToScreen).ToArray();
if (points.Length > 2)
path.AddPolygon(points);
}
var scheme = ColorScheme.Default;
using var fill = new SolidBrush(scheme.LibraryFillColor);
using var pen = new Pen(scheme.LibraryOutlineColor);
g.FillPath(fill, path);
g.DrawPath(pen, path);
}
private void PaintInfo(Graphics g)
{
if (infoLines == null)
@@ -534,15 +624,34 @@ namespace OpenNest.Controls
new(TextRenderer.MeasureText(text, Font, System.Drawing.Size.Empty, TextFormatFlags.NoPadding).Width + 2 * LabelPadding,
LabelHeight);
/// <summary>
/// One view's place on the control, the blank's or the side view's: its points are
/// shown at <see cref="Offset"/> + point x <see cref="Scale"/>.
/// </summary>
private readonly record struct Frame(Vector Offset, double Scale, List<Entity> Profile, RectangleF Rect);
private Frame BlankFrame() =>
new(shapeOffset, 1, profile, GuiRect(Plate.Parts[0].BoundingBox));
private Frame SideFrame()
{
var section = SideBounds();
var shown = new Box(sideOffset.X + section.X * sideScale, sideOffset.Y + section.Y * sideScale,
section.Length * sideScale, section.Width * sideScale);
return new(sideOffset, sideScale, sideProfile, GuiRect(shown));
}
private PointF ToScreen(Vector shapePoint)
{
var graph = PointWorldToGraph(shapePoint.X + shapeOffset.X, shapePoint.Y + shapeOffset.Y);
var graph = PointWorldToGraph(shapePoint.X * frame.Scale + frame.Offset.X, shapePoint.Y * frame.Scale + frame.Offset.Y);
return new PointF(graph.X + origin.X, graph.Y + origin.Y);
}
private RectangleF ShapeRect()
/// <summary>A length in the current frame's coordinates, in pixels.</summary>
private float FrameToGui(double length) => LengthWorldToGui(length * frame.Scale);
private RectangleF GuiRect(Box box)
{
var box = Plate.Parts[0].BoundingBox;
var graphTopLeft = PointWorldToGraph(box.X, box.Y + box.Width);
return new RectangleF(graphTopLeft.X + origin.X, graphTopLeft.Y + origin.Y,
LengthWorldToGui(box.Length), LengthWorldToGui(box.Width));
@@ -554,9 +663,14 @@ namespace OpenNest.Controls
if (Plate.Parts.Count == 0)
return result;
var shape = ShapeRect();
var blank = BlankFrame();
var side = sideProfile.Count > 0 ? SideFrame() : (Frame?)null;
foreach (var annotation in annotations)
{
if (annotation.OnSideView && side == null)
continue;
frame = annotation.OnSideView ? side.Value : blank;
var shape = frame.Rect;
var d = annotation.Dimension;
switch (d.Kind)
{
@@ -572,6 +686,7 @@ namespace OpenNest.Controls
}
}
frame = blank;
result.Labels.AddRange(LayoutChips());
return result;
}
@@ -621,15 +736,15 @@ namespace OpenNest.Controls
/// </summary>
private float ExtensionStart(Vector point, Vector side, float reach, RectangleF shape)
{
if (profile.Count == 0 || !(reach > 0))
if (frame.Profile == null || frame.Profile.Count == 0 || !(reach > 0))
return 0;
var limit = reach + (System.Math.Abs(side.X) > System.Math.Abs(side.Y) ? shape.Width : shape.Height);
var travelled = 0f;
for (var i = 0; i < MaxExtensionSteps && travelled < limit; i++)
{
var at = point + side * LengthGuiToWorld(reach - travelled);
var free = LengthWorldToGui(DistanceToProfile(at)) - ExtensionClearance;
var at = point + side * (LengthGuiToWorld(reach - travelled) / frame.Scale);
var free = FrameToGui(DistanceToProfile(at)) - ExtensionClearance;
if (free <= ExtensionPrecision)
break;
travelled += free;
@@ -640,7 +755,7 @@ namespace OpenNest.Controls
private double DistanceToProfile(Vector point)
{
var nearest = double.MaxValue;
foreach (var entity in profile)
foreach (var entity in frame.Profile)
nearest = System.Math.Min(nearest, point.DistanceTo(entity.ClosestPointTo(point)));
return nearest;
}
@@ -648,7 +763,7 @@ namespace OpenNest.Controls
private void AddReferenceCircle(AnnotationLayout result, ShapeDimension d)
{
if (d.CircleCenter is { } center && d.CircleRadius > 0)
result.Circles.Add((ToScreen(center), LengthWorldToGui(d.CircleRadius)));
result.Circles.Add((ToScreen(center), FrameToGui(d.CircleRadius)));
}
/// <summary>The current zoom relative to the fitted view: 1 until zoomed by hand.</summary>
@@ -784,7 +899,7 @@ namespace OpenNest.Controls
return false;
var center = ToScreen(holeCenter);
var radius = LengthWorldToGui(d.HoleRadius);
var radius = FrameToGui(d.HoleRadius);
var toEnd = new PointF(end.X - center.X, end.Y - center.Y);
var distance = (float)System.Math.Sqrt(Dot(toEnd, toEnd));
+7
View File
@@ -23,6 +23,13 @@ namespace OpenNest.Forms
/// <summary>True once the In This Nest tab changed a drawing's required quantity.</summary>
public bool QuantitiesChanged => view.QuantitiesChanged;
/// <summary>Raised with the drawing after each add or quantity edit, while the dialog is still open.</summary>
public event EventHandler<Drawing> NestChanged
{
add => view.NestChanged += value;
remove => view.NestChanged -= value;
}
/// <param name="nest">The nest to add drawings to.</param>
/// <param name="sets">Enables Used in Sets and Add to Set; null hides them.</param>
public DrawingLibraryForm(IDrawingLibraryStore library, string serverUrl, Nest nest, IDrawingSetStore sets = null)
+14
View File
@@ -1538,6 +1538,8 @@ namespace OpenNest.Forms
// The dialog adds drawings and sets quantities as the operator works in it.
using var change = BeginChange("Drawing Library");
var job = (Nest.Material, Nest.Thickness);
// Each add shows on the Drawings tab behind the dialog right away.
form.NestChanged += (_, drawing) => ShowLibraryChange(drawing);
form.ShowDialog(DialogOwner);
if (form.AddedDrawings.Count > 0 || form.QuantitiesChanged)
{
@@ -1555,6 +1557,18 @@ namespace OpenNest.Forms
change.Complete();
}
/// <summary>
/// Lists a drawing the open Drawing Library dialog just added or changed: brings the
/// Drawings tab forward and selects it there.
/// </summary>
internal void ShowLibraryChange(Drawing drawing)
{
UpdateDrawingList();
tabControl1.SelectedTab = tabPage2;
if (drawing != null && drawingListBox1.Items.Contains(drawing))
drawingListBox1.SelectedItem = drawing;
}
private void drawingListBox1_SaveToLibraryRequested(object sender, Drawing drawing)
{
SaveDrawingToLibrary(drawing);
+33 -11
View File
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Globalization;
@@ -388,21 +389,28 @@ namespace OpenNest.Forms
addButton.Enabled = true;
nameTextBox.Text = shape.GenerateName();
previewBox.ShowDrawing(drawing, newShape);
var sideView = shape.GetSideView();
previewBox.ShowDrawing(drawing, newShape, sideView?.Entities);
newShape = false;
var dimensions = shape.GetDimensions()
.Where(d => Parameter(d.Property) != null)
var dimensions = shape.GetDimensions().Select(d => (Dimension: d, OnSideView: false))
.Concat((sideView?.Dimensions ?? Array.Empty<ShapeDimension>()).Select(d => (Dimension: d, OnSideView: true)))
.Where(d => Parameter(d.Dimension.Property) != null)
.ToList();
var placed = dimensions.Select(d => d.Property)
.Concat(dimensions.Select(d => d.CountProperty).Where(p => p != null))
var placed = dimensions.Select(d => d.Dimension.Property)
.Concat(dimensions.Select(d => d.Dimension.CountProperty).Where(p => p != null))
.ToHashSet();
previewBox.SetAnnotations(
dimensions.Select(d => new ShapePreviewControl.Annotation(d,
d.Prefix + FormatLength((double)values[d.Property]),
d.CountProperty != null && values.TryGetValue(d.CountProperty, out var count)
? $"x {count} {d.CountNoun}"
: null)).ToList(),
dimensions.Select(item =>
{
var d = item.Dimension;
return new ShapePreviewControl.Annotation(d,
d.Prefix + FormatLength((double)values[d.Property]),
d.CountProperty != null && values.TryGetValue(d.CountProperty, out var count)
? $"x {count} {d.CountNoun}"
: null,
item.OnSideView);
}).ToList(),
parameters.Where(p => !placed.Contains(p.Name)).Select(NoteFor).ToList());
var bb = drawing.Program.BoundingBox();
@@ -444,14 +452,18 @@ namespace OpenNest.Forms
var text = value switch
{
bool b => b ? "Yes" : "No",
double d when IsUnitless(prop) => d.ToString("0.####", CultureInfo.CurrentCulture),
double d => FormatLength(d),
null => "None",
_ => value.ToString(),
};
var enabled = prop.Name != nameof(PipeFlangeShape.PipeSize) || !Equals(values.GetValueOrDefault(nameof(PipeFlangeShape.Blind)), true);
return new ShapePreviewControl.Note(prop.Name, $"{FriendlyName(prop.Name)}: {text}", enabled);
var label = prop.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName ?? FriendlyName(prop.Name);
return new ShapePreviewControl.Note(prop.Name, $"{label}: {text}", enabled);
}
private static bool IsUnitless(PropertyInfo prop) => prop.IsDefined(typeof(UnitlessAttribute));
internal static string FormatLength(double inches) => Fraction.Format(inches) + "\"";
/// <summary>The pipe sizes that fit inside the bolt holes: pipe OD + clearance &lt; pattern - hole.</summary>
@@ -669,6 +681,16 @@ namespace OpenNest.Forms
return null;
}
if (IsUnitless(prop))
{
if (!double.TryParse(text?.Trim(), NumberStyles.Float, CultureInfo.CurrentCulture, out var number) || !double.IsFinite(number))
return $"'{text}' is not a number.";
if (number < 0)
return "The value cannot be negative.";
value = number;
return null;
}
double length;
try
{
+14 -13
View File
@@ -443,6 +443,12 @@ plans the insert (`OpenNest.Data.LibraryDrawingInsert`) before changing anything
revisions through Update Drawings.
- Another drawing with the same name: refused, naming both.
Each add shows a green banner above the list naming what was added (or how many
more of a drawing already in the nest, and the new required quantity); it stays
until the next add replaces it or it is closed. The dialog stays open for more
adds, and the main window lists the drawing on its Drawings tab behind the
dialog at once, brings that tab forward and selects it there.
The added drawing is an independent copy carrying a library link (server key,
id, revision and a snapshot of the library details) that is saved with the nest
(see [the nest file format](nest-file-format.md#drawing-library-links)). Editing it
@@ -454,8 +460,8 @@ library or not, cutoffs excluded: name, library revision ("Not from the library"
or "(other server)" when it is linked elsewhere), and the Required, Nested and
Remaining quantities, with totals below. It refreshes after every add. Required
is edited in place (0 to 99,999; one click starts editing, a bad number keeps
the editor open with an error) and applies to the nest at once, like an add;
the main window's drawing list refreshes when the dialog closes.
the editor open with an error) and applies to the nest at once, like an add,
and the main window's drawing list shows the change at once.
The browser's **Cut first** column shows the setting; **Size (in)** (longer x
shorter side) and **Holes** show the measured summary, blank until it is measured
@@ -1305,17 +1311,12 @@ under a local name such as `server.env`, and set:
one layer: verify that the network/firewall admits only trusted clients.
- `OPENNEST_HOST_PORT` (default 8090) and `OPENNEST_DATA_VOLUME` (default `opennest-data`).
Publication requires an existing verified private package; first-package
initialization needs separate owner authorization outside the release workflow.
An authorized deployment operator must obtain a
`read:packages` token out of band and log in on the deployment host using
`docker login ghcr.io -u <github-user> --password-stdin`, piping the token from a
secret manager or a protected prompt (never a token literal in shell history).
Keep Docker's credentials protected on that host; do not put credentials in
`server.env`, Compose, the image, or source control. Login/pull success does not
authorize making the package public. Until an approved image has passed the
published-digest smoke, the reference below is only a template, not an available
verified image.
The published image is public, so the deployment host pulls it without a GitHub
login or token. A public image does not make the server safe to expose: it has no
authentication, so keep it on a trusted LAN as described above. Do not put
credentials in `server.env`, Compose, the image, or source control. Until an
approved image has passed the published-digest smoke, the reference below is only
a template, not an available verified image.
```sh
compose="docker compose --env-file server.env -f compose.server.yaml"
+26 -17
View File
@@ -92,23 +92,32 @@ server/image gates, and pushes the *same smoked image* to
be absent; retries after even a partial upload stop instead of overwriting. There
are no `latest`, major, or minor aliases. Do not dispatch just to test publication.
Publication requires an **existing owner-verifiable private package**, linked to
`ajisaacs/OpenNest`, with repository Actions access (normally inherited from the
link). The job uses only its scoped `GITHUB_TOKEN`. All package metadata 404s are
refused: GitHub can mask an inaccessible private package as `Not Found`. Opaque
registry token success, an empty tag list, or a registry 404 proves neither package
absence nor privacy and cannot override the metadata check. Explicit reduced
scope and failed registry read access also stop the job. The job rechecks private
association after upload.
The image is **public** (owner decision): the source repository is public, and
anyone may pull the image without a GitHub login. Publishing it does not make a
server reachable; the server has no authentication and stays on a trusted LAN
(see [nest storage](nest-storage.md#deploying-with-compose)).
First-package initialization is a separately owner-authorized prerequisite
outside this workflow. Until the private package, repository link, and Actions
access can be verified, publication remains blocked while read-only validation
can pass. There
is no automatic bootstrap, extra PAT, absence assertion, or bypass setting. A
local credential's Packages API 403 proves neither absence nor privacy. No
workflow changes visibility. Public availability needs separate owner approval
and a later anonymous-pull check; it is not approved here.
The job builds, tests and smokes the tag's own tree, but the publication policy
(preflight before upload and readback after it) always comes from `master`'s copy
of `scripts/server_image_release.py`, so an older tag publishes under the current
policy. The job uses only its scoped `GITHUB_TOKEN`. An existing package must be public
and linked to `ajisaacs/OpenNest`; a private package or one linked to another
repository stops the job before upload. The first publication creates the
package: GitHub's own package-not-found response is accepted only when the
registry also reports the repository unknown, because a package hidden from the
token still has a registry repository. Every other metadata error, denial,
reduced registry scope or failed tag-list read stops the job. Because the source
repository is public and the image carries its `org.opencontainers.image.source`
label, the new package is linked to the repository and public. The job rechecks
public visibility and association after upload, and the clean-runner
verification pulls the returned digest **without logging in**, which proves
anonymous pulls work.
If a first publication fails that recheck (the package came out private), the two
tags are already uploaded and a retry refuses them: in the package settings make
it public and confirm the anonymous pull by hand, or delete the package and
dispatch again. There is no extra PAT or bypass setting, and no workflow changes
visibility.
The local gate reads `docker image save` to hash the actual config and verify each
layer against its ordered uncompressed rootfs digest. It rejects unexpected
@@ -137,6 +146,6 @@ python3 -m unittest discover -s scripts -p test_server_image_release.py -v
```
Deployment is deliberately separate; use the verified digest and the
[private pull/Compose procedure](nest-storage.md#deploying-with-compose). No
[pull/Compose procedure](nest-storage.md#deploying-with-compose). No
publication, release creation, deployment, or visibility change is implied by
adding or validating this workflow.
+18 -6
View File
@@ -117,12 +117,20 @@ def absent(status, headers, body):
def package_policy(status, headers, body):
"""Return True when GitHub reports no package yet (first publication).
The repository is public and the image carries its source label, so the first
GITHUB_TOKEN push creates a public package linked to it; readback and the
anonymous pull prove that afterwards. Any other shape fails closed."""
data = json_body(body)
require(isinstance(data, dict), "malformed package metadata")
require(status == 200, "package metadata inaccessible; privacy unknown")
if status == 404 and data.get("message") in ("Package not found.", "Not Found") and \
str(data.get("documentation_url", "")).startswith("https://docs.github.com/rest/packages"):
return True
require(status == 200, "package metadata inaccessible; visibility unknown")
require(data.get("name") == PACKAGE and data.get("package_type") == "container" and
data.get("visibility") == "private" and isinstance(data.get("repository"), dict) and
data["repository"].get("full_name") == REPO, "package privacy/association mismatch")
data.get("visibility") == "public" and isinstance(data.get("repository"), dict) and
data["repository"].get("full_name") == REPO, "package visibility/association mismatch")
return False
@@ -188,8 +196,12 @@ def preflight(client, release_version, sha):
repo = json_body(body)
require(status == 200 and isinstance(repo, dict) and repo.get("full_name") == REPO and
repo.get("default_branch") == "master", "repository/default branch authorization unproven")
package_policy(*client.get(PACKAGE_API))
first_publication = package_policy(*client.get(PACKAGE_API))
tags_response = client.get(registry_path("tags/list"))
if first_publication:
# A package hidden from this token would still have a registry repository.
require(absent(*tags_response), "package metadata missing but registry repository exists")
return {"package": IMAGE, "visibility": "public", "first_publication": True}
require(tags_response[0] == 200, "existing package registry read access unproven")
data = json_body(tags_response[2])
require(isinstance(data, dict) and data.get("name") == REGISTRY_NAME and
@@ -200,7 +212,7 @@ def preflight(client, release_version, sha):
require(not any(tag in (data["tags"] or []) for tag in reserved_tags), "refusing existing immutable tag")
for tag in reserved_tags:
require(absent(*client.get(registry_path("manifests/" + tag))), "refusing existing immutable tag")
return {"package": IMAGE, "visibility": "private"}
return {"package": IMAGE, "visibility": "public"}
def content_digest(body):
@@ -439,7 +451,7 @@ def main():
local = local_identity(os.environ.get("LOCAL_IMAGE", ""))
if args.operation == "readback":
client = Client()
package_policy(*client.get(PACKAGE_API))
require(not package_policy(*client.get(PACKAGE_API)), "package metadata missing after upload")
directory = pathlib.Path(os.environ.get("METADATA_DIR", ".hermes/server-image-metadata"))
try:
previous = json_body((directory / "local.json").read_bytes())
+60 -26
View File
@@ -19,6 +19,8 @@ assert SPEC is not None and SPEC.loader is not None
release = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(release)
SHA = "a" * 40
# GitHub's real answer for a user package that does not exist (observed 2026-11-17).
GITHUB_PACKAGE_NOT_FOUND = {"message": "Package not found.", "documentation_url": "https://docs.github.com/rest/packages/packages#get-a-package-for-a-user", "status": "404"}
BASE = "mcr.microsoft.com/dotnet/aspnet@sha256:" + "b" * 64
LAYER = b"deterministic synthetic rootfs layer"
LAYER_GZIP = gzip.compress(LAYER, mtime=0)
@@ -123,23 +125,23 @@ class RegistrySafety(unittest.TestCase):
release.absent(*response(status, body))
self.assertFalse(release.absent(*response(200, {"schemaVersion": 2})))
def test_private_associated_package(self):
package = {"name": release.PACKAGE, "package_type": "container", "visibility": "private",
def test_public_associated_package(self):
package = {"name": release.PACKAGE, "package_type": "container", "visibility": "public",
"repository": {"full_name": release.REPO}}
self.assertFalse(release.package_policy(*response(200, package)))
for key, value in (("visibility", "public"), ("visibility", "internal"),
for key, value in (("visibility", "private"), ("visibility", "internal"),
("repository", None), ("repository", {"full_name": "other/OpenNest"}),
("name", "other"), ("package_type", "npm")):
wrong = dict(package, **{key: value})
with self.assertRaises(release.ReleaseError):
release.package_policy(*response(200, wrong))
def test_package_metadata_404_never_authorizes_bootstrap(self):
with self.assertRaises(release.ReleaseError):
release.package_policy(*response(404, {
"message": "Not Found", "documentation_url": "https://docs.github.com/rest/packages"}))
def test_github_not_found_metadata_means_first_publication(self):
self.assertTrue(release.package_policy(*response(404, dict(GITHUB_PACKAGE_NOT_FOUND))))
for status, body in ((403, {"message": "Resource not accessible"}), (404, {}),
(404, {"message": "Not Found", "documentation_url": "https://evil.test"})):
(404, {"message": "Not Found", "documentation_url": "https://evil.test"}),
(404, dict(GITHUB_PACKAGE_NOT_FOUND, message="Resource not accessible")),
(404, dict(GITHUB_PACKAGE_NOT_FOUND, documentation_url="https://docs.github.com/rest/repos"))):
with self.assertRaises(release.ReleaseError):
release.package_policy(*response(status, body))
@@ -151,9 +153,9 @@ class RegistrySafety(unittest.TestCase):
release.registry_token(status, encoded(body))
def preflight_client(self, package_status=200, tags=None):
package = {"name": release.PACKAGE, "package_type": "container", "visibility": "private",
package = {"name": release.PACKAGE, "package_type": "container", "visibility": "public",
"repository": {"full_name": release.REPO}}
missing = {"message": "Not Found", "documentation_url": "https://docs.github.com/rest/packages"}
missing = dict(GITHUB_PACKAGE_NOT_FOUND)
return FakeClient({
release.REPO_API: response(200, {"full_name": release.REPO, "default_branch": "master"}),
release.PACKAGE_API: response(package_status, package if package_status == 200 else missing),
@@ -171,11 +173,20 @@ class RegistrySafety(unittest.TestCase):
with self.assertRaises(release.ReleaseError):
release.preflight(client, "1.2.3", SHA)
def test_missing_metadata_denies_regardless_of_registry_tags(self):
with self.assertRaises(release.ReleaseError):
release.preflight(self.preflight_client(404), "1.2.3", SHA)
with self.assertRaises(release.ReleaseError):
release.preflight(self.preflight_client(404, ["old"]), "1.2.3", SHA)
def test_first_publication_requires_an_absent_registry_repository(self):
client = self.preflight_client(404)
unknown = response(404, {"errors": [{"code": "NAME_UNKNOWN"}]})
client.responses[release.registry_path("tags/list")] = unknown
self.assertEqual(release.preflight(client, "1.2.3", SHA),
{"package": release.IMAGE, "visibility": "public", "first_publication": True})
for tags in ([], ["old"]):
with self.subTest(tags=tags), self.assertRaises(release.ReleaseError):
release.preflight(self.preflight_client(404, tags), "1.2.3", SHA)
for denied in (response(404, {"errors": [{"code": "DENIED"}]}), response(401, {}), response(403, {})):
client = self.preflight_client(404)
client.responses[release.registry_path("tags/list")] = denied
with self.subTest(denied=denied[0]), self.assertRaises(release.ReleaseError):
release.preflight(client, "1.2.3", SHA)
def test_preflight_transport_metadata_and_tag_list_errors_fail_closed(self):
for path in (release.REPO_API, release.PACKAGE_API, release.registry_path("tags/list")):
@@ -502,10 +513,22 @@ class ArchiveIdentity(unittest.TestCase):
with self.assertRaisesRegex(release.ReleaseError, "rootfs chain"):
release.readback(client, "1.2.3", SHA, local)
def test_readback_refuses_a_package_still_missing_after_upload(self):
client, local = ReadbackSafety().fixture()
client.responses[release.PACKAGE_API] = response(404, dict(GITHUB_PACKAGE_NOT_FOUND))
with tempfile.TemporaryDirectory() as directory:
env = {"VERSION": "1.2.3", "SOURCE_SHA": SHA, "METADATA_DIR": directory}
with mock.patch.dict(os.environ, env), mock.patch.object(release, "git", return_value=SHA), \
mock.patch.object(release, "Client", return_value=client), \
mock.patch.object(release, "local_identity", return_value=local), \
mock.patch("sys.argv", ["helper", "readback"]):
with self.assertRaisesRegex(release.ReleaseError, "missing after upload"):
release.main()
def test_readback_requires_the_pre_smoke_identity_stamp(self):
client, local = ReadbackSafety().fixture()
client.responses[release.PACKAGE_API] = response(200, {"name": release.PACKAGE,
"package_type": "container", "visibility": "private", "repository": {"full_name": release.REPO}})
"package_type": "container", "visibility": "public", "repository": {"full_name": release.REPO}})
with tempfile.TemporaryDirectory() as directory:
env = {"VERSION": "1.2.3", "SOURCE_SHA": SHA, "METADATA_DIR": directory}
stamp = pathlib.Path(directory) / "local.json"
@@ -535,15 +558,12 @@ class ArchiveIdentity(unittest.TestCase):
class SpecRegressions(unittest.TestCase):
def test_masked_package_404_denies_even_empty_or_missing_registry(self):
safety = RegistrySafety()
for registry in (response(200, {"name": release.REGISTRY_NAME, "tags": []}),
response(404, {"errors": [{"code": "NAME_UNKNOWN"}]})):
client = safety.preflight_client(404)
client.responses[release.registry_path("tags/list")] = registry
with self.subTest(registry=registry), self.assertRaises(release.ReleaseError):
release.preflight(client, "1.2.3", SHA)
self.assertNotIn(release.registry_path("tags/list"), client.calls)
def test_masked_package_404_denies_an_existing_registry_repository(self):
client = RegistrySafety().preflight_client(404)
client.responses[release.registry_path("tags/list")] = response(200, {"name": release.REGISTRY_NAME, "tags": []})
with self.assertRaises(release.ReleaseError):
release.preflight(client, "1.2.3", SHA)
self.assertFalse(any("/manifests/" in call for call in client.calls))
def test_opaque_reduced_scope_token_cannot_authorize_masked_metadata(self):
with mock.patch.dict("os.environ", {"GITHUB_TOKEN": "test-only", "GITHUB_REPOSITORY": release.REPO}):
@@ -553,7 +573,7 @@ class SpecRegressions(unittest.TestCase):
token["scope"] = scope
responses = [response(200, token),
response(200, {"full_name": release.REPO, "default_branch": "master"}),
response(404, {"message": "Not Found", "documentation_url": "https://docs.github.com/rest/packages"}),
response(404, dict(GITHUB_PACKAGE_NOT_FOUND)),
response(200, {"name": release.REGISTRY_NAME, "tags": []}),
response(404, {"errors": [{"code": "MANIFEST_UNKNOWN"}]}),
response(404, {"errors": [{"code": "MANIFEST_UNKNOWN"}]})]
@@ -706,6 +726,20 @@ class WorkflowBehavior(unittest.TestCase):
self.assertNotIn("'release'", condition)
self.assertIn("github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/master'", condition)
def test_publication_policy_comes_from_master_not_the_tagged_tree(self):
# The tag's tree is built and tested, but an older tag's helper must not
# decide package visibility: preflight and readback run master's copy.
workflow = pathlib.Path(__file__).resolve().parents[1] / ".github/workflows/server-image.yml"
publish = workflow.read_text().split("\n publish:\n", 1)[1].split("\n verify-published:\n", 1)[0]
source = publish.index("server_image_release.py source")
copy = publish.index('cp scripts/server_image_release.py "$RELEASE_POLICY"')
tag_checkout = publish.index("ref: ${{ steps.source.outputs.source_sha }}")
self.assertLess(source, copy)
self.assertLess(copy, tag_checkout)
for operation in ("preflight", "readback"):
self.assertIn('python3 "$RELEASE_POLICY" ' + operation, publish)
self.assertNotIn("scripts/server_image_release.py " + operation, publish)
def test_build_log_pipeline_preserves_docker_failure(self):
workflow = pathlib.Path(__file__).resolve().parents[1] / ".github/workflows/server-image.yml"
lines = workflow.read_text().splitlines()