//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop

#include "fMain.h"
#include "fLayers.h"
#include "fAddScaledFile.h"
#include "Math.h"

#include <sgConsts.hpp>
#ifndef sgDXFONLY
#include <DWG.hpp>
#include <HPGL2.hpp>
#include <SVG.hpp>
#include <CGM.hpp>
#endif

#include <DXFExport.hpp>
#include <CADToDXF.hpp>
#include <sgExport.hpp>
#include <ShellAPI.hpp>
#include <Printers.hpp>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"

AnsiString sNotVectorial = "Raster drawings can not be saved to DXF format";

TfmMain *fmMain;

int Start;
//---------------------------------------------------------------------------
__fastcall TfmMain::TfmMain(TComponent* Owner)
  : TForm(Owner)
{
}
//---------------------------------------------------------------------------

void _fastcall TfmMain::Time()
{
  int T;
  T = (GetCurrentTime() - Start) / 1000;
  TVarRec v[] = {T / 60, T % 60};
  Panel3->Caption.Format("%.2d:%.2d", v, 1);
  Panel3->Update();
}

void TfmMain::AddTree(TTreeNode * Parent, TsgDXFEntity * E)
{
    Parent = TreeView1->Items->AddChildObject(Parent, E->EntName(), E);
    Application->ProcessMessages();
    ProgressBar1->Position =+ 1;
    for (int i = 0; i < E->Count; i++) AddTree(Parent, E->Entities[i]);
}


void _fastcall TfmMain::LoadStructure()
{
  AnsiString S_LStructure;
  ProgressBar1->Position = 0;
  ProgressBar1->Max = FImg->Converter->Count();
  Panel1->Caption = S_LStructure;
  Panel1->Update();
  TreeView1->Items->BeginUpdate();
  try
  {
    for (int i = 0; i < FImg->Converter->Main->Count; i++)
      AddTree(NULL, FImg->Converter->Main->Entities[i]);
  }
  __finally
  {
    ProgressBar1->Position = 0;
    TreeView1->Items->EndUpdate();
  }
}

TsgDXFImage * _fastcall TfmMain::GetImg()
{
  TsgDXFImage *vImg = NULL;
  if ((!sgPaintBox->Empty())&&
     (sgPaintBox->Picture->Graphic->InheritsFrom(__classid(TsgDXFImage))))
    vImg = (TsgDXFImage *)(sgPaintBox->Picture->Graphic);
  return vImg;
}

void _fastcall TfmMain::Open(AnsiString FileName)
{
  TreeView1->Items->Clear();
  sgPaintBox->Orbit3D->Visible = false;
  Start = GetCurrentTime();
  Screen->Cursor = crHourGlass;
  try
  {
    sb3DOrbit->Down = false;
    sgPaintBox->LoadFromFile(FileName);
    if (sgPaintBox->Picture->Graphic->InheritsFrom(__classid(Graphics::TBitmap)))
      sgPaintBox->Picture->Bitmap->HandleType = bmDDB;
    Panel1->Caption = UpperCase(ExtractFileName(FileName));
    HelpContext = 3;
    if (FImg)
    {
      if (cbShowLineWeight->Checked)
        FImg->ColorToLineWeight->Text = memColorToLineWeight->Text;
      FImg->IsShowLineWeight = cbShowLineWeight->Checked;
      TabSheet2->TabVisible = true;
    }
    Panel1->Caption = UpperCase(ExtractFileName(FileName));
    MiOEMClick(NULL);
  }
  __finally
  {
    actMainUpdate(NULL);
    ProgressBar1->Position = 0;
    Screen->Cursor = crDefault;
  }
}

void __fastcall TfmMain::FormCreate(TObject *Sender)
{
  FsgPaintBox = new TSGDrawingNavigator(this);
  sgPaintBox->Parent = tbsImage;
  sgPaintBox->Align = alClient;
  sgPaintBox->RectZooming = true;
  sgPaintBox->ScalingOnMouseWheel = true;
  sgPaintBox->AutoFocus = true;
  sgPaintBox->OnChangeScale = sgPaintBoxScaling;
  sgPaintBox->OnProgress = sgPaintBoxProgress;
  sgPaintBox->OnMouseMove = sgPaintBoxMouseMove;
  OpenDialog->Filter = GraphicFilter(__classid(TGraphic));
  /*if (ParamCount > 0)
  {
    Open(ParamStr(1));
    OpenDialog->FileName = ParamStr(1);
  } */
}

