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

#include <vcl.h>
#include <assert.h>
#include <mmsystem.h>
#include <digitalv.h>
#include <Jpeg.hpp>
#pragma hdrstop

#include "UnitMain.h"
#include "UnitVideo.h"
#include "UnitSelectFolder.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TFormMain *FormMain;

typedef enum{
    INTERVAL_0=0,
    INTERVAL_1,
    INTERVAL_2,
    INTERVAL_5,
    INTERVAL_10
}BROWSE_INTERVAL_TYPE;

typedef enum{
    RES_1920_1080=0,
    RES_1680_1050,
    RES_1280_1024,
    RES_1024_768,
    RES_800_600,
    RES_800_480,
    RES_640_480,
}RES_TYPE;

#define MYWM_LOAD   (WM_USER + 1)

//---------------------------------------------------------------------------
//主表构造函数
__fastcall TFormMain::TFormMain(TComponent* Owner)
    : TForm(Owner),
    m_bPlaying(false),
    m_pDirectShow(NULL),
    m_pFormVideo(NULL),
    m_pFormDisplay(NULL),
    m_bDownloadImage(false),
    m_bPlayFolder(false)
{
    m_strBrowseFolder = ::ExtractFilePath(Application->ExeName) + "Images";
    m_strFileFolder = m_strBrowseFolder;

    m_pBitmap = new Graphics::TBitmap;
    m_pBitmap->PixelFormat = pf24bit;  //assign the bitmap type
    m_pBitmap->Width = 800;
    m_pBitmap->Height = 600;

    m_pFileBitmap = new Graphics::TBitmap;
    m_pFileBitmap->Width = 800;
    m_pFileBitmap->Height = 600;

}

