unit Unit1;
{$INCLUDE CADSoftTools.INC}
//If you see error "File not found: 'CADSoftTools.INC'",
//then please contact info@cadsofttools.com to get a compilable version.
//If you have a compilable version, you need to copy the contents of
// Lib7/LibXE5win32/LibXE5win64... to Lib directory according to your
// Delphi version and target CPU platform.

interface

uses
  fAddScaledFile,
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, JPEG,
  ExtCtrls, StdCtrls, CADImage, DXFConv, ComCtrls, Menus, Printers, MVFont,
  sgConsts, SGExport, Math, ExtDlgs, Buttons,
  DXF, DWG, DWG12, HPGL2, SVG, CGM, DWF,
  {$IFDEF CADExportVCL}
  DXFExport,
  {$ENDIF}
  ShellAPI, fLayers, sgDrawingNavigator;

type
  TForm1 = class(TForm)
    Panel2: TPanel;
    prbProgress: TProgressBar;
    PageControl1: TPageControl;
    tbsImage: TTabSheet;
    TabSheet2: TTabSheet;
    TreeView1: TTreeView;
    Splitter1: TSplitter;
    ListBox1: TListBox;
    MainMenu1: TMainMenu;
    MIFile: TMenuItem;
    MIOpen: TMenuItem;
    MIClose: TMenuItem;
    N4: TMenuItem;
    MIExit: TMenuItem;
    pnlFileName: TPanel;
    pnlTime: TPanel;
    PrintDialog1: TPrintDialog;
    MIPrint: TMenuItem;
    OpenDialog1: TOpenPictureDialog;
    Panel4: TPanel;
    BtnOpen: TSpeedButton;
    BtnPlus: TSpeedButton;
    BtnMinus: TSpeedButton;
    BtnReal: TSpeedButton;
    BtnPrev: TSpeedButton;
    BtnPrint: TSpeedButton;
    N2: TMenuItem;
    MIAbout: TMenuItem;
    BtnSave: TSpeedButton;
    miSaveAs: TMenuItem;
    SavePictureDialog: TSavePictureDialog;
    SavePictureDialogDXF: TSavePictureDialog;
    mmiImageColors: TMenuItem;
    mmiDisabled: TMenuItem;
    mmiBlack: TMenuItem;
    mmiNormal: TMenuItem;
    SoftGoldHomePage1: TMenuItem;
    btnLayers: TSpeedButton;
    sb3DOrbit: TSpeedButton;
    sbAddScaledFiles: TSpeedButton;
    BtnPrint1: TSpeedButton;
    pnlCoords: TPanel;
    Memo1: TMemo;
    memColorToLineWeight: TMemo;
    cbShowLineWeight: TCheckBox;
    sbMergeFiles: TSpeedButton;
    btnLTypeHalf: TButton;
    miSaveToDXF: TMenuItem;
    btnFitToWindow: TSpeedButton;
    N1: TMenuItem;
    mmiMergeFiles: TMenuItem;
    mmiAddScaledFiles: TMenuItem;
    procedure MIOpenClick(Sender: TObject);
    procedure MICloseClick(Sender: TObject);
    procedure MIExitClick(Sender: TObject);
    procedure TreeView1Change(Sender: TObject; Node: TTreeNode);
    procedure MIPrintClick(Sender: TObject);
    procedure MIAutoClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure MIPrevClick(Sender: TObject);
    procedure sgPaintBoxScaling(Sender: TObject);
    procedure sgPaintBoxProgress(Sender: TObject; Stage: TProgressStage;
      PercentDone: Byte; RedrawNow: Boolean; const R: TRect;
      const Msg: String);
    procedure BtnPlusClick(Sender: TObject);
    procedure BtnMinusClick(Sender: TObject);
    procedure PageControl1Changing(Sender: TObject;
      var AllowChange: Boolean);
    procedure MIHelpClick(Sender: TObject);
    procedure OpenDialog1Show(Sender: TObject);
    procedure OpenDialog1Close(Sender: TObject);
    procedure btnSaveClick(Sender: TObject);
    procedure btnSaveToDXFClick(Sender: TObject);
    procedure mmiDisabledClick(Sender: TObject);
    procedure mmiBlackClick(Sender: TObject);
    procedure mmiNormalClick(Sender: TObject);
    procedure SoftGoldHomePage1Click(Sender: TObject);
    procedure MIAboutClick(Sender: TObject);
    procedure btnLayersClick(Sender: TObject);
    procedure sgPaintBoxPaint(Sender: TObject);
    procedure sb3DOrbitClick(Sender: TObject);
    procedure sgPaintBoxMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    procedure sbAddScaledFilesClick(Sender: TObject);
    procedure BtnPrint1Click(Sender: TObject);
    procedure cbShowLineWeightClick(Sender: TObject);
    procedure PageControl1Change(Sender: TObject);
    procedure sbMergeFilesClick(Sender: TObject);
    procedure btnLTypeHalfClick(Sender: TObject);
    procedure btnFitToWindowClick(Sender: TObject);
    procedure BtnRealClick(Sender: TObject);
  private
    fmAddScaledFile: TfmAddScaledFile;
    FsgPaintBox: TsgDrawingNavigator;
    procedure LoadStructure;
    procedure Time;
    procedure EnableScales;
    procedure Open(const FileName: String);
    function GetImg: TsgCADImage;
  public
    property sgPaintBox: TsgDrawingNavigator read FsgPaintBox;
    property Img: TsgCADImage read GetImg;
  end;

