feat(avalonia): create new nests from File > New, Ctrl+N, New and +

Move the File > New rules into OpenNest.Desktop (NewNestSource): nest
defaults, the default machine with its clamps and support grid, Made By
and the year's next name, from the nest server in Database mode and the
counter both apps keep in user-settings.json otherwise. The WinForms
factory now delegates to it.

The Avalonia app opens a new nest in a tab with no file (NestTabs.Add),
off the UI thread and one at a time, and its nest view keeps an empty
last plate as the WinForms nest window does, so a new nest shows Plate 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-11-13 17:31:18 -05:00
1 parent 9b7082e92f
commit 7f1cff301a
9 files changed
+525 -80

No files matched your search

+14
View File
@@ -21,6 +21,20 @@ namespace OpenNest.Avalonia
public static MachineSettingsSource Machines { get; } =
new(Shared, new MachineUserSettingsFile(UserSettingsFile.DefaultPath));
/// <summary>The storage mode and nest server, read once from storage.json as <see cref="Shared"/> does.</summary>
private static readonly NestStorageSettings Storage = NestStorageSettings.Load(NestStorageSettings.DefaultPath);
private static RemoteNestRepository repository;
/// <summary>
/// File > New nests, numbered by the nest server in Database mode and otherwise by the
/// counter both apps keep in user-settings.json.
/// </summary>
public static NewNestSource NewNests { get; } = new(
Machines,
new NewNestUserSettingsFile(UserSettingsFile.DefaultPath),
() => Storage.IsDatabaseMode ? repository ??= new RemoteNestRepository(Storage.ServerUrl) : null);
/// <summary>The post processors loaded from Posts/ beside the app, by load order.</summary>
public static IReadOnlyList<IPostProcessor> PostProcessors { get; private set; } = [];
+4 -2
View File
@@ -6,6 +6,7 @@
<DockPanel>
<Menu DockPanel.Dock="Top">
<MenuItem Header="_File">
<MenuItem x:Name="NewMenuItem" Header="_New" InputGesture="Ctrl+N" Click="OnNew" />
<MenuItem x:Name="OpenMenuItem" Header="_Open..." InputGesture="Ctrl+O" Click="OnOpen" />
<Separator />
<MenuItem x:Name="SaveMenuItem" Header="_Save" InputGesture="Ctrl+S" Click="OnSave" />
@@ -45,6 +46,7 @@
<Border DockPanel.Dock="Top" Padding="4" BorderThickness="0,0,0,1" BorderBrush="#D0D0D0">
<StackPanel Orientation="Horizontal" Spacing="4">
<Button x:Name="NewButton" Content="New" Click="OnNew" />
<Button x:Name="OpenButton" Content="Open" Click="OnOpen" />
<Button x:Name="SaveButton" Content="Save" Click="OnSave" />
<Button x:Name="SaveAsButton" Content="Save As" Click="OnSaveAs" />
@@ -56,7 +58,7 @@
</Border>
<Border DockPanel.Dock="Bottom" Padding="6,3" Background="#F0F0F0">
<TextBlock x:Name="Status" Text="Open a .nest file to begin." />
<TextBlock x:Name="Status" Text="Create a new nest or open a .nest file to begin." />
</Border>
<!-- One tab per open nest, along the bottom of the window. -->
@@ -67,7 +69,7 @@
</Border>
<Panel>
<TextBlock x:Name="EmptyHint" Text="Open a .nest file to begin." Foreground="#6B7280"
<TextBlock x:Name="EmptyHint" Text="Create a new nest or open a .nest file to begin." Foreground="#6B7280"
HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="15" />
<ContentControl x:Name="NestHost" />
</Panel>
+55 -11
View File
@@ -32,6 +32,8 @@ namespace OpenNest.Avalonia
private NestTab nestingTab;
private Task autoNest = Task.CompletedTask;
private bool closeConfirmed;
// A File > New waiting on the machines or the nest number.
private bool creatingNest;
private bool snapshotMode;
// A save or export waiting on its file picker or write; another one waits for it.
private bool writingFile;
@@ -59,6 +61,11 @@ namespace OpenNest.Avalonia
ColorSchemeRegistry.ApplySaved(Data.UserSettingsFile.Read(Data.UserSettingsFile.DefaultPath));
tabs.Changed += (_, _) => ShowActiveTab();
KeyBindings.Add(new KeyBinding
{
Gesture = new KeyGesture(Key.N, KeyModifiers.Control),
Command = new Command(() => OnNew(null, null)),
});
KeyBindings.Add(new KeyBinding
{
Gesture = new KeyGesture(Key.O, KeyModifiers.Control),
Command = new Command(() => OnOpen(null, null)),
@@ -111,14 +118,7 @@ namespace OpenNest.Avalonia
return document;
});
if (!views.ContainsKey(tab))
{
var view = new NestView(tab);
RestoreViewToggles(view);
view.ViewChanged += (_, _) => { if (view == ActiveView) UpdateStatus(); };
views[tab] = view;
notice = null;
ShowActiveTab();
}
AddView(tab);
if (warnings.Count > 0)
{
var count = warnings.Count == 1
@@ -136,6 +136,48 @@ namespace OpenNest.Avalonia
}
}
/// <summary>
/// Opens a new nest from the nest defaults, the default machine with its clamps and
/// support grid, and the year's next name, in a new tab, as File > New does in WinForms.
/// </summary>
public async Task NewNestAsync()
{
// One at a time, so two nests never take the same number.
if (creatingNest)
return;
creatingNest = true;
NewNest created;
try
{
// The machines finish loading first; reading them and the nest number may wait
// on the nest server, so neither runs on the UI thread.
await MachinesLoaded;
created = await Task.Run(() => DesktopSettings.NewNests.CreateAsync());
}
catch (Exception ex)
{
ShowNotice($"Could not create a new nest: {ex.Message}");
return;
}
finally
{
creatingNest = false;
}
AddView(tabs.Add(new Document { Nest = created.Nest }));
if (created.Warning != null)
await ConfirmDialog.ShowAsync(this, "Nest Defaults", created.Warning);
}
private void AddView(NestTab tab)
{
var view = new NestView(tab);
RestoreViewToggles(view);
view.ViewChanged += (_, _) => { if (view == ActiveView) UpdateStatus(); };
views[tab] = view;
notice = null;
ShowActiveTab();
}
/// <summary>
/// Restores the window's size, position and maximized state from the user settings the
/// WinForms app shares, and saves them on close. Not used for --snapshot, whose image
@@ -204,8 +246,8 @@ namespace OpenNest.Avalonia
Background = Brushes.Transparent,
VerticalAlignment = VerticalAlignment.Top,
};
ToolTip.SetTip(add, "Open a nest");
add.Click += OnOpen;
ToolTip.SetTip(add, "New nest");
add.Click += OnNew;
TabStrip.Children.Add(add);
}
@@ -536,6 +578,8 @@ namespace OpenNest.Avalonia
tabs.Activate(((tabs.ActiveIndex + step) % count + count) % count);
}
private async void OnNew(object sender, RoutedEventArgs e) => await NewNestAsync();
private async void OnOpen(object sender, RoutedEventArgs e)
{
var files = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
@@ -698,7 +742,7 @@ namespace OpenNest.Avalonia
if (canvas?.Plate == null)
{
var empty = view == null
? "Open a .nest file to begin."
? "Create a new nest or open a .nest file to begin."
: $"{view.Tab.Name} No plates";
Status.Text = notice ?? empty;
return;
+4
View File
@@ -43,6 +43,10 @@ namespace OpenNest.Avalonia
public void Refresh(int selectIndex)
{
var nest = Tab.Document.Nest;
// As the WinForms nest window: one empty plate stays at the end to nest onto, so a
// new nest shows Plate 1. Files leave empty plates out, so saving is unchanged.
using (var plates = new PlateManager(nest))
plates.EnsureSentinel();
Canvas.ClearCache();
PlateList.ItemsSource = nest.Plates
.Select((plate, i) =>
+18
View File
@@ -35,6 +35,24 @@ public class NestTabsTests
Assert.Equal(FullPath("b.nest"), b.Path);
}
[Fact]
public void Add_ANewNestTakesATabWithNoFileUntilSaved()
{
var tabs = new NestTabs();
tabs.Open(FullPath("a.nest"), Load);
var changes = 0;
tabs.Changed += (_, _) => changes++;
var created = tabs.Add(new Document { Nest = new Nest { Name = "N26-223" } });
Assert.Same(created, tabs.Active);
Assert.Equal(["a", "N26-223"], tabs.Tabs.Select(t => t.Name));
Assert.Null(created.Path);
Assert.Null(created.SavePath);
Assert.False(created.Modified);
Assert.Equal(1, changes);
}
[Fact]
public void Open_AFileAlreadyOpen_ActivatesItsTabWithoutLoadingAgain()
{
@@ -0,0 +1,201 @@
using OpenNest.Data;
using OpenNest.Geometry;
namespace OpenNest.Desktop.Tests;
/// <summary>
/// File > New in both desktop apps: the nest starts from the nest defaults and the default
/// machine, and takes the year's next name from the nest server in Database mode or this PC's
/// counter, which the WinForms and Avalonia apps share in user-settings.json.
/// </summary>
public sealed class NewNestSourceTests : IDisposable
{
private static readonly DateTime Now = new(2026, 11, 13, 9, 30, 0);
private readonly string directory = Path.Combine(Path.GetTempPath(), "OpenNestDesktopTests", Guid.NewGuid().ToString("N"));
private readonly MemoryNewNestSettings user = new();
public NewNestSourceTests() => Directory.CreateDirectory(directory);
public void Dispose()
{
try { Directory.Delete(directory, recursive: true); } catch (IOException) { }
}
private string MachinesDirectory => Path.Combine(directory, "Machines");
private string DefaultsPath => Path.Combine(directory, "defaults.json");
private string UserSettingsPath => Path.Combine(directory, "user-settings.json");
private MachineSettingsSource Machines() =>
new(new SharedSettingsSource(() => new NestStorageSettings(), _ => throw new InvalidOperationException("File mode")),
new MemoryUserSettings(), MachinesDirectory, DefaultsPath,
Path.Combine(directory, "clamps.json"), Path.Combine(directory, "grid.json"));
private NewNestSource Source(INewNestUserSettings? settings = null, Func<INestRepository?>? repository = null) =>
new(Machines(), settings ?? user, repository!, () => Now);
[Fact]
public async Task FileMode_NamesFromThisPcsCounterAndAdvancesIt()
{
user.NestNumber = 5;
user.LastNestCreatedDate = new DateTime(2026, 1, 2);
var created = await Source().CreateAsync();
Assert.Equal(NestNames.Format(2026, 5), created.Nest.Name);
Assert.Equal(6, user.NestNumber);
Assert.Equal(Now.Date, user.LastNestCreatedDate);
Assert.True(user.Saves > 0);
Assert.Equal(Now, created.Nest.DateCreated);
Assert.Null(created.Warning);
}
[Fact]
public async Task FileMode_RestartsTheCounterInANewYear()
{
user.NestNumber = 40;
user.LastNestCreatedDate = new DateTime(2025, 12, 31);
var created = await Source().CreateAsync();
Assert.Equal(NestNames.Format(2026, 1), created.Nest.Name);
Assert.Equal(2, user.NestNumber);
}
[Fact]
public async Task DatabaseMode_TheServerNumbersItAndTheCounterStaysAbove()
{
user.NestNumber = 3;
user.LastNestCreatedDate = Now.Date;
var repository = new NumberingRepository { NextNumber = 17 };
var created = await Source(repository: () => repository).CreateAsync();
Assert.Equal(NestNames.Format(2026, 17), created.Nest.Name);
Assert.Equal(18, user.NestNumber);
}
[Fact]
public async Task DatabaseMode_AnUnreachableServerFallsBackToTheCounter()
{
user.NestNumber = 3;
user.LastNestCreatedDate = Now.Date;
var repository = new NumberingRepository { Failure = new HttpRequestException("offline") };
var created = await Source(repository: () => repository).CreateAsync();
Assert.Equal(NestNames.Format(2026, 3), created.Nest.Name);
Assert.Equal(4, user.NestNumber);
}
[Fact]
public async Task StartsFromTheNestDefaultsAndTheDefaultMachine()
{
var machine = new MachineConfig { Name = "Fiber" };
new LocalJsonProvider(MachinesDirectory).SaveMachine(machine);
new NestDefaults { Units = Units.Millimeters, Size = new Size(3000, 1500), PartSpacing = 4, MachineId = machine.Id }
.Save(DefaultsPath);
var nest = (await Source().CreateAsync()).Nest;
Assert.Equal(Units.Millimeters, nest.Units);
Assert.Equal(new Size(3000, 1500), nest.PlateDefaults.Size);
Assert.Equal(4, nest.PlateDefaults.PartSpacing);
Assert.Equal(machine.Id, nest.Machine?.Id);
Assert.Empty(nest.Plates);
}
[Fact]
public async Task UnreadableNestDefaults_AreReportedWithTheNest()
{
File.WriteAllText(DefaultsPath, "{ not json");
var created = await Source().CreateAsync();
Assert.NotNull(created.Nest);
Assert.Contains("could not be read", created.Warning);
}
[Fact]
public async Task MadeBy_IsTheRememberedNameElseTheUserName()
{
user.MadeBy = " Synthetic operator ";
Assert.Equal("Synthetic operator", (await Source().CreateAsync()).Nest.MadeBy);
user.MadeBy = " ";
Assert.Equal(Environment.UserName, (await Source().CreateAsync()).Nest.MadeBy);
}
[Fact]
public async Task SettingsFile_SharesTheWinFormsNamesAndText()
{
// As System.Configuration writes them; MadeBy is only read.
UserSettingsFile.Write(UserSettingsPath, new Dictionary<string, string>
{
["NestNumber"] = "9",
["LastNestCreatedDate"] = "2026-03-04",
["MadeBy"] = "Synthetic operator",
["DefaultUnit"] = "Millimeters",
});
var created = await Source(new NewNestUserSettingsFile(UserSettingsPath)).CreateAsync();
Assert.Equal(NestNames.Format(2026, 9), created.Nest.Name);
Assert.Equal("Synthetic operator", created.Nest.MadeBy);
var stored = UserSettingsFile.Read(UserSettingsPath);
Assert.Equal("10", stored["NestNumber"]);
Assert.Equal("2026-11-13", stored["LastNestCreatedDate"]);
Assert.Equal("Millimeters", stored["DefaultUnit"]);
}
[Fact]
public void SettingsFile_ReadsTheWinFormsDefaultDateAndFallsBackWhenMissing()
{
var settings = new NewNestUserSettingsFile(UserSettingsPath);
Assert.Equal(1, settings.NestNumber);
Assert.Equal(2015, settings.LastNestCreatedDate.Year);
UserSettingsFile.Write(UserSettingsPath, new Dictionary<string, string>
{
["NestNumber"] = "not a number",
["LastNestCreatedDate"] = "04/08/2024 19:30:00",
});
Assert.Equal(1, settings.NestNumber);
Assert.Equal(new DateTime(2024, 4, 8, 19, 30, 0), settings.LastNestCreatedDate);
Assert.Equal("04/08/2024 19:30:00", NewNestUserSettingsFile.FormatDate(settings.LastNestCreatedDate));
}
private sealed class MemoryNewNestSettings : INewNestUserSettings
{
public int NestNumber { get; set; } = 1;
public DateTime LastNestCreatedDate { get; set; }
public string MadeBy { get; set; } = "";
public int Saves { get; private set; }
public void Save() => Saves++;
}
private sealed class NumberingRepository : INestRepository
{
public int NextNumber { get; set; } = 1;
public Exception? Failure { get; set; }
public Task<int> AllocateNestNumberAsync(int year, CancellationToken cancellationToken = default) =>
Failure != null ? Task.FromException<int>(Failure) : Task.FromResult(NextNumber++);
public Task<NestPage> QueryAsync(NestQuery query, CancellationToken ct = default) => throw new NotSupportedException();
public Task<IReadOnlyList<NestRecord>> ListAsync(CancellationToken ct = default) => throw new NotSupportedException();
public Task<NestRecord?> GetMetadataAsync(Guid id, CancellationToken ct = default) => throw new NotSupportedException();
public Task<byte[]?> GetFileAsync(Guid id, CancellationToken ct = default) => throw new NotSupportedException();
public Task<NestRecord> UploadAsync(byte[] file, NestRecord record, CancellationToken ct = default) => throw new NotSupportedException();
public Task<NestRecord> UpdateFileAsync(Guid id, byte[] file, NestRecord record, CancellationToken ct = default) => throw new NotSupportedException();
public Task<NestRecord> UpdateMetadataAsync(Guid id, NestRecord record, CancellationToken ct = default) => throw new NotSupportedException();
public Task DeleteAsync(Guid id, CancellationToken ct = default) => throw new NotSupportedException();
}
}
+14
View File
@@ -95,6 +95,20 @@ namespace OpenNest.Desktop
return tab;
}
/// <summary>
/// Adds <paramref name="document"/>, a nest with no file yet (File > New), in a new
/// active tab after the others. Its first Save asks for a file.
/// </summary>
public NestTab Add(Document document)
{
ArgumentNullException.ThrowIfNull(document);
var tab = new NestTab(document, null);
tabs.Add(tab);
ActiveIndex = tabs.Count - 1;
Changed?.Invoke(this, EventArgs.Empty);
return tab;
}
public void Activate(int index)
{
if (index < 0 || index >= tabs.Count)
+188
View File
@@ -0,0 +1,188 @@
using System;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using OpenNest.Data;
namespace OpenNest.Desktop;
/// <summary>
/// The per-user settings File > New reads and advances: the local nest counter, the date it
/// last counted from (the counter restarts each year) and the Made By the user last typed.
/// </summary>
public interface INewNestUserSettings
{
int NestNumber { get; set; }
DateTime LastNestCreatedDate { get; set; }
/// <summary>The Made By last typed in Nest Info; blank when none.</summary>
string MadeBy { get; }
/// <summary>Persists <see cref="NestNumber"/> and <see cref="LastNestCreatedDate"/>.</summary>
void Save();
}
/// <summary>A new nest and the warning to show with it (unreadable nest defaults), or null.</summary>
public sealed record NewNest(Nest Nest, string Warning);
/// <summary>
/// Creates File > New nests: nest defaults, clamps, the default machine and its support grid,
/// then the year's next name (<see cref="NestNames"/>). In Database mode the nest server
/// allocates the number so every PC shares one sequence; when it cannot, the user's
/// <see cref="INewNestUserSettings.NestNumber"/> is the local fallback, kept above every number
/// the server handed out and reset each year.
/// </summary>
public sealed class NewNestSource
{
private static readonly TimeSpan ServerTimeout = TimeSpan.FromSeconds(3);
private readonly MachineSettingsSource machines;
private readonly INewNestUserSettings user;
private readonly Func<INestRepository> databaseRepository;
private readonly Func<DateTime> now;
/// <param name="databaseRepository">
/// The nest server's repository in Database mode, or null in File mode; read on every new
/// nest. Null itself means File mode always.
/// </param>
/// <param name="now">The clock naming the nest; defaults to <see cref="DateTime.Now"/>.</param>
public NewNestSource(
MachineSettingsSource machines,
INewNestUserSettings user,
Func<INestRepository> databaseRepository = null,
Func<DateTime> now = null)
{
this.machines = machines ?? throw new ArgumentNullException(nameof(machines));
this.user = user ?? throw new ArgumentNullException(nameof(user));
this.databaseRepository = databaseRepository;
this.now = now ?? (() => DateTime.Now);
}
/// <summary>
/// The author a new nest starts with: the name the user last typed in Nest Info's Made By,
/// else their user name. Only new nests get it; opening an existing nest's info leaves a
/// blank Made By blank.
/// </summary>
public string DefaultMadeBy => MadeByOrUserName(user.MadeBy);
/// <summary><paramref name="remembered"/> trimmed, or the user name when it is blank.</summary>
public static string MadeByOrUserName(string remembered) =>
string.IsNullOrWhiteSpace(remembered) ? Environment.UserName : remembered.Trim();
/// <param name="release">
/// The drawing set release group the nest is for: its units, with the saved plate defaults
/// converted to them, its material and thickness, and the machine's spacing for those. Null
/// uses the defaults as saved.
/// </param>
public async Task<NewNest> CreateAsync(SetReleaseGroup release = null)
{
var nest = CreateDefaultNest(release, out var warning);
var created = now();
nest.DateCreated = created;
nest.DateLastModified = created;
nest.MadeBy = DefaultMadeBy;
nest.Name = NestNames.Format(created.Year, await AllocateNumberAsync(created).ConfigureAwait(false));
return new NewNest(nest, warning);
}
private Nest CreateDefaultNest(SetReleaseGroup release, out string warning)
{
var nest = new Nest();
var defaults = machines.LoadNestDefaults(out warning);
(release != null ? defaults.ConvertedTo(release.Units) : defaults).ApplyTo(nest);
// After the defaults so the rail and grid are converted to the new nest's units.
var machine = MachineSettingsSource.DefaultMachine(defaults, machines.LoadMachines());
MachineSettingsSource.LoadClampSettings(machine).ApplyToNewNest(nest);
machines.AssignMachine(nest, machine);
if (release != null)
{
nest.Material = new Material(release.MaterialName, release.MaterialGrade);
nest.Thickness = release.Thickness;
MachineCuttingDefaults.ApplySpacingTo(nest, machine);
}
return nest;
}
private async Task<int> AllocateNumberAsync(DateTime created)
{
if (created.Year != user.LastNestCreatedDate.Year)
user.NestNumber = 1;
user.LastNestCreatedDate = created.Date;
try
{
var repository = databaseRepository?.Invoke();
if (repository != null)
{
using var timeout = new CancellationTokenSource(ServerTimeout);
var number = await repository.AllocateNestNumberAsync(created.Year, timeout.Token).ConfigureAwait(false);
user.NestNumber = System.Math.Max(user.NestNumber, number + 1);
user.Save();
return number;
}
}
catch (Exception ex) when (ex is HttpRequestException or IOException
or OperationCanceledException or NotSupportedException or ArgumentException)
{
// Offline, an invalid server URL or an older server: fall back to this PC's counter.
}
var local = user.NestNumber;
user.NestNumber = local + 1;
user.Save();
return local;
}
}
/// <summary>
/// <see cref="INewNestUserSettings"/> kept in the desktop user-settings file
/// (<see cref="UserSettingsFile"/>) under the WinForms names and text, so both apps count from
/// one sequence: NestNumber as an invariant integer (1 when missing or unreadable),
/// LastNestCreatedDate as System.Configuration's invariant date text, and MadeBy as text. Each
/// read goes to the file and each change is written at once, so <see cref="Save"/> has nothing
/// left to do.
/// </summary>
public sealed class NewNestUserSettingsFile(string path) : INewNestUserSettings
{
public const string NestNumberName = "NestNumber";
public const string LastNestCreatedDateName = "LastNestCreatedDate";
public const string MadeByName = "MadeBy";
/// <summary>The WinForms default, which never matches this year so the counter restarts.</summary>
private static readonly DateTime DefaultDate = new(2015, 4, 8, 19, 30, 0);
public int NestNumber
{
get => UserSettingsFile.Read(path).TryGetValue(NestNumberName, out var text)
&& int.TryParse(text?.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var number)
? number
: 1;
set => UserSettingsFile.Update(path, values =>
values[NestNumberName] = value.ToString(CultureInfo.InvariantCulture));
}
public DateTime LastNestCreatedDate
{
get => UserSettingsFile.Read(path).TryGetValue(LastNestCreatedDateName, out var text)
&& DateTime.TryParse(text?.Trim(), CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)
? date
: DefaultDate;
set => UserSettingsFile.Update(path, values => values[LastNestCreatedDateName] = FormatDate(value));
}
public string MadeBy => UserSettingText.ReadString(UserSettingsFile.Read(path), MadeByName, "");
public void Save()
{
}
/// <summary>As System.Configuration's invariant DateTimeConverter writes it.</summary>
public static string FormatDate(DateTime value) =>
value.TimeOfDay == TimeSpan.Zero
? value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)
: value.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
}
+27 -67
View File
@@ -1,23 +1,22 @@
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenNest.Data;
using OpenNest.Desktop;
using OpenNest.Properties;
namespace OpenNest.Forms
{
/// <summary>
/// Creates File > New nests: nest defaults, clamps, the default machine and its support grid, then the year's next name
/// (<see cref="NestNames"/>). In Database mode the nest server allocates the number so
/// every PC shares one sequence; when it cannot, <see cref="Settings.NestNumber"/> is the
/// local fallback, kept above every number the server handed out and reset each year.
/// The WinForms entry point for File > New nests. The rules live in the shared
/// <see cref="Desktop.NewNestSource"/>, reading this app's settings; this shows its warning.
/// </summary>
internal static class NewNestFactory
{
private static readonly TimeSpan ServerTimeout = TimeSpan.FromSeconds(3);
private static readonly Desktop.NewNestSource Factory = new(
MachineSettings.Source,
new AppUserSettings(),
() => NestStorage.Settings.IsDatabaseMode ? NestStorage.CreateRepository() : null);
/// <param name="release">
/// The drawing set release group the nest is for: its units, with the saved plate
@@ -26,72 +25,33 @@ namespace OpenNest.Forms
/// </param>
public static async Task<Nest> CreateAsync(IWin32Window owner, SetReleaseGroup release = null)
{
var nest = CreateDefaultNest(release);
var now = DateTime.Now;
nest.DateCreated = now;
nest.DateLastModified = now;
nest.MadeBy = DefaultMadeBy;
nest.Name = NestNames.Format(now.Year, await AllocateNumberAsync(now));
return nest;
var created = await Factory.CreateAsync(release);
if (created.Warning != null)
MessageBox.Show(owner, created.Warning, "Nest Defaults", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return created.Nest;
}
/// <summary>
/// The author a new nest starts with: the name the user last typed in Nest Info's Made By,
/// else their Windows user name. Only new nests get it; opening an existing nest's info
/// leaves a blank Made By blank.
/// </summary>
public static string DefaultMadeBy
{
get
{
var remembered = Settings.Default.MadeBy;
return string.IsNullOrWhiteSpace(remembered) ? Environment.UserName : remembered.Trim();
}
}
/// <summary>See <see cref="Desktop.NewNestSource.DefaultMadeBy"/>.</summary>
public static string DefaultMadeBy => Desktop.NewNestSource.MadeByOrUserName(Settings.Default.MadeBy);
private static Nest CreateDefaultNest(SetReleaseGroup release)
/// <summary>The app settings the shared rules read and save.</summary>
private sealed class AppUserSettings : INewNestUserSettings
{
var nest = new Nest();
var defaults = MachineSettings.LoadNestDefaults();
(release != null ? defaults.ConvertedTo(release.Units) : defaults).ApplyTo(nest);
// After the defaults so the rail and grid are converted to the new nest's units.
var machine = MachineSettings.DefaultMachine(defaults, MachineSettings.LoadMachines());
MachineSettings.LoadClampSettings(machine).ApplyToNewNest(nest);
MachineSettings.AssignMachine(nest, machine);
if (release != null)
public int NestNumber
{
nest.Material = new Material(release.MaterialName, release.MaterialGrade);
nest.Thickness = release.Thickness;
MachineCuttingDefaults.ApplySpacingTo(nest, machine);
}
return nest;
}
private static async Task<int> AllocateNumberAsync(DateTime now)
{
if (now.Year != Settings.Default.LastNestCreatedDate.Year)
Settings.Default.NestNumber = 1;
Settings.Default.LastNestCreatedDate = now.Date;
if (NestStorage.Settings.IsDatabaseMode)
{
try
{
using var timeout = new CancellationTokenSource(ServerTimeout);
var number = await NestStorage.CreateRepository()
.AllocateNestNumberAsync(now.Year, timeout.Token);
Settings.Default.NestNumber = System.Math.Max(Settings.Default.NestNumber, number + 1);
return number;
}
catch (Exception ex) when (ex is HttpRequestException or IOException
or OperationCanceledException or NotSupportedException or ArgumentException)
{
// Offline or an older server: fall back to this PC's counter.
}
get => Settings.Default.NestNumber;
set => Settings.Default.NestNumber = value;
}
return Settings.Default.NestNumber++;
public DateTime LastNestCreatedDate
{
get => Settings.Default.LastNestCreatedDate;
set => Settings.Default.LastNestCreatedDate = value;
}
public string MadeBy => Settings.Default.MadeBy;
public void Save() => Settings.Default.Save();
}
}
}