//主表解析函数
__fastcall TFormMain::~TFormMain()
{
    //TODO: Add your source code here
    if (m_pBitmap)
        delete m_pBitmap;
    FreeDirectShow();
    if (m_pFormDisplay)
        delete m_pFormDisplay;
    if (m_pFileList)
        delete m_pFileList;        
}
//---------------------------------------------------------------------------
// ComboBoxPatternType list 'ComboBoxPatternTypeChange' event
void __fastcall TFormMain::ComboBoxPatternTypeChange(TObject *Sender){

    PATTERN_TYPE PatternType;
    PanelVideoControl->Visible = false;
    TimerVideo->Enabled = false;
    m_bPlayFolder = false;
    PatternType = UIGetPatternType();
    if (PatternType == PATTERN_FOLDER){//ComboBoxPatternType->Items->Count-1){
        AnsiString strFolderName;
        SetCurrentDirectory(m_strBrowseFolder.c_str());
        TFormSelectFolder *pDiloag;
        pDiloag = new TFormSelectFolder(this);
        if (pDiloag->ShowModal() == mrOk){
            strFolderName = pDiloag->DirectoryListBox->Directory;
            m_strBrowseFolder = strFolderName;
        }
        delete pDiloag;
        //
        bool bEnableBrowse = false;
        if (!strFolderName.IsEmpty()){
            int iAttributes = faArchive;
            TSearchRec SearchRec;
            AnsiString strSearch;
            strSearch = strFolderName + "\\*.*";
            m_pFileList->Clear();
            if (FindFirst(strSearch.c_str(), iAttributes, SearchRec) == 0){
                do
                {
                    if ((SearchRec.Attr & iAttributes) == SearchRec.Attr)
                      {
                        AnsiString strExtName;
                        strExtName = ::ExtractFileExt(SearchRec.Name).UpperCase();
                        if (strExtName == ".JPG" || strExtName == ".BMP" || strExtName == ".JPEG")
                            m_pFileList->Add(strFolderName + "\\" + SearchRec.Name);
                      }
                } while (FindNext(SearchRec) == 0);
                FindClose(SearchRec);
                if (m_pFileList->Count){
                    bEnableBrowse = true;
                    m_nBrowseIndex = 0;
                    m_nPrePatternType = PatternType;
                    FreeDirectShow();
                    PaintBoxDisplay->Visible = true;
                    m_bPlayFolder = true;
                }else{
                    MessageDlg("Cannot find any bmp/jpg file in the folder.", mtError, TMsgDlgButtons() << mbOK, 0);
                }
            }else{
                MessageDlg("Cannot find any bmp/jpg file in the folder.", mtError, TMsgDlgButtons() << mbOK, 0);
            }
        }
        //
        if (!bEnableBrowse){
            //ComboBoxPatternType->ItemIndex = m_nPrePatternType;
            UISetPatternType(m_nPrePatternType);
        }else{
            m_nPrePatternType = PatternType; //ComboBoxPatternType->ItemIndex;
            FreeDirectShow();
            PanelBrowse->Visible = true;
            PaintBoxDisplay->Visible = true;
            BrowseImage();
            TimerBrowse->Interval = GetInterval();
            TimerBrowse->Enabled = true;
            return;
        }

    }else if (PatternType == PATTERN_FILE){//ComboBoxPatternType->Items->Count-1){
        OpenDialog->InitialDir = m_strFileFolder; //::ExtractFilePath(Application->ExeName);
        if (OpenDialog->Execute()){
//            FormVideo->Visible = false;
            AnsiString strName = OpenDialog->FileName;
            AnsiString strExt = ::ExtractFileExt(strName).UpperCase();
            m_strFileFolder = ::ExtractFilePath(strName);
            if (strExt == ".BMP" || strExt == ".JPEG" || strExt == ".JPG"){
                bool bTimerEnable;
                bTimerEnable = TimerBrowse->Enabled;
                TimerBrowse->Enabled = false;
                if (LoadImage(strName)){
                    m_nPrePatternType = PatternType;//ComboBoxPatternType->ItemIndex;
                    FreeDirectShow();
                    PaintBoxDisplay->Visible = true;
                    PanelBrowse->Visible = false;
                    if (m_bPlaying)
                        m_bDownloadImage = true;
                }else{
                    TimerBrowse->Enabled = bTimerEnable;
                }
            }else if (strExt == ".WMV" || strExt == ".MPG" || strExt == ".AVI"  || strExt == ".RMVB"  || strExt == ".MOV"){
                if (!m_pDirectShow)
                    m_pDirectShow = new TDirectShow;
                if (!m_pFormVideo)
                    m_pFormVideo = new TFormVideo(this);
                m_pFormVideo->Parent = this;
                if (m_pDirectShow->New(m_pFormVideo->Handle)){//::GetDesktopWindow())){
                    PanelVideoControl->Visible = true;
            //    if (m_pDirectShow->New(Handle)){//::GetDesktopWindow())){
                    int nVideoWidth, nVideoHeight;
                    m_pDirectShow->CloseFile();
                    bool bSuccess = m_pDirectShow->OpenFile(strName.c_str(), &nVideoWidth, &nVideoHeight);
                    if (bSuccess){
                        m_nPrePatternType = PatternType;//ComboBoxPatternType->ItemIndex;
                        TimerBrowse->Enabled = false;
                        PanelBrowse->Visible = false;
                        PaintBoxDisplay->Visible = false;
                        m_VideoInfo.nWidth = nVideoWidth;
                        m_VideoInfo.nHeight = nVideoHeight;
                        m_VideoInfo.bCanStep = m_pDirectShow->CanStep();
                        m_VideoInfo.dwDur = m_pDirectShow->GetDuration();
                        TrackBarPlayer->Max = m_VideoInfo.dwDur;
                        TrackBarPlayer->Min = 0;
                        TrackBarPlayer->Frequency = m_VideoInfo.dwDur / 20;
                        TrackBarPlayer->Position = 0;

                        //
                        AnsiString strInfo;
                        strInfo.sprintf("Original Image Resolution: %d x %d pixels", nVideoWidth, nVideoHeight);
                        UIShowImageInfo(strInfo.c_str(), clBlue);
#if 1
                        m_pFormVideo->OnPaint = OnPaint;
                        FormResize(this);
#else
                        m_nVideoWidth = nVideoWidth;
                        m_nVideoHeight = nVideoHeight;
                        TRect rc;
                        rc = CalDisplayRect(nVideoWidth, nVideoHeight);
                        m_pFormVideo->SetBounds(rc.left, rc.top, rc.Width(), rc.Height());
                        m_pFormVideo->OnPaint = OnPaint;
                        //
                        ::OffsetRect(&rc, -rc.left, -rc.top);
                        m_pDirectShow->SetDisplayRect(rc);
#endif
                        m_pFormVideo->Visible = true;
                    //    m_pDirectShow->Pause(); // start play it

                    //    m_VideoInfo.bPlaying = true;
                        m_VideoInfo.bStop = true;
                     //   UIPlayerUpdate();
                     //   TimerVideo->Enabled = true;
                    }else{
                        FreeDirectShow();
                        MessageDlg("Failed to open media file.", mtError, TMsgDlgButtons() << mbOK, 0);
                    }
                }else{
                    FreeDirectShow();
                    MessageDlg("Failed to init DirectX.", mtError, TMsgDlgButtons() << mbOK, 0);
                    //ComboBoxPatternType->ItemIndex = m_nPrePatternType;
                    UISetPatternType(m_nPrePatternType);
                }
            }else{
                MessageDlg("Unsupported file format", mtError, TMsgDlgButtons() << mbOK, 0);
//                ComboBoxPatternType->ItemIndex = m_nPrePatternType;
                UISetPatternType(m_nPrePatternType);
            }
            //::UpdateWindow(Handle);
            if (!m_pDirectShow)
                UIRedrawImage();
        }else{
//            ComboBoxPatternType->ItemIndex = m_nPrePatternType;
            UISetPatternType(m_nPrePatternType);
        }
        return;
    }else{
        m_nPrePatternType = PatternType;
    }
//    m_nPrePatternType = ComboBoxPatternType->ItemIndex;
    UISetPatternType(m_nPrePatternType);
    TimerBrowse->Enabled = false;
    FreeDirectShow();
    PanelBrowse->Visible = false;
    PaintBoxDisplay->Visible = true;

//    UpdateBitmapContent();
//    UIRedrawImage();
    if (m_bPlaying && !m_pDirectShow)
        m_bDownloadImage = true;
}
//---------------------------------------------------------------------------
// ComboBoxRes list 'ComboBoxResChange' event
void __fastcall TFormMain::ComboBoxResChange(TObject *Sender)
{
    int nWidth;// = 800;
    int nHeight;// = 600;
    RES_TYPE ResType = (RES_TYPE)ComboBoxRes->ItemIndex;
    switch(ResType){  //only one kind of resolution   PHILIP_DEMO only
        case RES_1920_1080: nWidth = 640; nHeight = 480; break;
        case RES_1680_1050: nWidth = 640; nHeight = 480; break;
        case RES_1280_1024: nWidth = 640; nHeight = 480; break;
        case RES_1024_768: nWidth = 640; nHeight = 480; break;
        case RES_800_600: nWidth = 640; nHeight = 480; break;
        case RES_800_480: nWidth = 640; nHeight = 480; break;
        case RES_640_480: nWidth = 640; nHeight = 480; break;
        default:
            assert(0);
    }

#ifdef PHILIP_DEMO
    if (ResType != RES_640_480){
        MessageDlg("This demo only support resolution 640x480", mtError, TMsgDlgButtons() << mbOK, 0);
        ComboBoxRes->ItemIndex = RES_640_480;
        return;
    }
#endif

    m_pBitmap->Width = nWidth;
    m_pBitmap->Height = nHeight;

    UpdateBitmapContent();
    PaintBoxDisplayPaint(this);

}
//---------------------------------------------------------------------------
//start upload data to PC from FPGA board via PCIe
void __fastcall TFormMain::UpdateBitmapContent(void)
{
    //TODO: Add your source code here
     if(DownloadImage());
     PrepareDownloadData();
}

