Import Plugins
An importer registers its file extensions, recognizes its files cheaply, and translates a file into TonCut projects, materials, pieces, and stock in LoadFile. LoadFile never writes to the user's data directly: it fills empty staging collections, and TonCut's Import dialog merges them afterwards.
Discovery flow
TonCut calls EnumExtensions(etImport, callback) on every active plugin while it loads plugins, and adds one Import dialog filter per callback.Invoke call. The extension must include the leading dot. A plugin that also exports answers in the same method.
EnumExtensions
function TCsvImportExportPlugin.EnumExtensions(
aType: TTcpExtensionType;
aEnumCb: ITcEnumExtensionsCallback
): TTcpResult;
begin
if aType in [etImport, etExport] then
aEnumCb.Invoke(aType, '.csv', 'CSV Import/Export Template');
Result := cprOK;
end;
When the user picks your filter in the Import dialog, TonCut calls LoadFile directly. IsMyFile is used only when TonCut has to find the plugin for a file itself.
File matching
TonCut asks IsMyFile only for plugins with , and only for the Open dialog's All files filter, drag-and-drop, temporary-file import, and files named on the command line:
- : your plugin is chosen immediately.
- : your plugin becomes a candidate. If no plugin returns OK, the last candidate in scan order is used.
- Anything else (return ): your plugin is skipped.
Keep IsMyFile cheap and conservative: check the extension, then read only as much of the file as you need to recognize it. The CSV starter checks the extension and the header row.
Validate the CSV header
// ParseCsvText and HasRequiredHeader come from the SDK's
// examples/delphi/CsvImportExport/uCsvCommon.pas.
function TCsvImportExportPlugin.ValidateHeader(
const aFileName: WideString
): TTcpResult;
var
table: TCsvTable;
begin
Result := cprNo;
if not SameText(ExtractFileExt(aFileName), '.csv') then
Exit;
if not FileExists(aFileName) then
Exit;
table := ParseCsvText(TFile.ReadAllText(aFileName, TEncoding.UTF8));
if (Length(table) > 0) and HasRequiredHeader(table[0]) then
Result := cprOK;
end;
The C# tab is managed CSV code only. In a C# plugin the native C++ shim implements IsMyFile and turns headerIsValid into a .
Staging and merge
LoadFile receives new, empty, in-memory staging collections for devices, materials, bands, projects, pieces (formats), and stock (sheets). They are not the live project data, and TonCut does not open an update scope around the call.
- Your plugin creates objects in the staging collections and adds them.
- If
LoadFilereturns , TonCut opens its Import dialog. The user chooses which categories to import, and TonCut merges them into the database in one transaction:- materials and bands are identified by name (an option that is on by default), so a material that already exists is reused rather than duplicated;
- stock sheets with the same content are merged and their quantities summed;
- the optional new project choice replaces the existing pieces and stock.
- Devices your plugin adds to the staging collection are ignored.
- If
LoadFilereturns anything else, or raises, all staged data is discarded and nothing reaches the project.
Because the collections are staging copies, lookups such as IMaterials.FindByTitle see only what this LoadFile call has added so far. Use them to avoid creating the same material twice within one file; the Import dialog takes care of matching existing data.
Do not keep the staging collections, or objects from them, after LoadFile returns.
Creating objects
| Method | Opens a dialog? | Can return nil? | Added to a collection? |
|---|---|---|---|
IMaterials.CreateMaterial, IProjects.CreateProject, IFormats.CreateFormat, ISheets.CreateSheet, IBands.CreateBand, IDevices.CreateDevice | No | No | No. Call Add on the same collection. |
ITonCut.CreateMaterial, ITonCut.CreateProject, ITonCut.CreateBand | Yes, modal | Yes, when the user cancels | Yes, to the live database, committed at once |
The collection factories are plain constructors. A new object gets a temporary negative Id until it is stored.
The ITonCut methods are for interactive workflows. In LoadFile they are wrong: they open one dialog per call, and what the user confirms is committed to the live database immediately, even if the user later cancels the import. Never Add an object they returned to a live collection; it is already there, and adding it again raises an error.
The correct non-interactive pattern is always: CreateX on the staging collection you received, set the properties, Add.
Finding staged objects
IMaterials.FindByTitle(aTitle, aKind, aWidth, aThickness) matches all four values exactly, and the title comparison is case-sensitive. Pass aWidth = 0 for anything that is not a 1D material. TonCut's dialogs keep (Title, Kind, Width, Thickness) unique; Add does not check it, so look the material up before you create it. IProjects.FindByTitle(aTitle) finds a staged project by title.
Update scopes
BeginUpdate, EndUpdate, and IsUpdating exist on IProjects, IFormats, ISheets, and IDevices. Engine version 25 also exposes them, together with OnChange, on IMaterials, IBands, IResults, and ITemplates. Update scopes are optional in LoadFile. Balance every successful BeginUpdate with EndUpdate in a finally block.
For the four collections added in version 25, scopes nest: IsUpdating stays
True until the outermost scope ends. During a scope, additions and removals
suppress their collection OnAdd and OnRemove callbacks. The outermost
EndUpdate emits one collection OnChange if an item was added, removed, or
emitted its own OnChange during the scope. An empty scope emits nothing, and
individual add/remove callbacks are not replayed. An item's own events are not
suppressed by its collection's scope. Outside a scope, additions and removals
keep their ordinary callbacks; item edits do not emit collection OnChange.
Calling EndUpdate without a matching BeginUpdate raises an error. These
scopes group notifications, not storage transactions: they do not roll back
changes when an import or a callback fails. Compile against the version 25 SDK
and use a host with the same cEngineVersion; the host requires an exact match.
Required values
Units. Every length is an integer in hundredths of a millimeter: multiply millimeters by cLengthMultiplier (100). This holds whatever unit the user displays (ITonCut.Units). See Data Model & Units.
Material width. For a 2D material, Width is 0. For a 1D material, Width is the bar width, and the width of every 1D piece equals its material's width.
Device. A staged material must have its Device set to a device from ITonCut.Devices; the SDK starter picks the first device whose MaterialKind matches the material, else the first device. The merge reads the device of every new material, so a new material without one may break the import (observed in code).
Projects. When ITonCut.UsingProjects is False, TonCut assigns every imported piece to its single flat project and ignores IFormat.Project. When it is True and a piece has no project, TonCut creates a project named after the imported file, due seven days later. Set Project only when the file names one.
Complete LoadFile
This LoadFile follows the SDK CSV starter's schema (SDK/manuals/csv-schema.md): millimeters in the file, mk1D/mk2D/mkUnknown material kinds, a missing or zero quantity read as 1. The CSV tokenizer comes from the SDK examples (examples/delphi/CsvImportExport/uCsvCommon.pas for Delphi, examples/shared/cpp/CsvCodec.hpp and .cpp for C++); everything that touches TonCut is shown in full.
LoadFile with staging collections
// uses System.SysUtils, System.IOUtils, Winapi.Windows, uICommon,
// uITcPluginCommon, uITonCut, uIDevice, uIDevices, uIMaterial, uIMaterials,
// uIBands, uIProject, uIProjects, uIFormat, uIFormats, uISheet, uISheets,
// uCsvCommon;
function ShowImportError(aWindow: THandle; const aMessage: string): TTcpResult;
begin
MessageBoxW(aWindow, PWideChar(aMessage), 'CSV import', MB_OK or MB_ICONERROR);
Result := cprFailed;
end;
function TryMillimetersToUnits(const aText: string; out aUnits: Cardinal): Boolean;
var
millimeters: Cardinal;
begin
aUnits := 0;
Result := TryParseCardinalField(aText, millimeters) and
(UInt64(millimeters) * cLengthMultiplier <= High(Cardinal));
if Result then
aUnits := millimeters * cLengthMultiplier;
end;
// The first device whose MaterialKind matches, else the first device.
function FindDeviceForKind(const aTonCut: ITonCut; aKind: TMaterialKind): IDevice;
var
devices: IDevices;
i: Integer;
begin
Result := nil;
devices := aTonCut.Devices;
for i := 0 to devices.Count - 1 do
if devices[i].MaterialKind = aKind then
Exit(devices[i]);
if devices.Count > 0 then
Result := devices[0];
end;
function FindOrCreateMaterial(const aMaterials: IMaterials; const aTonCut: ITonCut;
const aTitle: string; aKind: TMaterialKind; aWidth, aThickness: Cardinal): IMaterial;
var
device: IDevice;
begin
if aKind <> mk1D then
aWidth := 0; // only 1D materials have a width
Result := aMaterials.FindByTitle(aTitle, aKind, aWidth, aThickness);
if Result <> nil then
Exit;
device := FindDeviceForKind(aTonCut, aKind);
if device = nil then
raise Exception.Create('Define a cutting device in TonCut first.');
Result := aMaterials.CreateMaterial; // no dialog, never nil, not yet added
Result.Title := aTitle;
Result.Kind := aKind;
Result.Width := aWidth;
Result.Thickness := aThickness;
Result.Device := device; // required for every new material
aMaterials.Add(Result);
end;
function FindOrCreateProject(const aProjects: IProjects; const aTitle: string): IProject;
begin
Result := aProjects.FindByTitle(aTitle);
if Result = nil then
begin
Result := aProjects.CreateProject;
Result.Title := aTitle;
aProjects.Add(Result);
end;
end;
function TCsvImportExportPlugin.LoadFile(aWindow: THandle; const aFileName: WideString;
aDevices: IDevices; aMaterials: IMaterials; aBands: IBands; aProjects: IProjects;
aFormats: IFormats; aSheets: ISheets): TTcpResult;
var
table: TCsvTable;
header, row: TCsvRow;
material: IMaterial;
piece: IFormat;
sheet: ISheet;
recordType, projectTitle: string;
kind: TMaterialKind;
materialWidth, materialThickness, itemLength, itemWidth, quantity: Cardinal;
i: Integer;
begin
try
table := ParseCsvText(TFile.ReadAllText(aFileName, TEncoding.UTF8));
if (Length(table) = 0) or not HasRequiredHeader(table[0]) then
Exit(ShowImportError(aWindow, 'The file does not use the CSV starter header.'));
header := table[0];
aProjects.BeginUpdate;
aFormats.BeginUpdate;
aSheets.BeginUpdate;
try
for i := 1 to High(table) do
begin
row := table[i];
recordType := UpperCase(Trim(CellByName(header, row, 'RecordType')));
if recordType = '' then
Continue;
if (recordType <> 'FORMAT') and (recordType <> 'SHEET') then
Exit(ShowImportError(aWindow, Format('Row %d: unknown RecordType.', [i + 1])));
if not TryParseMaterialKind(CellByName(header, row, 'MaterialKind'), kind) or
not TryMillimetersToUnits(CellByName(header, row, 'MaterialWidth'), materialWidth) or
not TryMillimetersToUnits(CellByName(header, row, 'MaterialThickness'), materialThickness) or
not TryMillimetersToUnits(CellByName(header, row, 'Length'), itemLength) or
not TryMillimetersToUnits(CellByName(header, row, 'Width'), itemWidth) then
Exit(ShowImportError(aWindow, Format('Row %d: invalid value.', [i + 1])));
if not TryParseCardinalField(CellByName(header, row, 'Quantity'), quantity) or
(quantity = 0) then
quantity := 1;
material := FindOrCreateMaterial(aMaterials, FTonCut,
Trim(CellByName(header, row, 'MaterialTitle')), kind, materialWidth, materialThickness);
if kind = mk1D then
itemWidth := material.Width; // a 1D piece is as wide as its bar
if recordType = 'FORMAT' then
begin
piece := aFormats.CreateFormat;
projectTitle := Trim(CellByName(header, row, 'ProjectTitle'));
if projectTitle <> '' then
piece.Project := FindOrCreateProject(aProjects, projectTitle);
piece.Material := material;
piece.Length := itemLength;
piece.Width := itemWidth;
piece.Quantity := quantity;
piece.Identifier := CellByName(header, row, 'Identifier');
piece.Description := CellByName(header, row, 'Description');
aFormats.Add(piece);
end
else
begin
sheet := aSheets.CreateSheet;
sheet.Material := material;
sheet.Length := itemLength;
sheet.Width := itemWidth;
sheet.Quantity := Integer(quantity);
sheet.Identifier := CellByName(header, row, 'Identifier');
sheet.Description := CellByName(header, row, 'Description');
aSheets.Add(sheet);
end;
end;
finally
aSheets.EndUpdate;
aFormats.EndUpdate;
aProjects.EndUpdate;
end;
Result := cprOK;
except
on E: Exception do
Result := ShowImportError(aWindow, E.Message);
end;
end;
The complete starter projects are described on the SDK page.