var
  Form1: TForm1;
  Start: Cardinal;

implementation

{$R *.DFM}


{$IFDEF DEMO}
uses
  fInfo;
{$ENDIF}

//{$R *.RES}

procedure TForm1.Time;
var T: Integer;
begin
  T := (GetCurrentTime - Start) div 1000;
  pnlTime.Caption := Format('%.2d:%.2d', [T div 60, T mod 60]);
  pnlTime.Update;
end;

procedure TForm1.LoadStructure;

  procedure Add(Parent: TTreeNode; E: TsgDXFEntity);
  var
    I: Integer;
  begin
    Parent := TreeView1.Items.AddChildObject(Parent, E.EntName, E);
    Application.ProcessMessages;
    prbProgress.Position := prbProgress.Position + 1;
    for I := 0 to E.Count - 1 do Add(Parent, E[I]);
  end;

var
  I: Integer;
begin
  prbProgress.Position := 0;
  prbProgress.Max := Img.Converter.Count;
  TreeView1.Items.BeginUpdate;
  try
    TreeView1.Items.Clear;
    for I := 0 to Img.Converter.Main.Count - 1 do
      Add(nil, Img.Converter.Main[I]);
  finally
    prbProgress.Position := 0;
    TreeView1.Items.EndUpdate;
  end;
end;

procedure TForm1.EnableScales;
var
  vCADFlag: Boolean;
  vNotEmptyFlag: Boolean;
begin
  vCADFlag := Img <> nil;
  vNotEmptyFlag := not sgPaintBox.Empty;

  MIPrint.Enabled := vNotEmptyFlag;
  MIClose.Enabled := vNotEmptyFlag;
  BtnPrev.Enabled := vNotEmptyFlag;
  BtnSave.Enabled := vNotEmptyFlag;
  miSaveAs.Enabled := vNotEmptyFlag;
  BtnPrint.Enabled := vNotEmptyFlag;
  BtnPrint1.Enabled := vNotEmptyFlag;
  BtnPlus.Enabled := vNotEmptyFlag;
  BtnMinus.Enabled := vNotEmptyFlag;
  BtnReal.Enabled := vNotEmptyFlag;
  BtnFitToWindow.Enabled := vNotEmptyFlag;
  MIClose.Enabled := vNotEmptyFlag;

  btnLayers.Enabled := vCADFlag;
  sb3DOrbit.Enabled := vCADFlag;
  miSaveToDXF.Enabled := vCADFlag or (sgPaintBox.Picture.Graphic is TMetafile);
  mmiDisabled.Enabled := vCADFlag;
  mmiBlack.Enabled := vCADFlag;
  mmiNormal.Enabled := vCADFlag;
