
// EGrabberMFCView.cpp : implementation of the CEGrabberMFCView class
//

#include "stdafx.h"
// SHARED_HANDLERS can be defined in an ATL project implementing preview, thumbnail
// and search filter handlers and allows sharing of document code with that project.
#ifndef SHARED_HANDLERS
#include "EGrabberMFC.h"
#endif

#include "EGrabberMFCDoc.h"
#include "EGrabberMFCView.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// CEGrabberMFCView

IMPLEMENT_DYNCREATE(CEGrabberMFCView, CView)

BEGIN_MESSAGE_MAP(CEGrabberMFCView, CView)
    ON_MESSAGE(UPDATE_IMAGE, updateImage)
END_MESSAGE_MAP()

CEGrabberMFCView::CEGrabberMFCView()
{
}

CEGrabberMFCView::~CEGrabberMFCView()
{
}

BOOL CEGrabberMFCView::PreCreateWindow(CREATESTRUCT& cs)
{
    // TODO: Modify the Window class or styles here by modifying
    //  the CREATESTRUCT cs

    return CView::PreCreateWindow(cs);
}

LRESULT CEGrabberMFCView::updateImage(WPARAM wParam, LPARAM lParam)
{
    CClientDC dc(this);
    OnPrepareDC(&dc);
    OnDraw(&dc);
    return TRUE;
}

void CEGrabberMFCView::OnDraw(CDC* pDC)
{
    CEGrabberMFCDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
    pDoc->globalEGrabber.cs.Lock();
    try {
        SyncDraw(pDC);
    }
    catch (...) {}
    pDoc->globalEGrabber.cs.Unlock();
}

void CEGrabberMFCView::SyncDraw(CDC* pDC)
{
    CEGrabberMFCDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
    if (pDoc->globalEGrabber.currentBufferAvailable) {
        Buffer buffer(pDoc->globalEGrabber.currentBufferData);
        ConvertedBuffer bgr = buffer.convert(pDoc->globalEGrabber, "BGR8");
        uint8_t *dstBuffer = reinterpret_cast<uint8_t *>(bgr.getPixels());
        DWORD width = (DWORD)bgr.getWidth();
        DWORD height = (DWORD)bgr.getHeight();
        DWORD pitch = width * 3;
        if (pitch % 4) {
            for (DWORD y = 0; y < height; ++y) {
                SetDIBitsToDevice(pDC->GetSafeHdc(), 0, y, width, 1, 0, 0, 0,
                    1, dstBuffer, pDoc->globalEGrabber.bitmapInfo, DIB_RGB_COLORS);
                dstBuffer += pitch;
            }
        }
        else {
            SetDIBitsToDevice(pDC->GetSafeHdc(), 0, 0, width, height, 0, 0, 0,
                height, dstBuffer, pDoc->globalEGrabber.bitmapInfo, DIB_RGB_COLORS);
        }
    }
    pDoc->globalEGrabber.pendingUpdate = false;
}

// CEGrabberMFCView diagnostics

#ifdef _DEBUG
void CEGrabberMFCView::AssertValid() const
{
    CView::AssertValid();
}

void CEGrabberMFCView::Dump(CDumpContext& dc) const
{
    CView::Dump(dc);
}

CEGrabberMFCDoc* CEGrabberMFCView::GetDocument() const // non-debug version is inline
{
    ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CEGrabberMFCDoc)));
    return (CEGrabberMFCDoc*)m_pDocument;
}
#endif //_DEBUG