void __fastcall TFormMain::WndProc(Messages::TMessage &Message){

    TForm::WndProc(Message);
}

void __fastcall TFormMain::FormShow(TObject *Sender)
{
    // Timer interval (not used)
    ComboBoxInterval->Clear();
    ComboBoxInterval->Items->Add("Continued");
    ComboBoxInterval->Items->Add("1 seconds");
    ComboBoxInterval->Items->Add("2 seconds");
    ComboBoxInterval->Items->Add("5 seconds");
    ComboBoxInterval->Items->Add("10 seconds");
    ComboBoxInterval->ItemIndex = INTERVAL_5;
    PanelBrowse->Left = PanelVideoControl->Left;
    //
    ComboBoxRes->Clear();
    //resolution
    ComboBoxRes->Items->Add("CLR:640x480");
    ComboBoxRes->Items->Add("1920 x 1080(Full HD)");
    ComboBoxRes->Items->Add("1680 x 1050");
    ComboBoxRes->Items->Add("1280 x 1024");
    ComboBoxRes->Items->Add("1024 x 768");
    ComboBoxRes->Items->Add("800 x 600");
    ComboBoxRes->Items->Add("800 x 480");

#ifdef PHILIP_DEMO
    ComboBoxRes->ItemIndex = RES_640_480;
#else
    ComboBoxRes->ItemIndex = RES_1920_1080;
#endif

    //
    ComboBoxResChange(this);
    //
    UIRefresh();
}
//---------------------------------------------------------------------------
//rearrange the status bar for 3 spaces
void __fastcall TFormMain::StatusBarDrawPanel(TStatusBar *StatusBar,
      TStatusPanel *Panel, const TRect &Rect)
{
        TPoint pt;
        pt.x = Rect.left+2;
        pt.y = Rect.top;
        if (Panel == StatusBar->Panels->Items[0]){
            StatusBar->Canvas->Font->Color = m_PanelColor[0];
            StatusBar->Canvas->TextOut(pt.x, pt.y, Panel->Text);
        }else if (Panel == StatusBar->Panels->Items[1]){
            StatusBar->Canvas->Font->Color = m_PanelColor[1];
            StatusBar->Canvas->TextOut(pt.x, pt.y, Panel->Text);
        }else if (Panel == StatusBar->Panels->Items[2]){
            StatusBar->Canvas->Font->Color = m_PanelColor[2];
            StatusBar->Canvas->TextOut(pt.x, pt.y, Panel->Text);
        }

}
//---------------------------------------------------------------------------
//space 1 for datarate
void __fastcall TFormMain::UIShowStatus(AnsiString strText, TColor color){
    StatusBar->Panels->Items[0]->Text = strText;
    m_PanelColor[0] = color;
    StatusBar->Repaint();
}
//space 2 for upload status
void __fastcall TFormMain::UIShowInfo(AnsiString strText, TColor color){
    StatusBar->Panels->Items[1]->Text = strText;
    m_PanelColor[1] = color;
    StatusBar->Repaint();
}
//space 3 reserve
void __fastcall TFormMain::UIShowImageInfo(AnsiString strText, TColor color){
    StatusBar->Panels->Items[2]->Text = strText;
    m_PanelColor[1] = color;
    StatusBar->Repaint();
}