end;

procedure TForm1.Open(const FileName: String);
begin
  TreeView1.Items.Clear;
  Start := GetCurrentTime;
  Screen.Cursor := crHourGlass;
  try
    MICloseClick(nil);
    sgPaintBox.LoadFromFile(FileName);
    pnlFileName.Caption := UpperCase(ExtractFileName(FileName));
    EnableScales;
    HelpContext := 3;
    MIAutoClick(nil);
    if Img <> nil then
    begin
      if cbShowLineWeight.Checked then
        Img.ColorToLineWeight.Text := memColorToLineWeight.Text;
      Img.IsShowLineWeight := cbShowLineWeight.Checked;
      TabSheet2.TabVisible := True;
    end;
  finally
    prbProgress.Position := 0;
    Screen.Cursor := crDefault;
  end;
end;

procedure TForm1.MIOpenClick(Sender: TObject);
begin
  OpenDialog1.FileName := '';
  if not OpenDialog1.Execute then Exit;
  MacroStrings.Text :=  Memo1.Text;
  Open(OpenDialog1.FileName);
end;

procedure TForm1.MICloseClick(Sender: TObject);
begin
  ListBox1.Clear;
  TreeView1.Items.Clear;
  sgPaintBox.Picture.Graphic := nil;
  pnlFileName.Caption := '';
  pnlTime.Caption := '';
  MIClose.Enabled := False;
  MIPrint.Enabled := False;
  BtnSave.Enabled := False;
  PageControl1.ActivePage := tbsImage;
  TabSheet2.TabVisible := False;
  EnableScales;
  prbProgress.Max := 100;
  pnlCoords.Caption := '';
  HelpContext := 1;
end;

procedure TForm1.MIExitClick(Sender: TObject);
begin
  Close;
end;

procedure TForm1.TreeView1Change(Sender: TObject; Node: TTreeNode);
var
  E: TsgDXFEntity;
  S: String;
begin
  if not Node.Selected then Exit;
  E := TsgDXFEntity(Node.Data);
  if (E=nil) or (E.SrcStart = nil) or (E.SrcEnd = nil)
  then ListBox1.Clear
  else begin
    SetString(S, E.SrcStart, E.SrcEnd - E.SrcStart);
    ListBox1.Items.Text := S;
  end;
end;

procedure TForm1.MIPrintClick(Sender: TObject);
const PO: array[Boolean] of TPrinterOrientation = (poPortrait,poLandscape);
var
  W,H: Double;
  PW,PH: Integer;
begin
  with sgPaintBox.Picture do
  Printer.Orientation := PO[Width > Height];
  if PrintDialog1.Execute
  then with Printer, sgPaintBox.Picture do begin
    W := PageWidth / Width;
    H := PageHeight / Height;
    if W > H then W := H;
    PW := Round(W * Width);
    PH := Round(W * Height);
    BeginDoc;
    Canvas.StretchDraw(Bounds((PageWidth-PW) div 2, (PageHeight-PH) div 2, PW, PH), Graphic);
    EndDoc;
  end;
end;

