The background layer seems to be saved anyway, despite IEN_StoreBackground = False. However this option saves me from having to remove the background layer when dropping the layer on ImageEnView1, and thus reduces the complexity of the code.
Here is the improved code with added file-name validation:
function PAIsFilenameValid(const AFilename: string; var errorchar: Char): Boolean;
begin
Result := True;
for var i := 1 to Length(AFilename) do
begin
if not System.IOUtils.TPath.IsValidFileNameChar(AFilename[i]) then
begin
errorchar := AFilename[i];
Result := False;
BREAK;
end;
end;
end;
procedure TForm1.ButtonAddSelectedLayerAsClick(Sender: TObject);
// save the Layer in the Exe folder
begin
var LValue: string := '';
var LFileExists: Boolean;
var LSaveOK: Boolean := True;
var IsFileNameValid: Boolean;
var C: Char;
repeat
if not InputQuery('Add selected Layer to the Collection', 'Layer Name:', LValue) then EXIT;
IsFileNameValid := PAIsFilenameValid(LValue, C);
if not IsFileNameValid then
begin
Application.MessageBox(PChar('This character is not allowed in file-names: ' + C),
PChar('Application'), MB_OK + MB_ICONINFORMATION + MB_DEFBUTTON2 + MB_TOPMOST);
end;
LFileExists := FileExists(GetLayerFilePath(LValue));
if LFileExists then
begin
case
Application.MessageBox('This file already exists. Do you want to save anyway?',
PChar('Application'), MB_OKCANCEL + MB_ICONQUESTION + MB_DEFBUTTON2 + MB_TOPMOST)
of
IDOK: LSaveOK := True;
IDCANCEL: LSaveOK := False;
end;
end;
until (Trim(LValue) <> '') and LSaveOK and IsFileNameValid;
var TempIEV := TImageEnView.Create(nil);
try
// copy the Layer selected from ImageEnView1 to TempIEV:
var idx := TempIEV.LayersAdd(ImageEnView1.CurrentLayer);
TempIEV.IO.Params.IEN_StoreBackground := False; // do not save the background Layer
TempIEV.LayersCropBackground(); // the background still needs to be cropped because it is still present in the saved file!
TempIEV.Layers[idx].Name := LValue; // set the name of the new Layer
var LFile := GetLayerFilePath(LValue); // determine the file path
TempIEV.IO.SaveToFileIEN(LFile); // save the Layer file
ImageEnFolderMView1.RefreshFileList; // refresh the collection view
finally
TempIEV.Free;
end;
end;
function TForm1.GetLayerFilePath(const ALayerName: string): string;
begin
Result := IncludeTrailingPathDelimiter(FExeFolder) + ALayerName + '.ien';
end;