//---------------------------------------------------------------------------
//play or stop control
void __fastcall TFormMain::ButtonPlayClick(TObject *Sender)
{
 if(ButtonPlay->Caption == "Play")
 {
   ButtonPlay->Caption = "Stop";
   TimerVideo->Enabled = true;
 }
 else
 {
   ButtonPlay->Caption = "Play";
   TimerVideo->Enabled = false;
 }

}
//---------------------------------------------------------------------------

//download image data to PC, get the data transfer status and rate
bool __fastcall TFormMain::DownloadImage(void)
{
    //TODO: Add your source code here
    if (m_pFormDisplay){
        TRect rc = m_pFormDisplay->ClientRect;
        m_pFormDisplay->Canvas->StretchDraw(rc, m_pBitmap);
        return true;
    }
    // download from FPGA card
    bool bSuccess = true;
    if (m_DataDownload.IsFull()){
        UIShowInfo("FPGA Buffer Full", clRed);
    }else{
        UIShowInfo("Uploading...", clBlue);
        DWORD dwStartTime = ::GetTickCount();
        bSuccess =  m_DataDownload.Download();
        if (bSuccess){
            DWORD dwTimeElapsed = ::GetTickCount() - dwStartTime;
            if (dwTimeElapsed)
                m_fDataRate = (float)m_DataDownload.DataSize() / (float)dwTimeElapsed * 1000.0;
            AnsiString m_fDataRatechar = FloatToStrF(m_fDataRate*8,ffFixed,5,4);
            UIShowStatus(m_fDataRatechar.Insert(  "bps",15 ), clBlue) ;
            UIShowInfo("Upload Success", clGreen);
        }else{
            UIShowInfo("Failed to upload Success", clRed);
        }
    }
    return bSuccess;
}

