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

#include "fMain.h"
#include "fLayers.h"
#include "fEntity.h"
#include "dstring.h"
#include <Dialogs.hpp>
#include <Classes.hpp>
#include <DXFImage.hpp>
#include <sgConsts.hpp>
#include <DXFConv.hpp>
#ifndef sgDXFONLY
#include <DWG.hpp>
#include <HPGL2.hpp>
#include <SVG.hpp>
#include <CGM.hpp>
#endif
#include <DXFExport.hpp>
#include <CADToDXF.hpp>
#include <Printers.hpp>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"

AnsiString sNotVectorial = "Raster drawings can not be saved to DXF format";
AnsiString sExportWarning = "DXF Export is made via DXF Export VCL software which is not part of CAD Import VCL and should be bought additionally if needed.";

TfmMain *fmMain;
char *FSaveToFile;

void AddEntity(TsgDXFConverter * AConverter, TsgDXFEntity * AEnt)
{
  AConverter->Sections[csEntities]->AddEntity(AEnt);
  if (AConverter->OnCreate)
    AConverter->OnCreate(AEnt);
  AConverter->Loads(AEnt);
}

//---------------------------------------------------------------------------
__fastcall TfmMain::TfmMain(TComponent* Owner)
  : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TfmMain::FormCreate(TObject *Sender)
{
  FsgPaintBox = new TSGDrawingNavigator(this);
  sgPaintBox->Parent = this;
  sgPaintBox->Align = alClient;
  sgPaintBox->RectZooming = true;
  sgPaintBox->ScalingOnMouseWheel = true;
  sgPaintBox->AutoFocus = true;
  sgPaintBox->OnMouseMove = sgPaintBoxMouseMove;
  FfmAddBmpDlg = NULL;
  OpenDialog->Filter = GraphicFilter(__classid(TGraphic));
  FLastAdded = NULL;
}
//---------------------------------------------------------------------------
void __fastcall TfmMain::btnOpenClick(TObject *Sender)
{
  if (OpenDialog->Execute())
  {
    sbrCoords->Panels->Items[0]->Text = "Please wait...";
    sgPaintBox->LoadFromFile(OpenDialog->FileName);
  }
  sbrCoords->Panels->Items[0]->Text = OpenDialog->FileName;
}
//---------------------------------------------------------------------------


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

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