procedure TForm1.MIAutoClick(Sender: TObject);
begin
  sgPaintBoxScaling(nil);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  sSHXSearchPaths := ExpandFileName('../../../SHX');
  FsgPaintBox := TsgDrawingNavigator.Create(Self);
  FsgPaintBox.OnPaint := sgPaintBoxPaint;
  FsgPaintBox.OnChangeScale := sgPaintBoxScaling;
  FsgPaintBox.OnMouseMove := sgPaintBoxMouseMove;
  FsgPaintBox.OnProgress := sgPaintBoxProgress;
  FsgPaintBox.Parent := tbsImage;
  FsgPaintBox.Align := alClient;
  FsgPaintBox.AutoFocus := True;
  FsgPaintBox.ScalingOnMouseWheel := True;
  FsgPaintBox.RectZooming := True;
  {$IFDEF DEMO}
  fInfo.CreateInfoFrame(FsgPaintBox.Handle, Point(1, 1));
  {$ENDIF}
  OpenDialog1.Filter := GraphicFilter(TGraphic);
  if ParamCount > 0 then begin
    Open(ParamStr(1));
    OpenDialog1.FileName := ParamStr(1);
  end;
end;

procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if Key = VK_ESCAPE then Close;
  if sgPaintBox.Empty or (PageControl1.ActivePage <> tbsImage) or (Shift-[ssCtrl] <> [])
  then Exit;
  case Key of
    VK_ADD:		BtnPlusClick(nil);
    VK_SUBTRACT:	BtnMinusClick(nil);
    VK_MULTIPLY:
      if ssCtrl in Shift then
        sgPaintBox.Scale := 1
      else
        sgPaintBox.FitToSize;
  end;
end;

procedure TForm1.MIPrevClick(Sender: TObject);
begin
  sgPaintBox.CallPreviousView;
  BtnPrev.Enabled := sgPaintBox.HasPreviousView;
end;

procedure TForm1.sgPaintBoxScaling(Sender: TObject);
begin
  BtnReal.Enabled := True;
  BtnFitToWindow.Enabled := True;
  BtnPrev.Enabled := sgPaintBox.HasPreviousView;
end;

procedure TForm1.sgPaintBoxProgress(Sender: TObject; Stage: TProgressStage;
  PercentDone: Byte; RedrawNow: Boolean; const R: TRect; const Msg: String);
begin
  if Stage=psStarting then begin
    pnlFileName.Caption := Msg;
    pnlFileName.Update;
  end;
  prbProgress.Position := PercentDone;
  Time;
  if Stage=psEnding then begin
    prbProgress.Position := 0;
    pnlFileName.Caption := UpperCase(ExtractFileName(OpenDialog1.FileName))
  end;
end;

procedure TForm1.BtnPlusClick(Sender: TObject);
begin
  sgPaintBox.AlterScale(2, False, sgPaintBox.Center);
end;

procedure TForm1.BtnMinusClick(Sender: TObject);
begin
  sgPaintBox.AlterScale(0.5, False, sgPaintBox.Center);
end;

procedure TForm1.PageControl1Changing(Sender: TObject; var AllowChange: Boolean);
begin
  AllowChange := Img <> nil;
  FocusControl(nil);
end;

procedure TForm1.MIHelpClick(Sender: TObject);
begin
  Application.HelpCommand(HELP_CONTENTS,0);
end;

procedure TForm1.OpenDialog1Show(Sender: TObject);
begin
  MinDXFSize := 140;
end;

procedure TForm1.OpenDialog1Close(Sender: TObject);
begin
  MinDXFSize := 0;
end;

procedure TForm1.btnSaveClick(Sender: TObject);
var
  E: TsgExport;
  vMC: TMetafileCanvas;
  vM: TMetafile;
begin
  if sgPaintBox.Empty or not SavePictureDialog.Execute then Exit;
  if LowerCase(ExtractFileExt(SavePictureDialog.FileName)) = '.wmf' then
  begin
    vM := TMetafile.Create;
    try
      vM.Width := sgPaintBox.Picture.Width;
      vM.Height := sgPaintBox.Picture.Height;
      vMC := TMetafileCanvas.Create(vM, 0);
      try
        vMC.StretchDraw(Rect(0, 0, vM.Width, vM.Height), sgPaintBox.Picture.Graphic);
      finally
        vMC.Free;
      end;
      vM.SaveToFile(SavePictureDialog.FileName);
    finally
      vM.Free;
    end;
    Exit;
  end;

  E := TsgExport.Create;
  try
    E.ExportTo(sgPaintBox.Picture.Graphic,
               SavePictureDialog.FileName,
               TsgExportFormat(SavePictureDialog.FilterIndex-1),
               sgPaintBox.Picture.Width,
               sgPaintBox.Picture.Height);
  finally
    E.Free;
  end;