void TfmMain::Scroll(TShiftState Shift, bool Both, WORD Msg, WORD Code1,
  WORD Code2)
{
  if (Shift.Contains(ssCtrl)) Code1 = Code2;
  SendMessage(sgPaintBox->Handle, Msg, Code1, 0);
  if ((Both) && (Shift.Contains(ssCtrl)))
    SendMessage(sgPaintBox->Handle, WM_VSCROLL, Code1, 0);
}

void __fastcall TfmMain::FormKeyDown(TObject *Sender, WORD &Key,
      TShiftState Shift)
{
  if (Key == VK_ESCAPE) Close();
  if (sgPaintBox->Empty()) return;
  if ((PageControl1->ActivePage != tbsImage) || (!Shift.Contains(ssCtrl))) return;
  switch (Key){
    case VK_ADD:
      BtnPlusClick(NULL);
      break;
    case VK_SUBTRACT:
      BtnMinusClick(NULL);
      break;
    case VK_MULTIPLY:
      BtnRealClick(BtnReal);
      break;
  }
}

void __fastcall TfmMain::OpenDialogShow(TObject *Sender)
{
  Dxfimage::MinDXFSize = 140;
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::OpenDialogClose(TObject *Sender)
{
  Dxfimage::MinDXFSize = 0;
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::miSaveToDXFClick(TObject *Sender)
{
  TsgDXFExport *E;
  TMetafile *vMet;
  TGraphic *vGr = sgPaintBox->Picture->Graphic;
  TsgFloat vOffX, vOffY, vUSize;
  AnsiString vSaveToFile;

  if (!vGr) return;
  SavePictureDialog->FilterIndex = 5;
  if (!SavePictureDialog->Execute()) return;
  if (AnsiLowerCase(ExtractFileExt(SavePictureDialog->FileName)) != ".dxf")
     SavePictureDialog->FileName = SavePictureDialog->FileName + ".dxf";
  vSaveToFile = SavePictureDialog->FileName;
  if (vGr->InheritsFrom(__classid(TsgDXFImage))||
     vGr->InheritsFrom(__classid(TMetafile)))
  {
    E = new TsgDXFExport;
    try
    {
      E->IsParseWhite = true;// false
      if (vGr->InheritsFrom(__classid(TsgDXFImage)))
      {
        E->Use01MM = false;
        E->Canvas->StretchDraw(Rect(0, 0, vGr->Width, vGr->Height), vGr);
        E->EndDraw();
      }
      else
      {
        vMet = ((TsgDXFImage *)(vGr))->ExportToMetafile(vOffX, vOffY, vUSize);
        OffsetX = vOffX;
        OffsetY = vOffY;
        E->UnitSize = vUSize;
        E->LoadFromMetafile(vMet);
        delete vMet;
      }
      E->SaveToFile(vSaveToFile);
    }
    __finally
    {
      delete E;
    }
    MessageBox(Application->Handle, "DXF Export is made via DXF Export VCL software which is not part of CAD Import VCL and should be bought additionally if needed.", "WARNING", MB_ICONWARNING);
  }
  else
  {
    ShowMessage(sNotVectorial);
  }
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::MIExitClick(TObject *Sender)
{
  Close();
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::MICloseClick(TObject *Sender)
{
  ListBox1->Clear();
  TreeView1->Items->Clear();
  sgPaintBox->Picture->Graphic = NULL;
  FImg = NULL;
  Panel1->Caption = "";
  Panel3->Caption = "";
  pnlCoords->Caption = "";
  PageControl1->ActivePage = tbsImage;
  TabSheet2->TabVisible = false;
  ProgressBar1->Max = 100;
  HelpContext = 1;
  actMainUpdate(NULL);
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::MiOEMClick(TObject *Sender)
{
  MiOEM->Checked = !MiOEM->Checked;
  if (FImg == NULL) return;
  if (MiOEM->Checked)
    FImg->Charset = OEM_CHARSET;
  else
    FImg->Charset = DEFAULT_CHARSET;
  ListBox1->Font->Charset = FImg->Charset;
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::TreeView1Change(TObject *Sender, TTreeNode *Node)
//---------------------------------------------------------------------------
{
  if (!Node->Selected) return;
  TsgDXFEntity *E = ((TsgDXFEntity *)Node->Data);
  AnsiString S;
  if (E == NULL)
    ListBox1->Clear();
  else
  {
    if ((E->SrcStart == NULL) || (E->SrcEnd == NULL))
      ListBox1->Clear();
    else
    {
      S = AnsiString(E->SrcStart, E->SrcEnd - E->SrcStart);
      ListBox1->Items->Text = S;
    }
  }
}
//---------------------------------------------------------------------------
void __fastcall TfmMain::MIPrintClick(TObject *Sender)
{
  if (sgPaintBox->Width > sgPaintBox->Height)
    Printer()->Orientation = poLandscape;
  else
    Printer()->Orientation = poPortrait;
  if (PrintDialog1->Execute())
  {
    double W = Printer()->PageWidth / sgPaintBox->Picture->Width;
    double H = Printer()->PageHeight / sgPaintBox->Picture->Height;
    if (W > H) W = H;
    int PW = W * sgPaintBox->Picture->Width;
    int PH = W * sgPaintBox->Picture->Height;
    Printer()->BeginDoc();
    Printer()->Canvas->StretchDraw(Bounds((Printer()->PageWidth - PW) / 2,
      (Printer()->PageHeight - PH) / 2, PW, PH), sgPaintBox->Picture->Graphic);
    Printer()->EndDoc();
  }
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::BtnPrevClick(TObject *Sender)
{
  sgPaintBox->CallPreviousView();
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::sgPaintBoxProgress(TObject *Sender,
      TProgressStage Stage, BYTE PercentDone, bool RedrawNow,
      const TRect &R, const AnsiString Msg)
{
  if (Stage == psStarting)
  {
    Panel1->Caption = Msg;
    Panel1->Update();
  }
  ProgressBar1->Position = PercentDone;
  Time();
  if (Stage == psEnding)
  {
    ProgressBar1->Position = 0;
    Panel1->Caption = UpperCase(ExtractFileName(OpenDialog->FileName));
  }
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::BtnPlusClick(TObject *Sender)
{
  sgPaintBox->Scale = sgPaintBox->Scale * 2.0;
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::BtnMinusClick(TObject *Sender)
{
  sgPaintBox->Scale = sgPaintBox->Scale * 0.5;
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::PageControl1Changing(TObject *Sender,
      bool &AllowChange)
{
  AllowChange = (FImg != NULL);
  FocusControl(NULL);  
}
//---------------------------------------------------------------------------


void __fastcall TfmMain::ScrollBox1Resize(TObject *Sender)
{
  if (!(sgPaintBox->Empty()))
    sgPaintBox->SetBounds(sgPaintBox->Left,sgPaintBox->Top,
       sgPaintBox->Width,sgPaintBox->Height);  
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::BtnSaveClick(TObject *Sender)
{
  TsgExport * E;
  TMetafileCanvas * vMC;
  TMetafile * vM;
  AnsiString vFileName;
  int vWidth, vHeight;
  double vRatio;
  TGraphic * vGr;

  if (sgPaintBox->Empty() || !SavePictureDialog->Execute()) return;
  vFileName = SavePictureDialog->FileName;
  vGr = sgPaintBox->Picture->Graphic;
  vWidth = vGr->Width;
  vHeight = vGr->Height;
  // Converting CAD-drawing width/height to Screen size for export
  if (vHeight)
    vRatio = (double)vWidth / vHeight;
  else
    vRatio = 1.0;
  if (vRatio <= 1.0)
  {
    vHeight = Screen->Height;
    vWidth = Ceil(vHeight * vRatio);
  }
  else
  {
    vWidth = Screen->Width;
    vHeight = Ceil(vWidth / vRatio);
  }
  switch (SavePictureDialog->FilterIndex)
  {
    case 1:
      if (AnsiLowerCase(ExtractFileExt(vFileName)) != ".bmp")
        vFileName = vFileName + ".bmp";
      break;
    case 2:
      if ((AnsiLowerCase(ExtractFileExt(vFileName)) != ".jpg") ||
         (AnsiLowerCase(ExtractFileExt(vFileName)) != ".jpeg"))
        vFileName = vFileName + ".jpg";
      break;
    case 3:
      if (AnsiLowerCase(ExtractFileExt(vFileName)) != ".emf")
        vFileName = vFileName + ".emf";
      break;
    case 4:
      vM = new TMetafile();
      try
      {
        vM->Width = vWidth;
        vM->Height = vHeight;
        vMC = new TMetafileCanvas(vM, 0);
        try
        {
          vMC->StretchDraw(Rect(0, 0, vWidth, vHeight), vGr);
        }
        __finally
        {
          delete vMC;
        }
        if (AnsiLowerCase(ExtractFileExt(vFileName)) != ".wmf")
          vFileName = vFileName + ".wmf";
        vM->SaveToFile(vFileName);
      }
      __finally
      {
        delete vM;
      }
      return;
    case 5:
      if (AnsiLowerCase(ExtractFileExt(vFileName)) != ".dxf")
        vFileName = vFileName + ".dxf";
      SaveToDXF(vFileName);
      return;
  }  /* switch SavePictureDialog->FilterIndex */
  E = new TsgExport();
  try
  {
    E->ExportTo(vGr, vFileName,
      TsgExportFormat(SavePictureDialog->FilterIndex-1), vWidth, vHeight);
  }
  __finally
  {
    delete E;
  }
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::Disabled1Click(TObject *Sender)
{
  if ((sgPaintBox->Empty()) || (FImg == NULL)) return;
  ((TsgDXFImage *)sgPaintBox->Picture->Graphic)->DrawMode = Dxfimage::dmGray;
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::Black1Click(TObject *Sender)
{
  if ((sgPaintBox->Empty()) || (FImg == NULL)) return;
  ((TsgDXFImage *)sgPaintBox->Picture->Graphic)->DrawMode = Dxfimage::dmBlack;
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::Normal1Click(TObject *Sender)
{
  if ((sgPaintBox->Empty()) || (FImg == NULL)) return;
  ((TsgDXFImage *)sgPaintBox->Picture->Graphic)->DrawMode = Dxfimage::dmNormal;
}
//---------------------------------------------------------------------------


void __fastcall TfmMain::SoftGoldHomePage1Click(TObject *Sender)
{
  ShellExecute(Handle, "open", "www.cadsofttools.com", "", "", SW_SHOW);  
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::MIAboutClick(TObject *Sender)
{
  ShowMessage("DWG/DXF VCLs demo version \nPlease contact www.cadsofttools.com to order a full version");  
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::btnLayersClick(TObject *Sender)
{
  if ((FImg == NULL)||(!(FImg->Converter))) return;
  try
  {
    LayersDialogExecute(FImg, sgPaintBox);
  }
  catch (Exception &exception)
  {
  }
}
//---------------------------------------------------------------------------


void __fastcall TfmMain::sb3DOrbitClick(TObject *Sender)
{
  sb3DOrbit->Down = sb3DOrbit->Down | false;
  sgPaintBox->Orbit3D->Visible = sb3DOrbit->Down;
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::sgPaintBoxMouseMove(TObject *Sender,
      TShiftState Shift, int X, int Y)
{
  TFPoint vPt;
  AnsiString S, vUnits;
  if (GetImg())
  {
    vPt = sgPaintBox->GetDrawingCoords(X, Y, vUnits);
    TVarRec v[] = {vPt.X, vPt.Y, vPt.Z};
    S = Format("(%.3f; %.3f; %.3f)", v, 2);
    if ((vUnits != NULL)&&(vUnits != ""))
      S = S + " (" + vUnits + ")";
    pnlCoords->Caption = S;
  }
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::sbAddScaledFilesClick(TObject *Sender)
{
  TsgDXFImage *vCAD;
  sgPaintBox->Orbit3D->Visible = false;
  fmAddScaledFile = new TfmAddScaledFile(this);
  fmAddScaledFile->ShowModal();
  if ((fmAddScaledFile->CADFile != NULL)&&(fmAddScaledFile->FilesCount != 0))
  {
    vCAD = fmAddScaledFile->CADFile;
    if (cbShowLineWeight->Checked)
      vCAD->ColorToLineWeight->Text = Memo1->Text;
    else
      vCAD->ColorToLineWeight->Text =  "";
    sgPaintBox->Picture->Graphic = vCAD;
    actMainUpdate(NULL);
    btnFitToScreenClick(Sender);
  }
  delete fmAddScaledFile;
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::BtnPrintClick(TObject *Sender)
{
  if (sgPaintBox->Width > sgPaintBox->Height)
    Printer()->Orientation = poLandscape;
  else
    Printer()->Orientation = poPortrait;
  if (PrintDialog1->Execute())
  {
    double W = Printer()->PageWidth / sgPaintBox->Picture->Width;
    double H = Printer()->PageHeight / sgPaintBox->Picture->Height;
    if (W > H) W = H;
    int PW = W * sgPaintBox->Picture->Width;
    int PH = W * sgPaintBox->Picture->Height;
    Printer()->BeginDoc();
    Printer()->Canvas->StretchDraw(Bounds((Printer()->PageWidth - PW) / 2,
      (Printer()->PageHeight - PH) / 2, PW, PH), sgPaintBox->Picture->Graphic);
    Printer()->EndDoc();
  }
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::BtnPrint1Click(TObject *Sender)
{
  double koef = 25.4;
  double PxlsX, PxlsY;
  int W, H;
  HDC hPrinter;

  if (sgPaintBox->Width > sgPaintBox->Height)
    Printer()->Orientation = poLandscape;
  else
    Printer()->Orientation = poPortrait;

  if (PrintDialog1->Execute())
  {
    W = FImg->Width;
    H = FImg->Height;
    PxlsX = 1;
    PxlsY = 1;
    if (sgPaintBox->Picture->Graphic->ClassType() == __classid(TsgDXFImage))
    {
      hPrinter = Printer()->Handle;
      PxlsX = GetDeviceCaps(hPrinter, LOGPIXELSX);
      PxlsY = GetDeviceCaps(hPrinter, LOGPIXELSY);
      if (FImg->Millimetres)
      {
        PxlsX = PxlsX / koef;
        PxlsY = PxlsY / koef;
      }
    }
    Printer()->Title = "CAD Image VCL printing 1:1";
    Printer()->BeginDoc();
    Printer()->Canvas->StretchDraw(Rect(0, 0, Ceil(PxlsX * W), Ceil(PxlsY * H)), FImg);
    Printer()->EndDoc();
  }
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::FormDestroy(TObject *Sender)
{
//
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::cbShowLineWeightClick(TObject *Sender)
{
  if (!(FImg)) return;
  FImg->IsShowLineWeight = cbShowLineWeight->Checked;
  if (cbShowLineWeight->Checked)
    FImg->ColorToLineWeight->Text = memColorToLineWeight->Text;
  else
    FImg->ColorToLineWeight->Text = "";
  sgPaintBox->Repaint();
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::PageControl1Change(TObject *Sender)
{
  if (!TreeView1->Items->Count) LoadStructure();
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::sbMergingTestClick(TObject *Sender)
{
  TsgDXFImage *vGlobalCADFile;
  TsgDXFImage *Im;
  AnsiString cnstLayerName = "new_layer";
  AnsiString cnstLTypeName = "HIDDEN";
  AnsiString cnstCurDirName = "MergeFiles\\";
  char *cnstFileNames[2] = {"Frame.dxf", "Inserted.dxf"};
  
  TObject *vCADFiles[2];
  TsgDXFLineType *vLType;
  TsgDXFLine *vLine;
  TsgDXFArc *vArc;
  TsgDXFTable *vTbl;
  int I;
  AnsiString S;

  S = ExtractFilePath(Application->ExeName) + cnstCurDirName;
  SetCurrentDir(S);
  MacroStrings->Text = Memo1->Text;
  vGlobalCADFile = new TsgDXFImage;
  // 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 = new TsgDXFLineType;
  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")
    vCADFiles[0] = new TsgDXFImage;
  #ifdef sgDXFONLY
  ;
  #else
  else
    vCADFiles[0] = new TsgDWGImage;
  #endif
  Im = dynamic_cast<TsgDXFImage *>(vCADFiles[0]);
  Im->LoadFromFile(S + (AnsiString)(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
    MakeFPoint(1, 1, 1),          // Scale factor
    0.0);                         // Rotation angle (degrees)

  // The second inserted file
  if (ExtractFileExt(cnstFileNames[1]) == ".dxf")
    vCADFiles[1] = new TsgDXFImage;
  #ifdef sgDXFONLY
  ;
  #else
  else
    vCADFiles[1] = new TsgDWGImage;
  #endif
  Im = dynamic_cast<TsgDXFImage *>(vCADFiles[1]);
  Im->LoadFromFile(S + (AnsiString)(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
    MakeFPoint(10, 10, 1),         // scale factor
    0.0);                          // rotation angle (degrees)

  // Adding the line entity
  vLine = new TsgDXFLine;
  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 (vGlobalCADFile->Converter->OnCreate != NULL)
    vGlobalCADFile->Converter->OnCreate(vLine);
  vGlobalCADFile->Converter->Loads(vLine);
  vGlobalCADFile->Converter->Sections[csEntities]->AddEntity(vLine);

  // Adding the arc entity
  vArc = new TsgDXFArc;
  vArc->StartAngle = 60;                  // start angle in degrees
  vArc->EndAngle = 210;                   // } 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 (vGlobalCADFile->Converter->OnCreate != NULL)
    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
  vGlobalCADFile->IsWithoutBorder = false;
  sgPaintBox->Picture->Graphic = vGlobalCADFile;
  actMainUpdate(NULL);
  sgPaintBox->Invalidate();
  sb3DOrbit->Down = false;
  delete vGlobalCADFile;
}

//---------------------------------------------------------------------------

void __fastcall TfmMain::btnLTypeHalfClick(TObject *Sender)
{
  int I, J;
  if (sgPaintBox->Empty()) return;
  if (FImg)
  {
    if (FImg == NULL) return;
    FImg->Converter->LScale = FImg->Converter->LScale / 2;
    for(I=0;I<FImg->Converter->Counts[csEntities] - 1;I++)
      FImg->Converter->Loads(FImg->Converter->Entities[I]);
    for(I=0;I<FImg->Converter->Counts[csBlocks] - 1;I++)
      for(J=0;J<FImg->Converter->Blocks[I]->Count - 1;J++)
        FImg->Converter->Loads(FImg->Converter->Blocks[I]->Entities[J]);
    sgPaintBox->Invalidate();
  }
}
//---------------------------------------------------------------------------


void __fastcall TfmMain::BtnOpenClick(TObject *Sender)
{
  if (!OpenDialog->Execute()) return;
  MICloseClick(NULL);
  Open(OpenDialog->FileName);
}
//---------------------------------------------------------------------------


void __fastcall TfmMain::BtnRealClick(TObject *Sender)
{
  TPoint P;
  P = sgPaintBox->Center();
  sgPaintBox->AlterScale(((TComponent *)Sender)->Tag / 100.0, true, P);
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::btnFitToScreenClick(TObject *Sender)
{
  sgPaintBox->FitToSize();
}
//---------------------------------------------------------------------------

void _fastcall TfmMain::sgPaintBoxScaling(TObject *Sender)
{
  BtnReal->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::FormShow(TObject *Sender)
{
  Action = actMain;  
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::actMainUpdate(TObject *Sender)
{
  bool vNotEmpty = !sgPaintBox->Empty();
  bool vMet;
  vMet = (vNotEmpty)&&(sgPaintBox->Picture->Graphic->InheritsFrom(__classid(TMetafile)));
  FImg = GetImg();
  MIPrint->Enabled = vNotEmpty;
  miSaveAs->Enabled = vNotEmpty;
  sb3DOrbit->Enabled = (vNotEmpty)&&(FImg);
  btnLayers->Enabled = (FImg);
  btnFitToScreen->Enabled = vNotEmpty;
  MiOEM->Enabled = (FImg);
  MIClose->Enabled = vNotEmpty;
  BtnSave->Enabled = vNotEmpty;
  BtnPrint->Enabled = vNotEmpty;
  BtnPrint1->Enabled = vNotEmpty;
  BtnPlus->Enabled = vNotEmpty;
  BtnMinus->Enabled = vNotEmpty;
  BtnReal->Enabled = vNotEmpty;
  BtnPrev->Enabled = vNotEmpty;
}
//---------------------------------------------------------------------------

/* TfmMain::SaveToDXF

  Saving in DXF format.                      */
void __fastcall TfmMain::SaveToDXF(AnsiString AFileName)
{
  TsgDXFExport * vExpMetafile;
  TsgCADtoDXF * vExpCADfile;
  TGraphic * vGr;

  vGr = sgPaintBox->Picture->Graphic;
  if (!vGr) return;
  if (vGr->InheritsFrom(__classid(TsgDXFImage)) ||
     vGr->InheritsFrom(__classid(TMetafile)))
  {
    if (!vGr->InheritsFrom(__classid(TsgDXFImage)))
    {
      vExpMetafile = new TsgDXFExport();
      try
      {
        vExpMetafile->Canvas->StretchDraw(Rect(0, 0, vGr->Width, vGr->Height), vGr);
        vExpMetafile->EndDraw();
        vExpMetafile->SaveToFile(AFileName);
      }
      __finally
      {
        delete vExpMetafile;
      }
    }
    else
    {
      vExpCADfile = new TsgCADtoDXF((TsgDXFImage *)vGr);
      try
      {
        vExpCADfile->SaveToFile(AFileName);
      }
      __finally
      {
        delete vExpCADfile;
      }
    }
    MessageBox(Application->Handle, "DXF Export is made via DXF Export VCL software which is not part of CAD Import VCL and should be bought additionally if needed.", "WARNING", MB_ICONWARNING);
  }
  else
    ShowMessage(sNotVectorial);
}
//---------------------------------------------------------------------------