void __fastcall TFormMain::UIRefresh(void)
{
    //TODO: Add your source code here
//    ButtonPlay->Enabled = (m_pBitmap && m_DataDownload.IsReady())?true:false;
}

void __fastcall TFormMain::FormPaint(TObject *Sender)
{
    UIDrawImage();
}
//---------------------------------------------------------------------------

void __fastcall TFormMain::FormResize(TObject *Sender)
{
    ButtonPlay->Left = Width - ButtonPlay->Width - 30;

    if (!m_pDirectShow){
        UIRedrawImage();
    }else{
        TRect rc;
        //rc = CalDisplayRect(m_nVideoWidth, m_nVideoHeight);
        rc = CalDisplayRect(m_pBitmap->Width, m_pBitmap->Height);
        m_pFormVideo->SetBounds(rc.left, rc.top, rc.Width(), rc.Height());
        //
        ::OffsetRect(&rc, -rc.left, -rc.top);
        m_pDirectShow->SetDisplayRect(rc);

        // Resize player windows
        PanelVideoControl->Width = ButtonPlay->Left - PanelVideoControl->Left - 20;
        TrackBarPlayer->Width = PanelVideoControl->Width - TrackBarPlayer->Left - 10;
    }
    //
    TRect rc = ClientRect;
    StatusBar->Panels->Items[2]->Width = 240;
    StatusBar->Panels->Items[0]->Width = (rc.Width() - StatusBar->Panels->Items[2]->Width)/2;
    StatusBar->Panels->Items[1]->Width = StatusBar->Panels->Items[0]->Width;

}
//---------------------------------------------------------------------------


void __fastcall TFormMain::FreeDirectShow(void)
{
    //TODO: Add your source code here
    if (m_pDirectShow){
        m_pDirectShow->Stop();
        m_pDirectShow->CloseFile();
        m_pDirectShow->Delete();
        delete m_pDirectShow;
        m_pDirectShow = NULL;
    }
    if (m_pFormVideo){
        delete m_pFormVideo;
        m_pFormVideo = NULL;
    }
}