end;

procedure TForm1.btnSaveToDXFClick(Sender: TObject);
  {$IFDEF CADExportVCL}
var
  E: TsgDXFExport;
  vMet: TMetafile;
  vGr: TGraphic;
  vOffX, vOffY, vUSize: TsgFloat;
  vSaveToFile: string;
{$ENDIF}
begin
  {$IFDEF CADExportVCL}
  if not SavePictureDialogDXF.Execute then Exit;
  if AnsiLowerCase(ExtractFileExt(SavePictureDialogDXF.FileName)) <> '.dxf' then
     SavePictureDialogDXF.FileName := SavePictureDialogDXF.FileName + '.dxf';
  vSaveToFile := SavePictureDialogDXF.FileName;
  vGr := sgPaintBox.Picture.Graphic;
  E := TsgDXFExport.Create;
  try
    E.IsParseWhite := True;// False
    if not ((vGr is TsgCADImage) or (vGr is TMetafile)) then
    begin
      ShowMessage('Raster drawings can not be saved to DXF format.');
      Exit;
    end
    else
    begin
      if not (vGr is TsgCADImage) then
      begin
        E.Use01MM := False;
        E.Canvas.StretchDraw(Rect(0, 0, vGr.Width, vGr.Height), vGr);
        E.EndDraw;
      end
      else
      begin
        vMet := TsgCADImage(vGr).ExportToMetafile(vOffX, vOffY, vUSize);
        DXFExport.OffsetX := vOffX;
        DXFExport.OffsetY := vOffY;
        E.UnitSize := vUSize;
        E.LoadFromMetafile(vMet);
        {$IFDEF SG_DEBUG}
        vMet.SaveToFile(ChangeFileExt(vSaveToFile, '.emf'));
        {$ENDIF}
        vMet.Free;
      end;
    end;
    E.SaveToFile(vSaveToFile);
  finally
    E.Free;
  end;
  {$ELSE}
  MessageBox(0, PChar('This function is available with the CAD Export VCL only.'), 'WARNING', MB_ICONWARNING);
  {$ENDIF}
end;

procedure TForm1.mmiDisabledClick(Sender: TObject);
begin
  if sgPaintBox.Empty or not
    (sgPaintBox.Picture.Graphic is TsgCADImage) then
    Exit;
  (sgPaintBox.Picture.Graphic as TsgCADImage).DrawMode := dmGray;
end;

procedure TForm1.mmiBlackClick(Sender: TObject);
begin
  if sgPaintBox.Empty or not
    (sgPaintBox.Picture.Graphic is TsgCADImage) then
    Exit;
  (sgPaintBox.Picture.Graphic as TsgCADImage).DrawMode := dmBlack;
end;

procedure TForm1.mmiNormalClick(Sender: TObject);
begin
  if sgPaintBox.Empty or not
    (sgPaintBox.Picture.Graphic is TsgCADImage) then
    Exit;
  (sgPaintBox.Picture.Graphic as TsgCADImage).DrawMode := dmNormal;
end;

procedure TForm1.SoftGoldHomePage1Click(Sender: TObject);
begin
  ShellExecute(Handle, 'open', 'www.cadsofttools.com', '', '', SW_SHOW);
end;


procedure TForm1.MIAboutClick(Sender: TObject);
begin
 ShowMessage('DWG/DXF VCLs demo version '+ #13#10 +
             'Please contact www.cadsofttools.com to order a full version');
end;

procedure TForm1.btnLayersClick(Sender: TObject);
begin
  if Img = nil then Exit;
  LayersDialogExecute(Img, sgPaintBox);
