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

#include "Main.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)

#pragma resource "*.dfm"
TFormMain *FormMain;
//---------------------------------------------------------------------------
__fastcall TFormMain::TFormMain(TComponent* Owner)
  : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::SetDevices()
{
  ComboBoxCamera->Items->BeginUpdate();
  try
  {
    String CurrentDeviceName = ComboBoxCamera->Text;
    int CurrentDeviceIndex = ComboBoxCamera->ItemIndex;
    ComboBoxCamera->Items->Clear();
    TWVideoCaptureDevices Devices = WCamera->Devices;
    for (int i = 0; i < Devices.Length; ++i)
      ComboBoxCamera->Items->Add(Devices[i].Name);

    if ((CurrentDeviceIndex >= 0) && (CurrentDeviceIndex < ComboBoxCamera->Items->Count))
      if ((*ComboBoxCamera->Items)[CurrentDeviceIndex] == CurrentDeviceName)
      {
        ComboBoxCamera->ItemIndex = CurrentDeviceIndex;
        return;
      } 

    ComboBoxCamera->ItemIndex = ComboBoxCamera->Items->IndexOf(CurrentDeviceName);
  }
  __finally
  {
    ComboBoxCamera->Items->EndUpdate();
  }
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::SetFormats()
{
  ComboBoxFormat->Items->BeginUpdate();
  try
  {
    ButtonSaveCurrentImage->Enabled = false;
    WCamera->Active = false;
    WCamera->DeviceIndex = ComboBoxCamera->ItemIndex;
    ComboBoxFormat->Items->Clear();
    ComboBoxFormat->Enabled = WCamera->DeviceIndex != -1;
    if (ComboBoxFormat->Enabled)
    {
      TWCameraFormats Formats = WCamera->SupportedFormats;
      for (int i = 0; i < Formats.Length; ++i)
        if (Formats[i].AvgTimePerFrame == 0)
          ComboBoxFormat->Items->Add(IntToStr(Formats[i].Width) + "x" + IntToStr(Formats[i].Height) + " " + IntToStr(Formats[i].BitsPerPixel) + "bpp");
        else
          ComboBoxFormat->Items->Add(IntToStr(Formats[i].Width) + "x" + IntToStr(Formats[i].Height) + " " + IntToStr(10000000 / Formats[i].AvgTimePerFrame) + "Hz " + IntToStr(Formats[i].BitsPerPixel) + "bpp");
    }
  }
  __finally
  {
    ComboBoxFormat->Items->EndUpdate();
  }
}
//---------------------------------------------------------------------------
void __fastcall InitTrackBar(TLabel *TrackbarLabel, TTrackBar *TrackBar, TCheckBox *CheckBoxAuto)
{
  TrackbarLabel->Enabled = false;
  TrackBar->Enabled = false;
  CheckBoxAuto->Enabled = false;
}
//---------------------------------------------------------------------------
void __fastcall SetTrackBar(TLabel *TrackbarLabel, TTrackBar *TrackBar, TCheckBox *CheckBoxAuto, int Position, TWRange Range, bool Auto)
{
  CheckBoxAuto->Checked = Auto;
  TrackBar->Min = Range.Min;
  TrackBar->Max = Range.Max;
  TrackBar->PageSize = Range.Delta;
  if ((Range.Delta > 0) && ((Range.Max - Range.Min) / Range.Delta > 25))
    TrackBar->Frequency = (Range.Max - Range.Min) / 25;
  else
    TrackBar->Frequency = 1;
  TrackBar->Position = Position;

  TrackbarLabel->Enabled = true;
  CheckBoxAuto->Enabled = Range.Auto && Range.Manual;
  TrackBar->Enabled = !CheckBoxAuto->Checked;
}
//---------------------------------------------------------------------------
bool TrackBarsSetting;

void __fastcall TFormMain::SetTrackBars()
{
  if (!TrackBarsSetting)
  try
  {
    TrackBarsSetting = true;
    InitTrackBar(LabelBacklightCompensation, TrackBarBacklightCompensation, CheckBoxBacklightCompensation);
    InitTrackBar(LabelBrightness, TrackBarBrightness, CheckBoxBrightness);
    InitTrackBar(LabelColorEnable, TrackBarColorEnable, CheckBoxColorEnable);
    InitTrackBar(LabelContrast, TrackBarContrast, CheckBoxContrast);
    InitTrackBar(LabelExposure, TrackBarExposure, CheckBoxExposure);
    InitTrackBar(LabelFocus, TrackBarFocus, CheckBoxFocus);
    InitTrackBar(LabelGain, TrackBarGain, CheckBoxGain);
    InitTrackBar(LabelGamma, TrackBarGamma, CheckBoxGamma);
    InitTrackBar(LabelHue, TrackBarHue, CheckBoxHue);
    InitTrackBar(LabelIris, TrackBarIris, CheckBoxIris);
    InitTrackBar(LabelPan, TrackBarPan, CheckBoxPan);
    InitTrackBar(LabelRoll, TrackBarRoll, CheckBoxRoll);
    InitTrackBar(LabelSaturation, TrackBarSaturation, CheckBoxSaturation);
    InitTrackBar(LabelSharpness, TrackBarSharpness, CheckBoxSharpness);
    InitTrackBar(LabelTilt, TrackBarTilt, CheckBoxTilt);
    InitTrackBar(LabelWhiteBalance, TrackBarWhiteBalance, CheckBoxWhiteBalance);
    InitTrackBar(LabelZoom, TrackBarZoom, CheckBoxZoom);

    if (WCamera->DeviceIndex != -1)
    {
      if (WCamera->BacklightCompensationSupported)
        SetTrackBar(LabelBacklightCompensation, TrackBarBacklightCompensation, CheckBoxBacklightCompensation, WCamera->BacklightCompensation, WCamera->BacklightCompensationRange, WCamera->BacklightCompensationAuto);

      if (WCamera->BrightnessSupported)
        SetTrackBar(LabelBrightness, TrackBarBrightness, CheckBoxBrightness, WCamera->Brightness, WCamera->BrightnessRange, WCamera->BrightnessAuto);

      if (WCamera->ColorEnableSupported)
        SetTrackBar(LabelColorEnable, TrackBarColorEnable, CheckBoxColorEnable, WCamera->ColorEnable, WCamera->ColorEnableRange, WCamera->ColorEnableAuto);

      if (WCamera->ContrastSupported)
        SetTrackBar(LabelContrast, TrackBarContrast, CheckBoxContrast, WCamera->Contrast, WCamera->ContrastRange, WCamera->ContrastAuto);

      if (WCamera->ExposureSupported)
        SetTrackBar(LabelExposure, TrackBarExposure, CheckBoxExposure, WCamera->Exposure, WCamera->ExposureRange, WCamera->ExposureAuto);

      if (WCamera->FocusSupported)
        SetTrackBar(LabelFocus, TrackBarFocus, CheckBoxFocus, WCamera->Focus, WCamera->FocusRange, WCamera->FocusAuto);

      if (WCamera->GainSupported)
        SetTrackBar(LabelGain, TrackBarGain, CheckBoxGain, WCamera->Gain, WCamera->GainRange, WCamera->GainAuto);

      if (WCamera->GammaSupported)
        SetTrackBar(LabelGamma, TrackBarGamma, CheckBoxGamma, WCamera->Gamma, WCamera->GammaRange, WCamera->GammaAuto);

      if (WCamera->HueSupported)
        SetTrackBar(LabelHue, TrackBarHue, CheckBoxHue, WCamera->Hue, WCamera->HueRange, WCamera->HueAuto);

      if (WCamera->IrisSupported)
        SetTrackBar(LabelIris, TrackBarIris, CheckBoxIris, WCamera->Iris, WCamera->IrisRange, WCamera->IrisAuto);

      if (WCamera->PanSupported)
        SetTrackBar(LabelPan, TrackBarPan, CheckBoxPan, WCamera->Pan, WCamera->PanRange, WCamera->PanAuto);

      if (WCamera->RollSupported)
        SetTrackBar(LabelRoll, TrackBarRoll, CheckBoxRoll, WCamera->Roll, WCamera->RollRange, WCamera->RollAuto);

      if (WCamera->SaturationSupported)
        SetTrackBar(LabelSaturation, TrackBarSaturation, CheckBoxSaturation, WCamera->Saturation, WCamera->SaturationRange, WCamera->SaturationAuto);

      if (WCamera->SharpnessSupported)
        SetTrackBar(LabelSharpness, TrackBarSharpness, CheckBoxSharpness, WCamera->Sharpness, WCamera->SharpnessRange, WCamera->SharpnessAuto);

      if (WCamera->TiltSupported)
        SetTrackBar(LabelTilt, TrackBarTilt, CheckBoxTilt, WCamera->Tilt, WCamera->TiltRange, WCamera->TiltAuto);

      if (WCamera->WhiteBalanceSupported)
        SetTrackBar(LabelWhiteBalance, TrackBarWhiteBalance, CheckBoxWhiteBalance, WCamera->WhiteBalance, WCamera->WhiteBalanceRange, WCamera->WhiteBalanceAuto);

      if (WCamera->ZoomSupported)
        SetTrackBar(LabelZoom, TrackBarZoom, CheckBoxZoom, WCamera->Zoom, WCamera->ZoomRange, WCamera->ZoomAuto);
    }
  }
  __finally
  {
    TrackBarsSetting = false;
  }
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::StartDevice()
{
  SetTrackBars();
  if (ComboBoxFormat->ItemIndex != -1)
  {
    WCamera->Active = false;
    Format = WCamera->SupportedFormats[ComboBoxFormat->ItemIndex];
    WCamera->Format = Format;
    WCamera->Active = true;
    UpdateVideoPosition();
    WCamera->Run();
    PaintBox->Visible = WCamera->CaptureType == ctGrabber;
    ButtonSaveCurrentImage->Enabled = true;
  }
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::ComboBoxCameraDropDown(TObject *Sender)
{
  SetDevices();
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::ComboBoxCameraChange(TObject *Sender)
{
  SetFormats();
  SetTrackBars();
  ButtonDefaultValues->Enabled = WCamera->DeviceIndex != -1;
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::FormCreate(TObject *Sender)
{
  PanelCenter->DoubleBuffered = true;
  MemoryStream = new TMemoryStream();
  Bitmap = new TBitmap();
  SetTrackBars();
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::FormDestroy(TObject *Sender)
{
  WCamera->Active = false;
  delete Bitmap;
  delete MemoryStream;
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::ComboBoxFormatChange(TObject *Sender)
{
  StartDevice();
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::UpdateVideoPosition()
{
  if (WCamera->Active && (WCamera->CaptureType == ctVmr9))
  {
    if (CheckBoxStretch->Checked)
    {
      WCamera->AspectRatio = CheckBoxAspectRatio->Checked;
      WCamera->VideoPositionDest = PanelCenter->ClientRect;
    }
    else
    {
      TRect Rect;
      Rect.Left = (PanelCenter->Width - Format.Width) / 2;
      Rect.Top = (PanelCenter->Height - Format.Height) / 2;
      Rect.Right = Rect.Left + Format.Width;
      Rect.Bottom = Rect.Top + Format.Height;
      WCamera->VideoPositionDest = Rect;
    }
    PanelCenter->Invalidate();
  }
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::PanelCenterResize(TObject *Sender)
{
  UpdateVideoPosition();
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::CheckBoxClick(TObject *Sender)
{
  if (!TrackBarsSetting)
  {
    if (Sender == CheckBoxBacklightCompensation)
      WCamera->BacklightCompensationAuto = CheckBoxBacklightCompensation->Checked;
    else if (Sender == CheckBoxBrightness)
      WCamera->BrightnessAuto = CheckBoxBrightness->Checked;
    else if (Sender == CheckBoxColorEnable)
      WCamera->ColorEnableAuto = CheckBoxColorEnable->Checked;
    else if (Sender == CheckBoxContrast)
      WCamera->ContrastAuto = CheckBoxContrast->Checked;
    else if (Sender == CheckBoxExposure)
      WCamera->ExposureAuto = CheckBoxExposure->Checked;
    else if (Sender == CheckBoxFocus)
      WCamera->FocusAuto = CheckBoxFocus->Checked;
    else if (Sender == CheckBoxGain)
      WCamera->GainAuto = CheckBoxGain->Checked;
    else if (Sender == CheckBoxGamma)
      WCamera->GammaAuto = CheckBoxGamma->Checked;
    else if (Sender == CheckBoxHue)
      WCamera->HueAuto = CheckBoxHue->Checked;
    else if (Sender == CheckBoxIris)
      WCamera->IrisAuto = CheckBoxIris->Checked;
    else if (Sender == CheckBoxPan)
      WCamera->PanAuto = CheckBoxPan->Checked;
    else if (Sender == CheckBoxRoll)
      WCamera->RollAuto = CheckBoxRoll->Checked;
    else if (Sender == CheckBoxSaturation)
      WCamera->SaturationAuto = CheckBoxSaturation->Checked;
    else if (Sender == CheckBoxSharpness)
      WCamera->SharpnessAuto = CheckBoxSharpness->Checked;
    else if (Sender == CheckBoxTilt)
      WCamera->TiltAuto = CheckBoxTilt->Checked;
    else if (Sender == CheckBoxWhiteBalance)
      WCamera->WhiteBalanceAuto = CheckBoxWhiteBalance->Checked;
    else if (Sender == CheckBoxZoom)
      WCamera->ZoomAuto = CheckBoxZoom->Checked;
    SetTrackBars();
  }
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::TrackBarChange(TObject *Sender)
{
  if (!TrackBarsSetting)
    if (Sender == TrackBarBacklightCompensation)
      WCamera->BacklightCompensation = TrackBarBacklightCompensation->Position;
    else if (Sender == TrackBarBrightness)
      WCamera->Brightness = TrackBarBrightness->Position;
    else if (Sender == TrackBarColorEnable)
      WCamera->ColorEnable = TrackBarColorEnable->Position;
    else if (Sender == TrackBarContrast)
      WCamera->Contrast = TrackBarContrast->Position;
    else if (Sender == TrackBarExposure)
      WCamera->Exposure = TrackBarExposure->Position;
    else if (Sender == TrackBarFocus)
      WCamera->Focus = TrackBarFocus->Position;
    else if (Sender == TrackBarGain)
      WCamera->Gain = TrackBarGain->Position;
    else if (Sender == TrackBarGamma)
      WCamera->Gamma = TrackBarGamma->Position;
    else if (Sender == TrackBarHue)
      WCamera->Hue = TrackBarHue->Position;
    else if (Sender == TrackBarIris)
      WCamera->Iris = TrackBarIris->Position;
    else if (Sender == TrackBarPan)
      WCamera->Pan = TrackBarPan->Position;
    else if (Sender == TrackBarRoll)
      WCamera->Roll = TrackBarRoll->Position;
    else if (Sender == TrackBarSaturation)
      WCamera->Saturation = TrackBarSaturation->Position;
    else if (Sender == TrackBarSharpness)
      WCamera->Sharpness = TrackBarSharpness->Position;
    else if (Sender == TrackBarTilt)
      WCamera->Tilt = TrackBarTilt->Position;
    else if (Sender == TrackBarWhiteBalance)
      WCamera->WhiteBalance = TrackBarWhiteBalance->Position;
    else if (Sender == TrackBarZoom)
      WCamera->Zoom = TrackBarZoom->Position;
}
// ---------------------------------------------------------------------------
void __fastcall TFormMain::CheckBoxStretchClick(TObject *Sender)
{
  CheckBoxAspectRatio->Enabled = CheckBoxStretch->Checked;
  UpdateVideoPosition();
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::CheckBoxAspectRatioClick(TObject *Sender)
{
  UpdateVideoPosition();
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::ButtonSaveCurrentImageClick(TObject *Sender)
{
  if (WCamera->CurrentImageToFile("image.bmp") == ifJpeg)
    RenameFile("image.bmp", "image.jpg");
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::ButtonDefaultValuesClick(TObject *Sender)
{
  try
  {
    if (WCamera->BacklightCompensationSupported)
      WCamera->BacklightCompensation = WCamera->BacklightCompensationRange.Default;

    if (WCamera->BrightnessSupported)
      WCamera->Brightness = WCamera->BrightnessRange.Default;

    if (WCamera->ColorEnableSupported)
      WCamera->ColorEnable = WCamera->ColorEnableRange.Default;

    if (WCamera->ContrastSupported)
      WCamera->Contrast = WCamera->ContrastRange.Default;

    if (WCamera->ExposureSupported)
      WCamera->Exposure = WCamera->ExposureRange.Default;

    if (WCamera->FocusSupported)
      WCamera->Focus = WCamera->FocusRange.Default;

    if (WCamera->GainSupported)
      WCamera->Gain = WCamera->GainRange.Default;

    if (WCamera->GammaSupported)
      WCamera->Gamma = WCamera->GammaRange.Default;

    if (WCamera->HueSupported)
      WCamera->Hue = WCamera->HueRange.Default;

    if (WCamera->IrisSupported)
      WCamera->Iris = WCamera->IrisRange.Default;

    if (WCamera->PanSupported)
      WCamera->Pan = WCamera->PanRange.Default;

    if (WCamera->RollSupported)
      WCamera->Roll = WCamera->RollRange.Default;

    if (WCamera->SaturationSupported)
      WCamera->Saturation = WCamera->SaturationRange.Default;

    if (WCamera->SharpnessSupported)
      WCamera->Sharpness = WCamera->SharpnessRange.Default;

    if (WCamera->TiltSupported)
      WCamera->Tilt = WCamera->TiltRange.Default;

    if (WCamera->WhiteBalanceSupported)
      WCamera->WhiteBalance = WCamera->WhiteBalanceRange.Default;

    if (WCamera->ZoomSupported)
      WCamera->Zoom = WCamera->ZoomRange.Default;
  }
  __finally
  {
    SetTrackBars();
  }
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::ColorBoxBorderColorChange(TObject *Sender)
{
  PanelCenter->Color = ColorBoxBorderColor->Selected;
  if (WCamera->CaptureType == ctVmr9)
  {
    WCamera->BorderColor = ColorBoxBorderColor->Selected;
    if (WCamera->Active)
      StartDevice();
  }
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::WCameraImageAvailable(TObject *Sender, double SampleTime)
{
  PaintBox->Invalidate();
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::PaintBoxPaint(TObject *Sender)
{
  if (WCamera->Active && (WCamera->CaptureType == ctGrabber))
    try
    {
      if (!WCamera->CurrentImageToBitmap(Bitmap, MemoryStream))
        return;

      if (CheckBoxStretch->Checked)
      {
        TRect Rect;
        if (CheckBoxAspectRatio->Checked)
        {
          if (Bitmap->Width / Bitmap->Height >= PaintBox->Width / PaintBox->Height)
          {
            double AspectRatio = PaintBox->Width / Bitmap->Width;
            int Height = floor(AspectRatio * Bitmap->Height);
            Rect.Left = 0;
            Rect.Top = (PaintBox->Height - Height) / 2;
            Rect.Right = PaintBox->Width;
            Rect.Bottom = Rect.Top + Height;
          }
          else
          {
            double AspectRatio = PaintBox->Height / Bitmap->Height;
            int Width = floor(AspectRatio * Bitmap->Width);
            Rect.Left = (PaintBox->Width - Width) / 2;
            Rect.Top = 0;
            Rect.Right = Rect.Left + Width;
            Rect.Bottom = PaintBox->Height;
          }

          PaintBox->Canvas->StretchDraw(Rect,  Bitmap);
        }
        else
          Rect = PaintBox->ClientRect;

        PaintBox->Canvas->StretchDraw(Rect, Bitmap);
      }
      else
        PaintBox->Canvas->Draw(
          (PaintBox->Width - Bitmap->Width) / 2,
          (PaintBox->Height - Bitmap->Height) / 2,
          Bitmap);
    }
    catch (Exception &ex)
    {
    }
}
//---------------------------------------------------------------------------