TRect __fastcall TFormMain::CalDisplayRect(int nImageWidth, int nImageHeight)
{
    //TODO: Add your source code here
    TRect rc = PanelDisplay->ClientRect;
    ::InflateRect(&rc, -10, -10);
    if (rc.Width()*nImageHeight > nImageWidth*rc.Height()){
        // displayer is wider
        int nInfalte =  nImageWidth*rc.Height()/nImageHeight - rc.Width();
        ::InflateRect(&rc, nInfalte/2, 0);
    }else{
        // displayer is higher
        int nInfalte =  rc.Width()*nImageHeight/nImageWidth - rc.Height();
        ::InflateRect(&rc, 0, nInfalte/2);
    }
    return rc;
}
//fetch the data from the FPGA board
void __fastcall TFormMain::PrepareDownloadData(void)
{

    DWORD dwDataSize, dwBytesPerLine;
    BYTE *pData, *pDes,*pSrc;
    dwBytesPerLine = 640 * 16;   //8bit RGB
    dwDataSize =  dwBytesPerLine * 480;
    pData = new BYTE[dwDataSize];
    m_DataDownload.SetData(pData, dwDataSize);         //read 16 byte
    pDes = pData;
    ////////////////////////////////////////////////////////
    for(int y=0;y<m_pBitmap->Height;y++){
       pSrc =(BYTE *)m_pBitmap->ScanLine[y];
            for(int x=0;x<m_pBitmap->Width;x++){

                        memcpy(pSrc + x*3 , pDes+y*dwBytesPerLine + x*16 + 13,3);

            } // for
  }
 
    delete []pData;
}
void __fastcall TFormMain::PaintBoxDisplayPaint(TObject *Sender)
{
    UIDrawImage();
}

void __fastcall TFormMain::UIRedrawImage(void)
{
    //TODO: Add your source code here
    // determin image size
    TRect rc;

    if (m_pDirectShow){
        FormResize(this);
    }else{
        rc = CalDisplayRect(m_pBitmap->Width, m_pBitmap->Height);
        PaintBoxDisplay->SetBounds(rc.left, rc.top, rc.Width(), rc.Height());
    }

    // erase backgroun
    PaintBoxDisplay->Canvas->Brush->Color = PanelDisplay->Color;
    PaintBoxDisplay->Canvas->FillRect(rc);

    //
    UIDrawImage();

}
//---------------------------------------------------------------------------


void __fastcall TFormMain::UIDrawImage(void)
{
    //TODO: Add your source code here
    if (!m_pDirectShow){
#if 1
        TRect rc = PaintBoxDisplay->ClientRect;
        PaintBoxDisplay->Canvas->StretchDraw(rc, m_pBitmap);
#else

        ImageDisplay->Canvas->Draw(0,0, m_pBitmap);
#endif
    }else{
        m_pDirectShow->Repaint();
    }

}


void __fastcall TFormMain::UIPlayerUpdate(void)
{
    //TODO: Add your source code here
    if (!m_pDirectShow){
        PanelVideoControl->Visible = false;
        return;
    }
    //
    PanelVideoControl->Visible = true;
//    SpeedButtonPlay->Enabled = m_VideoInfo.bPlaying?false:true;
    SpeedButtonPlay->Down = m_VideoInfo.bPlaying;
    SpeedButtonPause->Down = !m_VideoInfo.bPlaying;
    SpeedButtonStop->Down = m_VideoInfo.bStop;
    SpeedButtonStep->Enabled = m_VideoInfo.bCanStep;


}
void __fastcall TFormMain::SpeedButtonPauseClick(TObject *Sender)
{
    if (m_pDirectShow){
        TimerVideo->Enabled = false;
        m_pDirectShow->Pause();
        m_VideoInfo.bPlaying = false;
        UIPlayerUpdate();
    }
}
//---------------------------------------------------------------------------

void __fastcall TFormMain::SpeedButtonPlayClick(TObject *Sender)
{
    if (m_pDirectShow && !m_VideoInfo.bPlaying){
        m_pDirectShow->Pause();
        m_VideoInfo.bPlaying = true;
        m_VideoInfo.bStop = false;
        UIPlayerUpdate();
        TimerVideo->Enabled = true;
    }
}
//---------------------------------------------------------------------------

