unit Unit1;

//{$DEFINE SG_USEDXFEXPORT}// only for DXFExport VCL
//{$DEFINE SG_DEBUG}

{$IFDEF SG_DEBUG}
  {$DEFINE MEMCHK}
{$ENDIF}

interface

uses
  fAddScaledFile,
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, JPEG,
  ExtCtrls, StdCtrls, DXFImage, DXFConv, ComCtrls, Menus, Printers, MVFont, Math,
  sgConsts, ExtDlgs, Buttons, SGExport,
  {$IFNDEF sgDXFONLY}
  DWG, HPGL2, SVG, CGM,
  {$ENDIF}
  {$IFDEF SG_USEDXFEXPORT}
  DXFExport,
  {$ENDIF}
  {$IFDEF MEMCHK}
  MemCheck,
  {$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;
    MIView: TMenuItem;
    MiOEM: TMenuItem;
    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;
    sbMergingTest: TSpeedButton;
    btnLTypeHalf: TButton;
    miSaveToDXF: TMenuItem;
    btnFitToWindow: TSpeedButton;
    procedure MIOpenClick(Sender: TObject);
    procedure MICloseClick(Sender: TObject);
    procedure MIExitClick(Sender: TObject);
    procedure TreeView1Change(Sender: TObject; Node: TTreeNode);
    procedure MiOEMClick(Sender: TObject);
    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 sbMergingTestClick(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: TsgDXFImage;
  public
    property sgPaintBox: TsgDrawingNavigator read FsgPaintBox;
    property Img: TsgDXFImage read GetImg;
  end;

var
  Form1: TForm1;
  Start: Cardinal;

implementation

{$R *.DFM}
//{$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;
    with prbProgress do Position := Position + 1;
    for I:=0 to E.Count-1 do Add(Parent, E[I]);
  end;

var
  I: Integer;
  S_LStructure: string;
begin
  TreeView1.Items.Clear;
  prbProgress.Position := 0;
  prbProgress.Max := Img.Converter.Count;
  pnlFileName.Caption := S_LStructure;
  pnlFileName.Update;
  TreeView1.Items.BeginUpdate;
  try
    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;
  MiOEM.Enabled := vCADFlag;
  MiOEM.Checked := vCADFlag and not Img.Converter.OEM;
  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;
  MiOEM.Enabled := False;
  BtnSave.Enabled := False;
  PageControl1.ActivePage := tbsImage;
  TabSheet2.TabVisible := False;
  EnableScales;
  sgPaintBox.SetBounds(0,0,0,0);
  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.MiOEMClick(Sender: TObject);
const CS: array[Boolean] of TFontCharset = (DEFAULT_CHARSET, OEM_CHARSET);
begin
  with MiOEM do Checked := not Checked;
  if Img=nil then Exit;
  Img.Charset := CS[MiOEM.Checked];
  ListBox1.Font.Charset := Img.Charset;
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
  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;
  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 SG_USEDXFEXPORT}
var
  E: TsgDXFExport;
  vMet: TMetafile;
  vGr: TGraphic;
  vOffX, vOffY, vUSize: TsgFloat;
  vSaveToFile: string;
{$ENDIF}
begin
  {$IFDEF SG_USEDXFEXPORT}
  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 TsgDXFImage) or (vGr is TMetafile)) then
    begin
      ShowMessage('Raster drawings can not be saved to DXF format.');
      Exit;
    end
    else
    begin
      if not (vGr is TsgDXFImage) then
      begin
        E.Use01MM := False;
        E.Canvas.StretchDraw(Rect(0, 0, vGr.Width, vGr.Height), vGr);
        E.EndDraw;
      end
      else
      begin
        vMet := TsgDXFImage(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 DXFExport VCL only.'), 'WARNING', MB_ICONWARNING);
  {$ENDIF}
end;

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

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

procedure TForm1.mmiNormalClick(Sender: TObject);
begin
  if sgPaintBox.Empty or not
    (sgPaintBox.Picture.Graphic is TsgDXFImage) then
    Exit;
  (sgPaintBox.Picture.Graphic as TsgDXFImage).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
  {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 TsgDXFImage 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: TsgDXFImage;
begin
  sgPaintBox.Orbit3D.Visible := False;
  fmAddScaledFile := TfmAddScaledFile.Create(self);
  try
    if (fmAddScaledFile.ShowModal = mrOk) and
       (fmAddScaledFile.FilesCount <> 0) then
    begin
      vCAD := TsgDXFImage(fmAddScaledFile.CADFile);
      btnLayers.Enabled := True;
      if cbShowLineWeight.Checked then
        vCAD.ColorToLineWeight.Text :=  Memo1.Text
      else
        vCAD.ColorToLineWeight.Text :=  '';
      sgPaintBox.Picture.Graphic := vCAD;
      EnableScales;
      sb3DOrbit.Enabled := True;
      sb3DOrbit.Down := False;
      miSaveAs.Enabled := True;
      miSaveToDXF.Enabled := miSaveAs.Enabled;
    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 TsgDXFImage then
    begin
      PxlsX := GetDeviceCaps(Printer.Handle, LOGPIXELSX);
      PxlsY := GetDeviceCaps(Printer.Handle, LOGPIXELSY);
      if TsgDXFImage(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
    TsgDXFImage(sgPaintBox.Picture.Graphic).ColorToLineWeight.Text := memColorToLineWeight.Text
  else
    TsgDXFImage(sgPaintBox.Picture.Graphic).ColorToLineWeight.Text := '';
  sgPaintBox.Invalidate;
end;

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

procedure TForm1.sbMergingTestClick(Sender: TObject);
const
  cnstLayerName:  string = 'new_layer';
  cnstLTypeName:  string = 'HIDDEN';
  cnstCurDirName: string = 'MergeFiles';
  cnstFileNames:  array [0..1] of string = ('Frame.dxf', 'Inserted.dxf');
  N: array[TConvSection] of string = ('TABLES','BLOCKS','ENTITIES','LTYPE',
    'LAYERS', 'STYLE', 'DIMSTYLE', 'BLOCK_RECORD', 'VPORTS');
var
  vGlobalCADFile: TsgDXFImage;
  vCADFiles: array [0..1] of TObject;
  vScale: TFPoint;
  vLType: TsgDXFLineType;
  vLine: TsgDXFLine;
  vArc: TsgDXFArc;
begin
  SetCurrentDir(ExtractFilePath(Application.ExeName)+'\'+cnstCurDirName);
  MacroStrings.Text :=  Memo1.Text;
  vGlobalCADFile := TsgDXFImage.Create;
  { 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
  vGlobalCADFile.Converter.InitializeSections;

  { The first inserted file }
  if ExtractFileExt(cnstFileNames[0]) = '.dxf' then
    vCADFiles[0] := TsgDXFImage.Create
  {$IFDEF sgDXFONLY}
  ;
  {$ELSE}
  else
    vCADFiles[0] := TsgDWGImage.Create;
  {$ENDIF}
  vScale := MakeFPoint(1, 1, 1);
  TsgDXFImage(vCADFiles[0]).LoadFromFile(cnstFileNames[0]);
  vGlobalCADFile.AddScaledDXF(
    vCADFiles[0],                 // TsgDXFImage object for inserting
    ChangeFileExt(ExtractFileName(cnstFileNames[0]), ''), // Name
    MakeFPoint(0.0, 0.0, 0.0),    // Position in ACAD coords
    vScale,                       // Scale factor
    0.0);                         // Rotation angle (degrees)

  { The second inserted file }
  if ExtractFileExt(cnstFileNames[1]) = '.dxf' then
    vCADFiles[1] := TsgDXFImage.Create
  {$IFDEF sgDXFONLY}
  ;
  {$ELSE}
  else
    vCADFiles[1] := TsgDWGImage.Create;
  {$ENDIF}
  vScale := MakeFPoint(10, 10, 1);
  TsgDXFImage(vCADFiles[1]).LoadFromFile(cnstFileNames[1]);
  vGlobalCADFile.AddScaledDXF(
    vCADFiles[1],                  // TsgDXFImage object for inserting
    ChangeFileExt(ExtractFileName(cnstFileNames[1]), ''), // Name
    MakeFPoint(80.0, 100.0, 0.0),  // Position in ACAD coords
    //{ Use this code for superpose (Left, Bottom) corners of drawings }
    //MakeFPoint(vGlobalCADFile.Converter.Layouts[0].Box.Left - vScale.X*TsgDXFImage(vCADFiles[1]).Converter.Layouts[0].Box.Left, vGlobalCADFile.Converter.Layouts[0].Box.Bottom - vScale.Y*TsgDXFImage(vCADFiles[1]).Converter.Layouts[0].Box.Bottom, 0),
    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.SetColor(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.SetColor(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;
end;

procedure TForm1.btnLTypeHalfClick(Sender: TObject);
var
  I, J: Integer;
begin
  if Img = nil then Exit;
  Img.Converter.LScale := Img.Converter.LScale / 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: TsgDXFImage;
begin
  Result := nil;
  if sgPaintBox.Picture.Graphic is TsgDXFImage then
    Result := TsgDXFImage(sgPaintBox.Picture.Graphic);
end;

initialization

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