end;

procedure TForm1.sgPaintBoxPaint(Sender: TObject);
begin
  // paint to TsgDrawingNavigator
  // uncomment the following code to check painting above the drawing
  {sgPaintBox.Canvas.Font.Size := 14;
  sgPaintBox.Canvas.Font.Color := clBlack;
  sgPaintBox.Canvas.Font.Name := 'Arial';
  sgPaintBox.Canvas.TextOut(20, 20, 'Custom drawing on Graphic Viewer allowed');
  {}
end;

procedure TForm1.sb3DOrbitClick(Sender: TObject);
begin
  sb3DOrbit.Down := sb3DOrbit.Down or False;
  sgPaintBox.Orbit3D.Visible := sb3DOrbit.Down;
  sgPaintBox.Invalidate;
end;

procedure TForm1.sgPaintBoxMouseMove(Sender: TObject; Shift: TShiftState;
  X, Y: Integer);
var
  vPt: TFPoint;
  vUnits: string;
begin
  if sgPaintBox.Picture.Graphic is TsgCADImage then
  begin
    vPt := sgPaintBox.GetDrawingCoords(X, Y, vUnits);
    pnlCoords.Caption := Format('%.3f; %.3f; %.3f (%s)', [vPt.X, vPt.Y, vPt.Z, vUnits]);
  end;
end;

procedure TForm1.sbAddScaledFilesClick(Sender: TObject);
var
  vCAD: TsgCADImage;
begin
  sgPaintBox.Orbit3D.Visible := False;
  fmAddScaledFile := TfmAddScaledFile.Create(self);
  try
    if (fmAddScaledFile.ShowModal = mrOk) and
       (fmAddScaledFile.FilesCount <> 0) then
    begin
      vCAD := fmAddScaledFile.CADFile;
      btnLayers.Enabled := True;
      if cbShowLineWeight.Checked then
        vCAD.ColorToLineWeight.Text := Memo1.Text
      else
        vCAD.ColorToLineWeight.Text := '';
      MICloseClick(nil);
      sgPaintBox.Picture.Graphic := vCAD;
      EnableScales;
      sb3DOrbit.Enabled := True;
      sb3DOrbit.Down := False;
      miSaveAs.Enabled := True;
      miSaveToDXF.Enabled := miSaveAs.Enabled;
      TabSheet2.TabVisible := True;
    end;
  finally
    fmAddScaledFile.Free;
  end;
end;

procedure TForm1.BtnPrint1Click(Sender: TObject);
const PO: array[Boolean] of TPrinterOrientation = (poPortrait,poLandscape);
const koef = 25.4;
var
  PxlsX, PxlsY: Double;
  W, H: Integer;
begin
  Printer.Orientation := PO[sgPaintBox.Picture.Graphic.Width >
    sgPaintBox.Picture.Graphic.Height];
  if PrintDialog1.Execute then
  begin
    W := sgPaintBox.Picture.Graphic.Width;
    H := sgPaintBox.Picture.Graphic.Height;
    PxlsX := 1;
    PxlsY := 1;
    if sgPaintBox.Picture.Graphic is TsgCADImage then
    begin
      PxlsX := GetDeviceCaps(Printer.Handle, LOGPIXELSX);
      PxlsY := GetDeviceCaps(Printer.Handle, LOGPIXELSY);
      if TsgCADImage(sgPaintBox.Picture.Graphic).Millimetres then
      begin
        PxlsX := PxlsX / koef;
        PxlsY := PxlsY / koef;
      end;
    end;
    Printer.Title := 'CAD Image VCL printing 1:1';
    Printer.BeginDoc;
    Printer.Canvas.StretchDraw(Rect(0, 0, Round(PxlsX * W), Round(PxlsY * H)),
      sgPaintBox.Picture.Graphic);
    Printer.EndDoc;
  end;
end;

procedure TForm1.cbShowLineWeightClick(Sender: TObject);
begin
  if Img = nil then
    Exit;
  Img.IsShowLineWeight := cbShowLineWeight.Checked;
  if cbShowLineWeight.Checked then
    TsgCADImage(sgPaintBox.Picture.Graphic).ColorToLineWeight.Text := memColorToLineWeight.Text
  else
    TsgCADImage(sgPaintBox.Picture.Graphic).ColorToLineWeight.Text := '';
  sgPaintBox.Invalidate;
end;

procedure TForm1.PageControl1Change(Sender: TObject);
begin
  if TreeView1.Items.Count = 0 then
    LoadStructure;
end;

procedure TForm1.sbMergeFilesClick(Sender: TObject);
const
  cnstLayerName:  string = 'new_layer';
  cnstLTypeName:  string = 'HIDDEN';
  cnstCurDirName: string = 'MergeFiles';
  cnstFileNames:  array [0..1] of string = ('Frame.dxf', 'Inserted.dxf');
var
  vCurrDir, vPrevCurDir: string;
  vGlobalCADFile: TsgCADImage;
  vScale: TFPoint;
  vLType: TsgDXFLineType;
  vLine: TsgDXFLine;
  vArc: TsgDXFArc;
begin
  vPrevCurDir := GetCurrentDir;
  vCurrDir := ExtractFilePath(Application.ExeName);
  if (vCurrDir <> '') and (vCurrDir[Length(vCurrDir)] <> '\') then
    vCurrDir := vCurrDir + '\';
  vCurrDir := vCurrDir + cnstCurDirName;
  if not DirectoryExists(vCurrDir) then
    vCurrDir := ExtractFilePath(vCurrDir);
  SetCurrentDir(vCurrDir);
  try
    MICloseClick(nil);
    MacroStrings.Text :=  Memo1.Text;
    vGlobalCADFile := TsgCADImage.Create;
    vGlobalCADFile.Converter.InitializeSections;
    { Drawing have not border }
    vGlobalCADFile.IsWithoutBorder := True;
    vGlobalCADFile.ColorToLineWeight.Add('clYellow = 0.1');
    vGlobalCADFile.ColorToLineWeight.Add('clLime = 0.3');
    vGlobalCADFile.ColorToLineWeight.Add('clAqua = 0.1');
    vGlobalCADFile.ColorToLineWeight.Add('clBlue= 0.1');
    vGlobalCADFile.ColorToLineWeight.Add('clFuchsia = 0.1');
    vGlobalCADFile.ColorToLineWeight.Add('clBlack = 0.1');
    vGlobalCADFile.ColorToLineWeight.Add('clGray= 0.5');
    vGlobalCADFile.ColorToLineWeight.Add('clSilver= 1');
    // or this: vGlobalCADFile.ColorToLineWeight.Assign(Self.memColorToLineWeight.Lines);
    { Adding the new linetype to image-converter }
    vLType := TsgDXFLineType.Create;
    vLType.Name := cnstLTypeName;
    vLType.Lines.Scale := 50;       // linetype scale
    vLType.Lines.AddTick(0.25);     // length of the "solid" part of a line
    vLType.Lines.AddTick(-0.125);   // length of the "empty" part of a line
    if Assigned(vGlobalCADFile.Converter.OnCreate) then
      vGlobalCADFile.Converter.OnCreate(vLType);
    vGlobalCADFile.Converter.Loads(vLType);
    vGlobalCADFile.Converter.Sections[csLTypes].AddEntity(vLType);

    { The first inserted file }
    vGlobalCADFile.AddScaledDXF(
      GetCADFile(cnstFileNames[0]), // TsgCADImage object for inserting
      ChangeFileExt(ExtractFileName(cnstFileNames[0]), ''), // Name
      MakeFPoint(0.0, 0.0, 0.0),    // Position in ACAD coords
      cnstFPointSingle,             // Scale factor
      0.0);                         // Rotation angle (degrees)

    { The second inserted file }
    vScale := MakeFPoint(10, 10, 1);
    vGlobalCADFile.AddScaledDXF(
      GetCADFile(cnstFileNames[1]), // TsgCADImage object for inserting
      ChangeFileExt(ExtractFileName(cnstFileNames[1]), ''), // Name
      MakeFPoint(80.0, 100.0, 0.0), // Position in ACAD coords
      vScale,                       // Scale factor
      0.0);                         // Rotation angle (degrees)
    { Adding the line entity }
    vLine := TsgDXFLine.Create;
    vLine.Point  := MakeFPoint( 80, 100, 0);// first point
    vLine.Point1 := MakeFPoint(150, 150, 0);// second point
    vLine.Color := clBlue;                 // color
    vLine.Layer := vGlobalCADFile.Converter.LayerByName(cnstLayerName);
    vLine.SetLType(vGlobalCADFile.Converter.LTypeByName(cnstLTypeName));
    if Assigned(vGlobalCADFile.Converter.OnCreate) then
      vGlobalCADFile.Converter.OnCreate(vLine);
    vGlobalCADFile.Converter.Loads(vLine);
    vGlobalCADFile.Converter.Sections[csEntities].AddEntity(vLine);

    { Adding the arc entity }
    vArc := TsgDXFArc.Create;
    vArc.StartAngle := 60;                  // start angle in degrees
    vArc.EndAngle := 210;                   // end angle in degrees
    vArc.Radius := 50;                      // radius
    vArc.Point := MakeFPoint(110, 160, 0);  // center point
    vArc.Color := clBlue;                  // color
    vArc.Layer := vGlobalCADFile.Converter.LayerByName(cnstLayerName);
    vArc.SetLType(vGlobalCADFile.Converter.LTypeByName(cnstLTypeName));
    if Assigned(vGlobalCADFile.Converter.OnCreate) then
      vGlobalCADFile.Converter.OnCreate(vArc);
    vGlobalCADFile.Converter.Loads(vArc);
    vGlobalCADFile.Converter.Sections[csEntities].AddEntity(vArc);

    { Apply new drawing extents }
    vGlobalCADFile.GetExtents;

    { Copying of new drawing to sgPaintBox }
    btnLayers.Enabled := True;
    sgPaintBox.Picture.Graphic := vGlobalCADFile;
    EnableScales;
    sb3DOrbit.Enabled := True;
    sb3DOrbit.Down := False;
    vGlobalCADFile.Free;
    TabSheet2.TabVisible := True;
  finally
    SetCurrentDir(vPrevCurDir);
  end;
end;

procedure TForm1.btnLTypeHalfClick(Sender: TObject);
var
  I, J: Integer;
begin
  if Img = nil then Exit;
  Img.Converter.LTScale := Img.Converter.LTScale / 2;
  for I := 0 to Img.Converter.Counts[csEntities] - 1 do
    Img.Converter.Loads(Img.Converter.Entities[I]);
  for I := 0 to Img.Converter.Counts[csBlocks] - 1 do
    for J := 0 to Img.Converter.Blocks[I].Count - 1 do
      Img.Converter.Loads(Img.Converter.Blocks[I].Entities[J]);
  sgPaintBox.Invalidate;
end;

procedure TForm1.btnFitToWindowClick(Sender: TObject);
begin
  sgPaintBox.FitToSize;
  btnFitToWindow.Enabled := False;
end;

procedure TForm1.BtnRealClick(Sender: TObject);
begin
  sgPaintBox.Scale := 1.0;
  BtnReal.Enabled := False;
end;

function TForm1.GetImg: TsgCADImage;
begin
  Result := nil;
  if sgPaintBox.Picture.Graphic is TsgCADImage then
    Result := TsgCADImage(sgPaintBox.Picture.Graphic);
end;

initialization

  {$IFDEF MEMCHK}
  MemChk
  {$ENDIF}
end.