void __fastcall TfmMain::btnNewClick(TObject *Sender)
{
  TsgDXFEntity *Ent = NULL;
  TsgDXFImage *Im;

  if (!sgPaintBox->Empty())
    if (sgPaintBox->Picture->Graphic->InheritsFrom(__classid(TsgDXFImage)))
    {
      Im = dynamic_cast<TsgDXFImage *>(sgPaintBox->Picture->Graphic);
      Ent = GetEntity(Im);
      if (Ent != NULL)
      {
        AddEntity(Im->Converter, Ent);
        Im->GetExtents();
        FLastAdded = Ent;
      }
      sgPaintBox->Refresh();
    }
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::btnDeleteClick(TObject *Sender)
{

  TsgDXFImage *Im;

  if ((!sgPaintBox->Empty())&&
     (sgPaintBox->Picture->Graphic->InheritsFrom(__classid(TsgDXFImage))))
  {
    Im = dynamic_cast<TsgDXFImage *>(sgPaintBox->Picture->Graphic);
    if (FLastAdded != NULL)
    {
      Im->Converter->DeleteEntity(FLastAdded, true);
      Im->GetExtents();
      FLastAdded = NULL;
      sgPaintBox->Refresh();
    }
  }
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::btnSaveToDXFClick(TObject *Sender)
{
  TsgDXFExport * vExpMetafile;
  TsgCADtoDXF * vExpCADfile;
  TGraphic * vGr = sgPaintBox->Picture->Graphic;
  if ((vGr)&&(vGr->InheritsFrom(__classid(TsgDXFImage)) || vGr->InheritsFrom(__classid(TMetafile))))
  {
    if (!(SaveDialog->Execute())) return;
    if (AnsiLowerCase(ExtractFileExt(SaveDialog->FileName)) != ".dxf")
      SaveDialog->FileName = SaveDialog->FileName + ".dxf";
    if (!vGr->InheritsFrom(__classid(TsgDXFImage)))
    {
      vExpMetafile = new TsgDXFExport();
      try
      {
        vExpMetafile->Canvas->StretchDraw(Rect(0, 0, vGr->Width, vGr->Height), vGr);
        vExpMetafile->EndDraw();
        vExpMetafile->SaveToFile(SaveDialog->FileName);
      }
      __finally
      {
        delete vExpMetafile;
      }
    }
    else
    {
      vExpCADfile = new TsgCADtoDXF((TsgDXFImage *)vGr);
      try
      {
        vExpCADfile->SaveToFile(SaveDialog->FileName);
      }
      __finally
      {
        delete vExpCADfile;
      }
    }
    MessageBox(Application->Handle, sExportWarning.c_str(), "WARNING", MB_ICONWARNING);
  }
  else
    ShowMessage(sNotVectorial);
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::sgPaintBoxMouseMove(TObject *Sender,
      TShiftState Shift, int X, int Y)
{
  TFPoint vPt;
  AnsiString S, vUnits;

  if ((!sgPaintBox->Empty())&&
      sgPaintBox->Picture->Graphic->InheritsFrom(__classid(TsgDXFImage)))
  {
    vPt = sgPaintBox->GetDrawingCoords(X, Y, vUnits);
    TVarRec v[] = {vPt.X, vPt.Y, vPt.Z};
    S = Format("%.3f; %.3f; %.3f", v, 2);
    S = S + " (" + vUnits + ")";
    sbrCoords->Panels->Items[1]->Text = S;
  }
}
//---------------------------------------------------------------------------

bool DirectExportEntity(TsgDXFExport *DXFExport, TsgDXFEntity *DXFEntity)
{
  if (DXFEntity->PaperSpace != 0)// this export made only for 'Model Space'
    return false;
  TdxfExportData Data;
  AnsiString ent_name = DXFEntity->EntName();
  AnsiString layer_name = DXFEntity->Layer->Name;
  if (layer_name == "0")
    DXFExport->CurrentLayer = NULL;
  else
    DXFExport->CurrentLayer = new TsgExpDXFLayer(layer_name);
  DXFExport->CurrentLayer->Color = ColorToDXF(DXFEntity->Layer->Pen->Color);
  memset(&Data, 0, sizeof(TdxfExportData));
  if (ent_name == "ARC") {
     TsgDXFArc *vArc = dynamic_cast<TsgDXFArc*>(DXFEntity);
     Data.Color = ColorToDXF(vArc->Pen->Color);
     Data.Point = vArc->Point;
     Data.Radius = vArc->Radius;
     Data.StartAngle = vArc->StartAngle;
     Data.EndAngle = vArc->EndAngle;
     DXFExport->AddArc(Data);
  }
  else if (ent_name == "CIRCLE") {
     TsgDXFCircle *vCircle = dynamic_cast<TsgDXFCircle*>(DXFEntity);
     Data.Color = ColorToDXF(vCircle->Pen->Color);
     Data.Point = vCircle->Point;
     Data.Radius = vCircle->Radius;
     DXFExport->AddCircle(Data);
  }
  else if (ent_name == "ELLIPSE") {
     TsgDXFEllipse *vEllipse = dynamic_cast<TsgDXFEllipse*>(DXFEntity);
     Data.Color = ColorToDXF(vEllipse->Pen->Color);
     Data.Point = vEllipse->Point;
     Data.Point1 = vEllipse->RadPt;
     Data.Radius = vEllipse->Ratio;
     Data.StartAngle = Radian(vEllipse->StartAngle);
     Data.EndAngle = Radian(vEllipse->EndAngle);
     Data.SelfType = atEllipse;
     DXFExport->AddArc(Data);
  }
  else if (StrPos(ent_name.c_str(), "INSERT") != NULL) {
    TsgDXFInsert *vInsert = dynamic_cast<TsgDXFInsert*>(DXFEntity);
    if (vInsert->Block != NULL)
    {
      Data.Text = vInsert->Block->Name;
      Data.Point = vInsert->Point;
      Data.Scale = vInsert->Scale;
      DXFExport->Insert(Data);
    }
  }
  else if (ent_name == "LINE") {
     TsgDXFLine *vLine = dynamic_cast<TsgDXFLine*>(DXFEntity);
     Data.Color = ColorToDXF(vLine->Pen->Color);
     Data.Thickness = vLine->GetThickness();
     Data.Point = vLine->Point;
     Data.Point1 = vLine->Point1;
     DXFExport->AddLine(Data);
  }
  else if (StrPos(ent_name.c_str(), "MTEXT") != NULL) {
     TsgDXFMText *vMText = dynamic_cast<TsgDXFMText*>(DXFEntity);
     Data.Color = ColorToDXF(vMText->Color);
     Data.Point = vMText->Point;
     Data.Point1 = vMText->Point1;
     Data.FHeight = vMText->Height;
     Data.Text = vMText->Text;
     DXFExport->AddMText(Data);
  }
  else if (StrPos(ent_name.c_str(), "TEXT") != NULL) {
     TsgDXFText *vText = dynamic_cast<TsgDXFText*>(DXFEntity);
     Data.Color = ColorToDXF(vText->Font->Color);
     Data.Point = vText->Point;
     Data.FHeight = vText->Height;
     Data.HAlign = vText->HAlign;
     Data.Rotation = vText->Rotation;
     Data.Text = vText->Text;
     DXFExport->AddText(Data);
  }
  else if ((ent_name == "POLYLINE") || (ent_name == "LWPOLYLINE")) {
    TsgDXFPolyline *vPolyline = dynamic_cast<TsgDXFPolyline*>(DXFEntity);
    TdxfPoint *pdxf_point, dxf_point;
    int i;
    Data.Color = ColorToDXF(vPolyline->Pen->Color);
    Data.Count = 1;
    Data.Points = new TList();
    Data.Points->Add(new TList());
    // Export vertexes without bulges and meshes
    for (i= 0; i< vPolyline->PolyPoints->Count; ++i)
    {
      pdxf_point = new TdxfPoint();
      TFPoint *p = (TFPoint*)(vPolyline->PolyPoints->Items[i]);
      pdxf_point->X = p->X;
      pdxf_point->Y = p->Y;
      pdxf_point->Z = p->Z;
      ((TList*) Data.Points->Items[0])->Add(pdxf_point);
    }
    DXFExport->AddPolyLine(Data, 0);
    // Lists have been copied to internal data
    for (i= 0; i< ((TList*) Data.Points->Items[0])->Count; ++i)
      delete (((TList*) Data.Points->Items[0])->Items[i]);
    delete ((TList*) Data.Points->Items[0]);
    delete Data.Points;
  }
  else if (ent_name == "SOLID") {
     TsgDXFSolid *vSolid = dynamic_cast<TsgDXFSolid*>(DXFEntity);
     Data.Color = ColorToDXF(vSolid->Pen->Color);
     Data.Point = vSolid->Point;
     Data.Point1 = vSolid->Point1;
     Data.Point2 = vSolid->Point2;
     Data.Point3 = vSolid->Point3;
     DXFExport->AddSolid(Data);
  }
  else if (ent_name == "SPLINE") {
    // Has not full realization in "DXFExport" for direct export
    // (it is possible with the big accuracy to export as Polyline)
  }
  else if (ent_name == "HATCH"){
    // Has not full realization in "DXFExport" for direct export
  }
  return true;
}

//---------------------------------------------------------------------------
void __fastcall TfmMain::btnDirectExportClick(TObject *Sender)
{
  if (!(SaveDialog->Execute())) return;
  if (AnsiLowerCase(ExtractFileExt(SaveDialog->FileName)) != ".dxf")
     SaveDialog->FileName = SaveDialog->FileName + ".dxf";

  TsgDXFImage *Img;
  TsgDXFExport *vDXF;
  TdxfExportData Data;
  TsgExpDXFLayer *vLayer;
  PdxfPoint Pt;
  int cnt, i, j;
  vDXF = new TsgDXFExport();
  try
  {
    Img = dynamic_cast<TsgDXFImage *>(sgPaintBox->Picture->Graphic);
    ////////////////////
    //LTYPES SECTION//
    ////////////////////
    float *Array = new float[20];
    memset(Array, 0, sizeof(float) * 20);
    cnt = Img->Converter->Counts[csLTypes];
    for (int i = 0; i < cnt; i++){
        AnsiString LTypeName = Img->Converter->LTypes[i]->Name;
        if ((LTypeName == "Continuous") || (LTypeName == "ByLayer") || (LTypeName == "ByBlock"))
          continue;
        //AnsiString LTypePatternLength = Img->Converter->LTypes[i]->Lines->PatternLength;
        int ticks_cnt = Img->Converter->LTypes[i]->Lines->Count();
        for (int j = 0; j < ticks_cnt; j++){
            Array[j] = Img->Converter->LTypes[i]->Lines->Ticks[j];
        }
        vDXF->AddLType(LTypeName, Array, ticks_cnt);
    }
    delete[] Array;

    ////////////////////
    //BLOCKS SECTION//
    ////////////////////
    cnt = Img->Converter->Counts[csBlocks];
    for (i = 0; i < cnt; i++){
        AnsiString BlockName = Img->Converter->Blocks[i]->Name;
        int ent_cnt = Img->Converter->Blocks[i]->Count;
        if (ent_cnt < 1)
          continue;
        vDXF->BeginBlock(BlockName);
        for (j = 0; j < ent_cnt; j++) {
            DirectExportEntity(vDXF, Img->Converter->Blocks[i]->Entities[j]);
        }
        vDXF->EndBlock();
    }
    ////////////////////
    //ENTITIES SECTION//
    ////////////////////
    cnt = Img->Converter->Counts[csEntities];
    for (i = 0; i < cnt; i++){
        DirectExportEntity(vDXF, Img->Converter->Entities[i]);
    }
    vDXF->SaveToFile(SaveDialog->FileName);
  }
  __finally
  {
    delete vDXF;
  }
  MessageBox(Application->Handle, sExportWarning.c_str(), "WARNING", MB_ICONWARNING);
}

//---------------------------------------------------------------------------
TsgDXFBlock* FindBlock(TsgDXFConverter *AConverter, const AnsiString AName)
{
  TsgDXFBlock *vBlock;
  for (int i=0; i< AConverter->Counts[csBlocks]; ++i)
  {
    vBlock = AConverter->Blocks[i];
    if (vBlock->Name != AName)
      continue;
    return vBlock;
  }
  return NULL;
}

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

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

void __fastcall TfmMain::mmiAboutClick(TObject *Sender)
{
  MessageBox(Handle, "DWG/DXF VCLs demo version \n Please contact www.cadsofttools.com to order a full version", "WARNING", MB_ICONWARNING);
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::btnShowLayersClick(TObject *Sender)
{
  TsgDXFImage *Im;
  if (!sgPaintBox->Empty())
    if (sgPaintBox->Picture->Graphic->InheritsFrom(__classid(TsgDXFImage)))
    {
      Im = dynamic_cast<TsgDXFImage *>(sgPaintBox->Picture->Graphic);
      LayersDialogExecute(Im, sgPaintBox);
    }
}
//---------------------------------------------------------------------------


void __fastcall TfmMain::BitBtnClick(TObject * Sender)
{
  TOpenDialog * OD;
  TEdit * Edit;

  OD = (TOpenDialog *)(((TButton *)(Sender))->Tag);
  if (OD->Execute())
  {
    Edit = (TEdit *)(OD->Tag);
    Edit->Text = OD->FileName;
    ((TBitBtn *)((TEdit *)(Edit->Tag)))->Enabled = FileExists(Edit->Text);
  }
}

bool __fastcall TfmMain::DialogBySetupParamsBitMap(AnsiString * AStr, TFPoint * APoint, TFPoint * AScale)
{
  TForm * FfmAddBmpDlg;
  TBitBtn * vBitBtn;
  TButton * vButton;
  TEdit * vEdit;
  TStaticText * vStatTexts[5];
  TEdit * vEditTexts[5];
  TOpenDialog * vOD;
  TGroupBox * vGBDir;
  TGroupBox * vGBPos;
  TGroupBox * vGBScale;
  bool Result = false;


  if (FfmAddBmpDlg)
  {
    FfmAddBmpDlg = new TForm(Application);
    FfmAddBmpDlg->Position = poScreenCenter;
    FfmAddBmpDlg->BorderStyle = bsToolWindow;
    FfmAddBmpDlg->BorderWidth = 8;
    FfmAddBmpDlg->Caption = "Initialize parametrs of BitMap";

    vGBDir = new TGroupBox(FfmAddBmpDlg);
    vGBDir->Parent = FfmAddBmpDlg;
    vGBDir->SetBounds(0, 0, 352, 48);
    vGBDir->Caption = " Path ";

    vEdit = new TEdit(vGBDir);
    vEdit->Parent = vGBDir;
    vEdit->AutoSize = false;
    vEdit->SetBounds(8, 16, 256, 24);
    vEdit->ReadOnly = true;
    vEdit->TabStop = false;

    vButton = new TButton(vGBDir);
    vButton->Parent = vGBDir;
    vButton->SetBounds(272, 16, 72, 24);
    vButton->Caption = "Open";
    vButton->OnClick = BitBtnClick;

    vGBPos = new TGroupBox(FfmAddBmpDlg);
    vGBPos->Parent = FfmAddBmpDlg;
    vGBPos->SetBounds(0, 56, 352, 104);
    vGBPos->Caption = " Position ";

    vStatTexts[0] = new TStaticText(vGBPos);
    vStatTexts[0]->Parent = vGBPos;
    vStatTexts[0]->SetBounds(8, 16, 16, 24);
    vStatTexts[0]->Caption = "X:";
    vEditTexts[0] = new TEdit(vGBPos);
    vEditTexts[0]->Parent = vGBPos;
    vEditTexts[0]->SetBounds(24, 16, 320, 24);
    vEditTexts[0]->AutoSize = false;
    vEditTexts[0]->Text = "0.0";

    vStatTexts[1] = new TStaticText(vGBPos);
    vStatTexts[1]->Parent = vGBPos;
    vStatTexts[1]->SetBounds(8, 44, 16, 24);
    vStatTexts[1]->Caption = "Y:";
    vEditTexts[1] = new TEdit(vGBPos);
    vEditTexts[1]->Parent = vGBPos;
    vEditTexts[1]->SetBounds(24, 44, 320, 24);
    vEditTexts[1]->AutoSize = false;
    vEditTexts[1]->Text = "0.0";

    vStatTexts[2] = new TStaticText(vGBPos);
    vStatTexts[2]->Parent = vGBPos;
    vStatTexts[2]->SetBounds(8, 72, 16, 24);
    vStatTexts[2]->Caption = "Z:";
    vEditTexts[2] = new TEdit(vGBPos);
    vEditTexts[2]->Parent = vGBPos;
    vEditTexts[2]->SetBounds(24, 72, 320, 24);
    vEditTexts[2]->AutoSize = false;
    vEditTexts[2]->Text = "0.0";

    vGBScale = new TGroupBox(FfmAddBmpDlg);
    vGBScale->Parent = FfmAddBmpDlg;
    vGBScale->SetBounds(0, 168, 352, 76);
    vGBScale->Caption = " Scale ";

    vStatTexts[3] = new TStaticText(vGBScale);
    vStatTexts[3]->Parent = vGBScale;
    vStatTexts[3]->SetBounds(8, 16, 16, 24);
    vStatTexts[3]->Caption = "X:";
    vEditTexts[3] = new TEdit(vGBScale);
    vEditTexts[3]->Parent = vGBScale;
    vEditTexts[3]->SetBounds(24, 16, 320, 24);
    vEditTexts[3]->AutoSize = false;
    vEditTexts[3]->Text = "1.0";

    vStatTexts[4] = new TStaticText(vGBScale);
    vStatTexts[4]->Parent = vGBScale;
    vStatTexts[4]->SetBounds(8, 44, 16, 24);
    vStatTexts[4]->Caption = "Y:";
    vEditTexts[4] = new TEdit(vGBScale);
    vEditTexts[4]->Parent = vGBScale;
    vEditTexts[4]->SetBounds(24, 44, 320, 24);
    vEditTexts[4]->AutoSize = false;
    vEditTexts[4]->Text = "1.0";

    vBitBtn = new TBitBtn(FfmAddBmpDlg);
    vBitBtn->Parent = FfmAddBmpDlg;
    vBitBtn->SetBounds(272, 257, 72, 24);
    vBitBtn->Kind = bkOK;
    vBitBtn->Enabled = false;

    vOD = new TOpenDialog(FfmAddBmpDlg);
    vOD->Filter = "BitMap | *.bmp";

    vButton->Tag = (int)((void *)(vOD));
    vOD->Tag = (int)((void *)(vEdit));
    vEdit->Tag = (int)((void *)(vBitBtn));

    FfmAddBmpDlg->AutoSize = true;
  }
  Result = FfmAddBmpDlg->ShowModal() == mrOk;

  if (Result)
  {
    *AStr = vEdit->Text;
    APoint->X = ConvToFloatDef(vEditTexts[0]->Text, 0.0);
    APoint->Y = ConvToFloatDef(vEditTexts[1]->Text, 0.0);
    APoint->Z = ConvToFloatDef(vEditTexts[2]->Text, 0.0);
    AScale->X = ConvToFloatDef(vEditTexts[3]->Text, 1.0);
    AScale->Y = ConvToFloatDef(vEditTexts[4]->Text, 1.0);
    AScale->Z = 1;
  }
  return Result;
}

void __fastcall TfmMain::mmiAddBitmapClick(TObject *Sender)
{
  TsgDXFImage * Im;

  AnsiString vStr;
  TFPoint vPoint, vScale;
  Graphics::TBitmap * vBitMap;
  TsgDXFImageEnt * vImageEnt = NULL;

  if (sgPaintBox->Picture->Graphic->InheritsFrom(__classid(TsgDXFImage)))
  {
    if (DialogBySetupParamsBitMap(&vStr, &vPoint, &vScale))
    {
      vBitMap = new Graphics::TBitmap;
      try
      {
        vBitMap->LoadFromFile(vStr);
        try
        {
          vImageEnt = new TsgDXFImageEnt();
          vImageEnt->Point = vPoint;
          vImageEnt->Point1 = MakeFPoint(vBitMap->Width, 0, 0);
          vImageEnt->Point2 = MakeFPoint(0, vBitMap->Height, 0);
          vImageEnt->Point3 = vScale;
          vImageEnt->SetImage(vBitMap);
        }
        __finally
        {
          delete vBitMap;
        }
      }
      catch (Exception &exception)
      {
        delete vBitMap;
      }
    }
    Im = dynamic_cast<TsgDXFImage *>(sgPaintBox->Picture->Graphic);

    if (vImageEnt)
    {
      AddEntity(Im->Converter, (TsgDXFEntity *)vImageEnt);
      Im->GetExtents();
      Im->RefreshCurrentLayout();
      FLastAdded = vImageEnt;
    }
  }
}

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

void __fastcall TfmMain::mmiAssignTsgDXFLineClick(TObject *Sender)
{
  TsgDXFImage * vImg;
  TsgDXFEntity * vEnt;
  TsgDXFLine * vNewEnt;
  int I, vCnt;

  vImg = dynamic_cast<TsgDXFImage *>(sgPaintBox->Picture->Graphic);
  if (vImg)
  {
    vCnt =  vImg->Converter->Counts[csEntities];
    I = 0;
    while (I < vCnt)
    {
      vEnt = vImg->Converter->Sections[csEntities]->Entities[I];
      if (vEnt->ClassType() == __classid(TsgDXFLine))
      {
        vNewEnt = new TsgDXFLine();
        vNewEnt->AssignEntity(vEnt);
        vImg->Converter->DeleteEntity(vEnt, true);
        vCnt--;
        vNewEnt->SetColor(clRed);
        AddEntity(vImg->Converter, vNewEnt);
      }
      else
        I++;
    }
    sgPaintBox->Refresh();
  }
}
//---------------------------------------------------------------------------
void __fastcall TfmMain::mmiAssignTsgDXFSplineClick(TObject *Sender)
{
  TsgDXFImage * vImg;
  TsgDXFEntity * vEnt;
  TsgDXFSpline * vNewEnt;
  int I, vCnt;

  vImg = dynamic_cast<TsgDXFImage *>(sgPaintBox->Picture->Graphic);
  if (vImg)
  {
    vCnt =  vImg->Converter->Counts[csEntities];
    I = 0;
    while (I < vCnt)
    {
      vEnt = vImg->Converter->Sections[csEntities]->Entities[I];
      if (vEnt->ClassType() == __classid(TsgDXFSpline))
      {
        vNewEnt = new TsgDXFSpline();
        vNewEnt->AssignEntity(vEnt);
        vImg->Converter->DeleteEntity(vEnt, true);
        vCnt--;
        vNewEnt->SetColor(clRed);
        AddEntity(vImg->Converter, vNewEnt);
      }
      else
        I++;
    }
    sgPaintBox->Refresh();
  }
}
//---------------------------------------------------------------------------
void __fastcall TfmMain::mmiAssignTsgDXFTextClick(TObject *Sender)
{
  TsgDXFImage * vImg;
  TsgDXFEntity * vEnt;
  TsgDXFText * vNewEnt;
  int I, vCnt;

  vImg = dynamic_cast<TsgDXFImage *>(sgPaintBox->Picture->Graphic);
  if (vImg)
  {
    vCnt =  vImg->Converter->Counts[csEntities];
    I = 0;
    while (I < vCnt)
    {
      vEnt = vImg->Converter->Sections[csEntities]->Entities[I];
      if (vEnt->ClassType() == __classid(TsgDXFText))
      {
        vNewEnt = new TsgDXFText();
        vNewEnt->AssignEntity(vEnt);
        vImg->Converter->DeleteEntity(vEnt, true);
        vCnt--;
        vNewEnt->SetColor(clRed);
        AddEntity(vImg->Converter, vNewEnt);
      }
      else
        I++;
    }
    sgPaintBox->Refresh();
  }
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::mmiPrintClick(TObject *Sender)
{
  double W, H;
  int PW, PH;
  int vStoredNullWidth;
  TsgDXFImage * Im = dynamic_cast<TsgDXFImage *>(sgPaintBox->Picture->Graphic);

  if (sgPaintBox->Picture->Width > sgPaintBox->Picture->Height)
    Printer()->Orientation = poLandscape;
  else
    Printer()->Orientation = poPortrait;
  if (PrintDialog->Execute())
  {
    if (Im)
    {
      vStoredNullWidth = Im->NullWidth;
      Im->NullWidth = 3;
    }
    W = Printer()->PageWidth / sgPaintBox->Picture->Width;
    H = Printer()->PageHeight / sgPaintBox->Picture->Height;
    if (W > H) W = H;
    PW = W * sgPaintBox->Picture->Width;
    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();
    if (Im) Im->NullWidth = vStoredNullWidth;
    sgPaintBox->Repaint();
  }
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::mmiAssignAllClick(TObject *Sender)
{
  TsgDXFImage * vImg = dynamic_cast<TsgDXFImage *>(sgPaintBox->Picture->Graphic);
  TsgDXFEntity * vNewEnt;
  TsgDXFEntity * vEnt;
  int I, vCnt;

  try
  {
    if (vImg)
    {
      vCnt = vImg->Converter->Counts[csEntities];
      for(I = 0; I < vCnt; I++)
      {
        vEnt = vImg->Converter->Sections[csEntities]->Entities[I];
        vNewEnt = vImg->Converter->NewEntity(NULL, vEnt->ClassType());
        if (vNewEnt)
        {
          vNewEnt->AssignEntity(vEnt);
          vImg->Converter->DeleteEntity(vEnt, true);
          vNewEnt->SetColor(clRed);
          AddEntity(vImg->Converter, vNewEnt);
        }
      }
      sgPaintBox->Refresh();
    }
  }
  catch (Exception &exception)
  {
    ShowMessage("This file contains entities for which AssignEntity will be implemented in future verions of CADImportVCL");
    sgPaintBox->Refresh();
  }
}
//---------------------------------------------------------------------------

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

void __fastcall TfmMain::actMainUpdate(TObject *Sender)
{
  bool vNotEmpty = !sgPaintBox->Empty();
  bool vCAD = (vNotEmpty)&&(sgPaintBox->Picture->Graphic->InheritsFrom(__classid(TsgDXFImage)));
  bool vMet = (vNotEmpty)&&(sgPaintBox->Picture->Graphic->InheritsFrom(__classid(TMetafile)));
  btnSaveToDXF->Enabled = vNotEmpty;
  btnDirectExport->Enabled = vCAD;
  btnPrint->Enabled = vNotEmpty;
  btnZoomIn->Enabled = vNotEmpty;
  btnZoomOut->Enabled = vNotEmpty;
  btnFitToWindow->Enabled = vNotEmpty;
  btnNew->Enabled = vCAD;
  btnDelete->Enabled = vCAD&&(FLastAdded);
  btnShowLayers->Enabled = vCAD;
  mmiSaveDXF->Enabled = vCAD || vMet;
  mmiExportToDXF->Enabled = vCAD;
  mmiPrint->Enabled = vNotEmpty;
  mmiAddNew->Enabled = vCAD;
  mmiAddBitmap->Enabled = vCAD;
  mmiAssignTsgDXFLine->Enabled = vCAD;
  mmiAssignTsgDXFSpline->Enabled = vCAD;
  mmiAssignTsgDXFText->Enabled = vCAD;
  mmiAssignAll->Enabled = vCAD;
  mmiDelLast->Enabled = vCAD;
  mmiZoomIn->Enabled = vNotEmpty;
  mmiZoomOut->Enabled = vNotEmpty;
  mmiZoomOut->Enabled = vNotEmpty;
  mmiFitToWindow->Enabled = vNotEmpty;
  mmiClosePicture->Enabled = vNotEmpty;
}
//---------------------------------------------------------------------------

void __fastcall TfmMain::mmiClosePictureClick(TObject *Sender)
{
  sgPaintBox->Picture->Graphic = NULL;
}
//---------------------------------------------------------------------------