void __fastcall TFormMain::SpeedButtonStopClick(TObject *Sender)
{
    if (m_pDirectShow){
        TimerVideo->Enabled = false;
        m_pDirectShow->Stop();
        m_VideoInfo.bPlaying = false;
        m_VideoInfo.bStop = true;
        m_VideoInfo.dwPos = 0;
        TrackBarPlayer->Position = 0;
        UIPlayerUpdate();
    }
}
//---------------------------------------------------------------------------

void __fastcall TFormMain::SpeedButtonStepClick(TObject *Sender)
{
    if (m_pDirectShow){
        TimerVideo->Enabled = false;
        m_pDirectShow->Step(1);
        m_VideoInfo.bPlaying = false;
        UIPlayerUpdate();
        UIVideoTimeUpdate();
        UIVideoProgressUpdate();
    }
}
//---------------------------------------------------------------------------

void __fastcall TFormMain::TrackBarPlayerChange(TObject *Sender)
{
    if (m_pDirectShow){
        DWORD dwPos;
        dwPos = TrackBarPlayer->Position;
        if (dwPos != m_VideoInfo.dwPos){
            m_pDirectShow->SeekToPosition(dwPos);
            UIPlayerUpdate();
            UIVideoTimeUpdate();
        }
    }
}
//---------------------------------------------------------------------------


void __fastcall TFormMain::UIVideoProgressUpdate(void)
{
    //TODO: Add your source code here
    if (m_pDirectShow){
        DWORD dwPos;
        dwPos = m_pDirectShow->GetCurrentPosition();
        m_VideoInfo.dwPos = dwPos;
        TrackBarPlayer->Position = dwPos;
        UIVideoTimeUpdate();

        if (m_VideoInfo.dwPos >= m_VideoInfo.dwDur){
            // restart
            // SpeedButtonStopClick(this);
            DWORD dwPos = 0;
            TrackBarPlayer->Position = dwPos;
            m_pDirectShow->SeekToPosition(dwPos);
            UIPlayerUpdate();
            UIVideoTimeUpdate();
        }


    }
}
void __fastcall TFormMain::TimerVideoTimer(TObject *Sender)
{
    UpdateBitmapContent();
    PaintBoxDisplayPaint(this);
    //UIVideoProgressUpdate();
}
//---------------------------------------------------------------------------


void __fastcall TFormMain::UIVideoTimeUpdate(void)
{
    //TODO: Add your source code here
    /*
    if (m_pDirectShow && m_VideoInfo.dwDur){
        DWORD dwPos;
        dwPos = m_pDirectShow->GetCurrentPosition();
        AnsiString strInfo;
        strInfo.sprintf("%02d:%02d/%02d:%02d", dwPos/60, dwPos%60, m_VideoInfo.dwDur/60, m_VideoInfo.dwDur%60);
        UIShowStatus(strInfo.c_str(), clBlue);
    }
    */ 
}

bool __fastcall TFormMain::IsHotKeyActive(void)
{
    //TODO: Add your source code here
    bool bActive = false;
    if (::GetKeyState(VK_LCONTROL) & 0x8000)
        bActive = true;
    return bActive;

}



void __fastcall TFormMain::BrowseImage(void)
{
    //TODO: Add your source code here
    AnsiString strFilename;
    strFilename = m_pFileList->Strings[m_nBrowseIndex];
    LoadImage(strFilename);
    UIRedrawImage();
//    PrepareDownloadData();
    //
    m_nBrowseIndex++;
    if (m_nBrowseIndex >= m_pFileList->Count)
        m_nBrowseIndex = 0;}

void __fastcall TFormMain::TimerBrowseTimer(TObject *Sender)
{
    TimerBrowse->Enabled = false;
    BrowseImage();
//    if (ComboBoxPatternType->ItemIndex == PATTERN_FOLDER)
    if (UIGetPatternType() == PATTERN_FOLDER)
        TimerBrowse->Enabled = true;
    //
}
//---------------------------------------------------------------------------
bool __fastcall TFormMain::LoadImage(AnsiString strFilename)
{
    //TODO: Add your source code here
    bool bSuccess = true;
    AnsiString strExt = ::ExtractFileExt(strFilename).UpperCase();
     if (strExt == ".BMP"){// || strExt == ".JPEG"){
        m_pFileBitmap->LoadFromFile(strFilename);
        TRect rc(0,0,m_pBitmap->Width, m_pBitmap->Height);
        m_pBitmap->Canvas->StretchDraw(rc, m_pFileBitmap);
     }else if (strExt == ".JPEG" || strExt == ".JPG"){
        TJPEGImage *pJpeg;
        pJpeg = new TJPEGImage;
        try{
            pJpeg->LoadFromFile(strFilename);
            m_pFileBitmap->Assign(pJpeg);
            TRect rc(0,0,m_pBitmap->Width, m_pBitmap->Height);
            m_pBitmap->Canvas->StretchDraw(rc, m_pFileBitmap);
        }
        catch(...){
            bSuccess = false;
        }
        delete pJpeg;
     }else{
        bSuccess = false;
     }
     return bSuccess;

}

int __fastcall TFormMain::GetInterval(void)
{
    //TODO: Add your source code here
    int nInterval = 1;
    BROWSE_INTERVAL_TYPE BrowseInterverType;
    BrowseInterverType = (BROWSE_INTERVAL_TYPE)ComboBoxInterval->ItemIndex;
    switch(BrowseInterverType){
        case INTERVAL_0: nInterval = 1; break;
        case INTERVAL_1: nInterval = 1000; break;
        case INTERVAL_2: nInterval = 2000; break;
        case INTERVAL_5: nInterval = 5000; break;
        case INTERVAL_10: nInterval = 10000; break;
    }
    return nInterval;

}

void __fastcall TFormMain::ComboBoxIntervalChange(TObject *Sender)
{
    TimerBrowse->Interval = GetInterval();
}
//---------------------------------------------------------------------------

void __fastcall TFormMain::UIBuildPatternList(void)
{
    //TODO: Add your source code here
    AnsiString strText;
    int nIndex = 0;
    ComboBoxPatternType->Clear();

    for(int i=0;i<PATTERN_NUM;i++){
        strText = "";
        switch(i){
            case PATTERN_RGB: strText = "RGB"; break;
            case PATTERN_SCALE_H: strText = "Scale H"; break;
            case PATTERN_SCALE_V: strText = "Scale V"; break;
            case PATTERN_WHITE: strText = "white"; break;
            case PATTERN_BORDER: strText = "Border"; break;
            case PATTERN_MATRIX2: strText = "Matrix 2"; break;
            case PATTERN_FOLDER: strText = "Folder..."; break;
            case PATTERN_FILE: strText = "File..."; break;
        }
        if (!strText.IsEmpty()){
            ComboBoxPatternType->Items->Add(strText.c_str());
            m_szPatternType[nIndex++] = (PATTERN_TYPE)i;
        }
    }
    ComboBoxPatternType->ItemIndex = 0;
    m_nPrePatternType = m_szPatternType[0];

}

PATTERN_TYPE __fastcall TFormMain::UIGetPatternType(void)
{
    //TODO: Add your source code here
    PATTERN_TYPE Type;
    int nSelect;
    nSelect = ComboBoxPatternType->ItemIndex;
    Type = m_szPatternType[nSelect];
    return Type;
}
 
void __fastcall TFormMain::UISetPatternType(PATTERN_TYPE PatternType){
    int nSelect = -1;
    for(int i=0;i<PATTERN_NUM && nSelect == -1;i++){
        if (PatternType == m_szPatternType[i])
            nSelect = i;
    }
    assert(nSelect != -1);
    ComboBoxPatternType->ItemIndex = nSelect;

}

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







