// ShowEffectDlg.cpp : implementation file
//

#include "stdafx.h" 
#include "ylgl.h"
#include "ShowEffect.h"
#include <math.h>
#include "InputName.h"
#define	THUMBNAIL_WIDTH		60
#define	THUMBNAIL_HEIGHT	50

/////////////////////////////////////////////////////////////////////////////
// ShowEffectDlg dialog
ShowEffectDlg::ShowEffectDlg(CWnd* pParent /*=NULL*/)
: CDialog(ShowEffectDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(ShowEffectDlg)
	// NOTE: the ClassWizard will add member initialization here
	m_pImgFinalShow=NULL;
	m_pImgPNG=NULL;
	m_pImgPNGbake=NULL;
	m_pImgJPG=NULL;
	//}}AFX_DATA_INIT
	m_nPNGIndex=0;
	m_nJPGIndex=0;
	m_fscale=1.0;

	m_bTerminate=false;
	m_bRunning=false;
	m_hThread = NULL;
	m_bTerminate2=false;
	m_bRunning2=false;
	m_hThread2 = NULL;


	m_bLoadPNG=1;
	m_bLoadJPG=1;
}

void ShowEffectDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(ShowEffectDlg)
	DDX_Control(pDX, IDC_LIST2, m_ListJPG);
	DDX_Control(pDX, IDC_LIST1, m_ListPNG);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(ShowEffectDlg, CDialog)
	//{{AFX_MSG_MAP(ShowEffectDlg)
	ON_WM_DESTROY()
	ON_WM_PAINT()
	ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
	ON_BN_CLICKED(IDC_BUTTON2, OnButton2)
	ON_WM_LBUTTONDOWN()
	ON_WM_MOUSEMOVE()
	ON_WM_LBUTTONUP()
	ON_WM_MOUSEWHEEL()
	ON_NOTIFY(NM_CLICK, IDC_LIST1, OnClickList1)
	ON_WM_TIMER()
	ON_NOTIFY(NM_CLICK, IDC_LIST2, OnClickList2)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()
//	ON_WM_ERASEBKGND()
/////////////////////////////////////////////////////////////////////////////
// ShowEffectDlg message handlers
unsigned __stdcall LoadThumbNail17(LPVOID lpParam)
{
	try
	{
		ShowEffectDlg *pDlg=(ShowEffectDlg*)lpParam;

		CListCtrl   *ListCtrl=&pDlg->m_ListJPG;
		CImageList* pImgList=&pDlg->m_ImageListThumb2;

		// reset our image list
		for(int i=0; i<pImgList->GetImageCount(); i++)
			pImgList->Remove(i);	

		// remove all items from list view
		ListCtrl->DeleteAllItems();

		pImgList->SetImageCount(pDlg->m_vJPGFile.size());

		TCHAR path[MAX_PATH];
		vector<CString>::iterator iter;

		// Set redraw to FALSE to avoid flickering during adding new items
		ListCtrl->SetRedraw(FALSE);
		int nIndex=0;
		CString str, spath;	

		for(iter=pDlg->m_vJPGFile.begin(); iter!=pDlg->m_vJPGFile.end() && pDlg->m_bTerminate2!=true; iter++, nIndex++)
		{
			str=*iter;

			str=str.Right (str.GetLength ()-str.ReverseFind ('\\')-1);
			str=str.Left (str.Find ("."));

			ListCtrl->InsertItem(nIndex, str, nIndex);
		}

		ListCtrl->SetRedraw(TRUE);
		ListCtrl->Invalidate();

		const float fRatio=(float)THUMBNAIL_HEIGHT/THUMBNAIL_WIDTH;

		int XDest, YDest, nDestWidth, nDestHeight;
		nIndex=0;

		SolidBrush whitebrush(Color(255,255,255,255));
		for(iter=pDlg->m_vJPGFile.begin(); iter!=pDlg->m_vJPGFile.end() && pDlg->m_bTerminate2!=true; iter++, nIndex++)
		{
			// Load Image File
			Image *image=NULL;
			Bitmap *pBmp=NULL;
			str=*iter;
			spath=str.Left (str.ReverseFind ('\\')+1);
			spath+="s";
			spath+=str.Right (str.GetLength ()-str.ReverseFind ('\\')-1);
			if (PathFileExists(spath))
				::LoadImageFromBuf (&image, spath);
			else
				::LoadImageFromBuf (&image, str);


			int orientation=GetOrientation(image);
			if(orientation==8)
				image->RotateFlip( Rotate270FlipNone );
			else if(orientation==6)
				image->RotateFlip( Rotate90FlipNone );

			if(image->GetWidth()==0)
				continue;

			// Calculate Rect to fit to canvas

			const float fImgRatio=(float)image->GetHeight()/image->GetWidth();
			if(fImgRatio > fRatio)
			{
				nDestWidth=THUMBNAIL_HEIGHT/fImgRatio;
				XDest=(THUMBNAIL_WIDTH-nDestWidth)/2;
				YDest=0;
				nDestHeight=THUMBNAIL_HEIGHT;
			}
			else
			{
				XDest=0;
				nDestWidth=THUMBNAIL_WIDTH;
				nDestHeight=THUMBNAIL_WIDTH*fImgRatio;
				YDest=(THUMBNAIL_HEIGHT-nDestHeight)/2;
			}
			pBmp=new Bitmap(THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT, PixelFormat24bppRGB );
			Graphics graph2(pBmp);
			graph2.Clear(Color(255,192,192,192));

			graph2.FillRectangle (&whitebrush,1, 1, THUMBNAIL_WIDTH-2, THUMBNAIL_HEIGHT-2); 

			Graphics graph(pBmp);
			Rect desRect(XDest, YDest, nDestWidth, nDestHeight); 
			// Draw Image

			graph.DrawImage(image, desRect, 0,0,image->GetWidth(),image->GetHeight(),UnitPixel);

			delete image;

			// Attach to Bitmap and Replace image in CImageList
			CBitmap bitmap;
			HBITMAP hbmp;
			pBmp->GetHBITMAP(Color(255,255,255,255), &hbmp);
			bitmap.Attach(hbmp);
			pImgList->Replace(nIndex, &bitmap, NULL);
			delete pBmp;
			// Redraw only a current item for removing flickering and fast speed.
			ListCtrl->RedrawItems(nIndex, nIndex);

			// Release used DC and Object
		}
		ListCtrl->Invalidate();
		pDlg->m_bRunning2=false;
		pDlg->m_bTerminate2=false;

		_endthreadex( 0 );

		return 0;
	}
	catch(...)
	{
	}

	return true;
}

unsigned __stdcall LoadThumbNail16(LPVOID lpParam)
{
	try
	{
		ShowEffectDlg *pDlg=(ShowEffectDlg*)lpParam;

		CListCtrl   *ListCtrl=&pDlg->m_ListPNG;
		CImageList* pImgList=&pDlg->m_ImageListThumb;

		// reset our image list
		for(int i=0; i<pImgList->GetImageCount(); i++)
			pImgList->Remove(i);	

		// remove all items from list view
		ListCtrl->DeleteAllItems();

		pImgList->SetImageCount(pDlg->m_vPNGFile.size());

		TCHAR path[MAX_PATH];
		vector<CString>::iterator iter;

		// Set redraw to FALSE to avoid flickering during adding new items
		ListCtrl->SetRedraw(FALSE);
		int nIndex=0;
		CString str, spath;	

		for(iter=pDlg->m_vPNGFile.begin(); iter!=pDlg->m_vPNGFile.end() && pDlg->m_bTerminate!=true; iter++, nIndex++)
		{
			str=*iter;

			str=str.Right (str.GetLength ()-str.ReverseFind ('\\')-1);
			str=str.Left (str.Find ("."));

			ListCtrl->InsertItem(nIndex, str, nIndex);
		}

		ListCtrl->SetRedraw(TRUE);
		ListCtrl->Invalidate();

		const float fRatio=(float)THUMBNAIL_HEIGHT/THUMBNAIL_WIDTH;

		int XDest, YDest, nDestWidth, nDestHeight;
		nIndex=0;

		SolidBrush whitebrush(Color(255,255,255,255));
		for(iter=pDlg->m_vPNGFile.begin(); iter!=pDlg->m_vPNGFile.end() && pDlg->m_bTerminate!=true; iter++, nIndex++)
		{
			// Load Image File
			Image *image=NULL;
			Bitmap *pBmp=NULL;
			str=*iter;
			spath=str.Left (str.ReverseFind ('\\')+1);
			spath+="s";
			spath+=str.Right (str.GetLength ()-str.ReverseFind ('\\')-1);
			spath.Replace ("png","jpg");
			if (PathFileExists(spath))
			{
				::LoadImageFromBuf (&image, spath);
			}
			else
				::LoadImageFromBuf (&image, str);


			int orientation=GetOrientation(image);
			if(orientation==8)
				image->RotateFlip( Rotate270FlipNone );
			else if(orientation==6)
				image->RotateFlip( Rotate90FlipNone );

			if(image->GetWidth()==0)
				continue;

			// Calculate Rect to fit to canvas

			const float fImgRatio=(float)image->GetHeight()/image->GetWidth();
			if(fImgRatio > fRatio)
			{
				nDestWidth=THUMBNAIL_HEIGHT/fImgRatio;
				XDest=(THUMBNAIL_WIDTH-nDestWidth)/2;
				YDest=0;
				nDestHeight=THUMBNAIL_HEIGHT;
			}
			else
			{
				XDest=0;
				nDestWidth=THUMBNAIL_WIDTH;
				nDestHeight=THUMBNAIL_WIDTH*fImgRatio;
				YDest=(THUMBNAIL_HEIGHT-nDestHeight)/2;
			}
			pBmp=new Bitmap(THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT, PixelFormat24bppRGB );
			Graphics graph2(pBmp);
			graph2.Clear(Color(255,192,192,192));

			graph2.FillRectangle (&whitebrush,1, 1, THUMBNAIL_WIDTH-2, THUMBNAIL_HEIGHT-2); 

			Graphics graph(pBmp);
			Rect desRect(XDest, YDest, nDestWidth, nDestHeight); 
			// Draw Image

			graph.DrawImage(image, desRect, 0,0,image->GetWidth(),image->GetHeight(),UnitPixel);

			delete image;

			// Attach to Bitmap and Replace image in CImageList
			CBitmap bitmap;
			HBITMAP hbmp;
			pBmp->GetHBITMAP(Color(255,255,255,255), &hbmp);
			bitmap.Attach(hbmp);
			pImgList->Replace(nIndex, &bitmap, NULL);
			delete pBmp;
			// Redraw only a current item for removing flickering and fast speed.
			ListCtrl->RedrawItems(nIndex, nIndex);

			// Release used DC and Object
		}

		ListCtrl->Invalidate();
		pDlg->m_bRunning=false;
		pDlg->m_bTerminate=false;

		_endthreadex( 0 );

		return 0;
	}
	catch(...)
	{
	}
	return true;
}

BOOL ShowEffectDlg::OnInitDialog() 
{
	CDialog::OnInitDialog();
	GetDlgItem(IDC_BUTTON2)->EnableWindow(IsHasRights2new(49));

	// ��ȡ����PNGЧ��ͼ;
	using namespace helper_coffs;
	ffsco o;
	o.dirs(0);
	o.find(LPCSTR(g_path7), LPCSTR(_T("*.png")));
	ffsco::typeT coo;
	ffsco::typeT::iterator it;
	coo = o.co_file();
	for (it = coo.begin();	coo.end() != it;	it ++) 
	{
		m_AryPNGImgpaths.Add((*it).c_str());
	}
	if(m_AryPNGImgpaths.GetSize()==0)
	{
		AfxMessageBox(_T("����û�а�װЧ��ͼ!"), MB_ICONINFORMATION);
		::CreateDirectory (g_path7, NULL);
	}

	// Jeff.m_rcscreen:��Ļ�ߴ�;
	::SetWindowPos(m_hWnd,HWND_TOP,0 ,0,g_screenwid,g_screenhei,SWP_SHOWWINDOW); 
	m_rcscreen=CRect(0, 0, g_screenwid, g_screenhei);

	// Jeff.rc:��ʱ����;
	// Jeff.rc2:�ͻ������С,���ڷ���PNGЧ��ͼ;
	// Jeff.rc3:��ť����;
	CRect rc,rc2,rc3;
	GetClientRect(rc2);

	GetDlgItem(IDC_BUTTON1)->GetWindowRect(rc3);
	ScreenToClient(rc3);
	rc=rc2;
	rc.right =110;
	rc.top =rc3.bottom +rc3.top;
	m_ListPNG.MoveWindow(rc);

	rc=rc2;
	rc.left=rc.right-110;
	m_ListJPG.MoveWindow(rc);

	// m_pbmp:������ʾPNGЧ��ͼ��Bimap����PNG+������Ƭ �϶�Ϊһ�Ľ����;
	rc=rc2;
	rc.left +=110;
	rc.right -=110;
	m_pImgFinalShow = new Bitmap(rc.Width (), rc.Height (), PixelFormat24bppRGB );

	m_ImageListThumb.Create(THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT, ILC_COLOR24, 0, 1);
	m_ListPNG.SetImageList(&m_ImageListThumb, LVSIL_NORMAL);
	m_ImageListThumb2.Create(THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT, ILC_COLOR24, 0, 1);
	m_ListJPG.SetImageList(&m_ImageListThumb2, LVSIL_NORMAL);

	// ����PGNЧ��ͼ��List�б���;
	if(m_bRunning)return 0;
	CStringArray *pArray = &m_AryPNGImgpaths;
	m_vPNGFile.clear();
	for(int i=0; i<pArray->GetSize (); i++)
	{
		CString filePath=pArray->ElementAt (i);
		filePath.MakeLower();
		m_vPNGFile.push_back(filePath);
	}
	TerminateThread();
	m_hThread = (HANDLE)_beginthreadex(NULL,0, LoadThumbNail16,(LPVOID)this,0/* CREATE_SUSPENDED*/,&m_dwThreadID); 
	m_bRunning=true;

	// ����ѡƬ�������Ƭ��List�б���;
	{
		if(m_bRunning2)return 0;
		CStringArray *pArray=m_pPhotopatharray;
		m_vJPGFile.clear();
		for(int i=0; i<pArray->GetSize (); i++)
		{
			CString filePath=pArray->ElementAt (i);
			filePath.MakeLower();
			m_vJPGFile.push_back(filePath);
		}
		TerminateThread2();
		m_hThread2 = (HANDLE)_beginthreadex(NULL,0, LoadThumbNail17,(LPVOID)this,0/* CREATE_SUSPENDED*/,&m_dwThreadID2); 
		m_bRunning2=true;
	}

	SetTimer(1, 200, NULL);
	return TRUE;  // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}

BOOL ShowEffectDlg::TerminateThread()
{
	if ( !m_bRunning )
		return TRUE;

	m_bTerminate=true;

	for( ; ; )
	{
		if ( ::WaitForSingleObject(m_hThread, 0) == WAIT_OBJECT_0 )
			break;

		MSG msg;
		while (::PeekMessage(&msg,NULL,0,0,PM_NOREMOVE)) 
		{ 
			if (!AfxGetApp()->PumpMessage()) 
				break; 
		} 
	}
	::CloseHandle(m_hThread);
	return TRUE;
}

BOOL ShowEffectDlg::TerminateThread2()
{
	if ( !m_bRunning2 )
		return TRUE;

	m_bTerminate2=true;

	for( ; ; )
	{
		if ( ::WaitForSingleObject(m_hThread2, 0) == WAIT_OBJECT_0 )
			break;

		MSG msg;
		while (::PeekMessage(&msg,NULL,0,0,PM_NOREMOVE)) 
		{ 
			if (!AfxGetApp()->PumpMessage()) 
				break; 
		} 
	}
	::CloseHandle(m_hThread2);
	return TRUE;
}
void ShowEffectDlg::OnDestroy() 
{
	// TODO: Add your message handler code here
	TerminateThread2();
	TerminateThread();

	if(m_pImgFinalShow) 
		delete m_pImgFinalShow;
	m_pImgFinalShow=NULL;	

	if(m_pImgPNG)
		delete m_pImgPNG;
	m_pImgPNG=NULL;

	if(m_pImgPNGbake)
		delete m_pImgPNGbake;
	m_pImgPNGbake=NULL;

	if(m_pImgJPG)
		delete m_pImgJPG;
	m_pImgJPG=NULL;

	CDialog::OnDestroy();
}

void ShowEffectDlg::OnPaint() 
{
	CPaintDC dc(this); // device context for painting

	// TODO: Add your message handler code here
	try
	{
		if(m_pImgFinalShow)
		{
			Graphics graph2(dc.GetSafeHdc ());
			graph2.DrawImage(m_pImgFinalShow,110,0);
		}
	}
	catch(...)
	{
	}
	// Do not call CDialog::OnPaint() for painting messages
}

BOOL ShowEffectDlg::OnEraseBkgnd(CDC* pDC) 
{
	// TODO: Add your message handler code here and/or call default
	return 1;
}

void ShowEffectDlg::InitRc(Image *img)
{
	try
	{
		if(img==NULL)return;
		CRect rc;
		GetClientRect(rc);
		rc.right -=220;
		m_rc=rc;

		int width,height;
		width=img->GetWidth();
		height=img->GetHeight();
		//////////
		float fscale=(float)width/(float)height;
		float rcscale=((float)m_rc.Width ())/((float)m_rc.Height ());
		int rcwid=m_rc.Width ();
		int rchei=m_rc.Height ();
		int dt=0;
		if(rcscale<fscale)
		{
			dt=(rchei-rcwid/fscale)/2;
			m_rc.top+=dt;
			m_rc.bottom-=dt;
		}
		else
		{
			dt=(rcwid-rchei*fscale)/2;
			m_rc.left +=dt;
			m_rc.right-=dt;
		}
		m_rcbak=m_rc;
	}
	catch(...)
	{
	}
}

void ShowEffectDlg::RcChange()
{ 
}

int GetFileNo2()
{ 
	CString path;
	int begin=1;
	path.Format ("%s\\Ч��ͼ-%d.png", g_path7, begin);
	while (PathFileExists(path))
	{
		begin++;
		path.Format ("%s\\Ч��ͼ-%d.png", g_path7, begin);
	}
	return begin;
}

extern void SaveImageToFile(Image *img, CString path);
void ShowEffectDlg::OnButton1() 
{ 
	if(AfxMessageBox("����������\r\n1.ͼƬ��ʽΪ͸��PNG��ʽ.\r\n2.��ʾ���յ�λ��Ϊ͸��.", MB_ICONINFORMATION));
	CFileDialog fdlg(true, NULL,"openfile", OFN_ALLOWMULTISELECT,"png�ļ�(*.png)|*.png||"); 
	TCHAR   szBuffer[60000]={0};
	fdlg.m_ofn.lpstrFile   =   szBuffer;
	fdlg.m_ofn.nMaxFile   = 60000;
	if(fdlg.DoModal ()!=IDOK)
	{
		return;
	}
	POSITION pos=fdlg.GetStartPosition ();
	CStringArray array;
	while(pos!=NULL)
	{
		array.Add(fdlg.GetNextPathName (pos));
	}
	if(array.GetSize ()==0)return;

	int i = 0;
	for( i=0; i<array.GetSize (); i++)
	{
		Bitmap *img=NULL;
		//::LoadImageFromBuf(&img, array.ElementAt(i));
		LoadImageFromBuf((Image**)&img, array.ElementAt(i));
		if(img==NULL)continue;
		if(img->GetWidth()==0)continue;

		if(img->GetWidth()>2000 || img->GetHeight()>2000)
		{
			CRect rc(0,0,2000,2000);
			RectFitDes(img->GetWidth(), img->GetHeight(), rc);
			Bitmap *simg=new Bitmap(rc.Width (), rc.Height (), PixelFormat32bppARGB );
			Graphics graphic(simg);
			graphic.Clear(Color(0,0,0,0));
			graphic.DrawImage(img, 0,0,simg->GetWidth(), simg->GetHeight() );
			delete img;
			img=simg;
		}
		CString path;
		CString str=array.ElementAt (i);
		str=str.Right (str.GetLength ()-str.ReverseFind ('\\')-1);
		str=str.Left (str.Find ("."));
		/*	InputName dlg;
		if(dlg.DoModal ()!=IDOK)
		{
		path.Format ("%s\\Ч��ͼ-%d.png", g_path7, GetFileNo2());
		}
		else
		{	*/
		path.Format ("%s\\%s.png", g_path7, str);
		//}
		::SaveImageToFile (img, path);


		str=path;
		CString   spath=str.Left (str.ReverseFind ('\\')+1);
		spath+="s";
		spath+=str.Right (str.GetLength ()-str.ReverseFind ('\\')-1);
		spath.Replace ("png","jpg");
		CRect rc(0,0,100,100);
		RectFitDes(img->GetWidth(), img->GetHeight(), rc);
		Bitmap *simg=new Bitmap(rc.Width (), rc.Height (), PixelFormat32bppARGB );
		Graphics graphic(simg);graphic.Clear(Color(0,0,0,0));
		graphic.DrawImage(img, 0,0,simg->GetWidth(), simg->GetHeight() );
		::SaveImageToFile (simg, spath);
		delete img;delete simg;
	}
	m_nPNGIndex=0;
	m_nJPGIndex=0;
	m_AryPNGImgpaths.RemoveAll ();

	using namespace helper_coffs;
	ffsco o;
	o.dirs(0);
	o.find(LPCSTR(g_path7), LPCSTR(_T("*.png")));
	ffsco::typeT coo;
	ffsco::typeT::iterator it;
	coo = o.co_file();
	for (it = coo.begin();		coo.end() != it;		it ++) 
	{
		m_AryPNGImgpaths.Add((*it).c_str());
	}
	if(m_AryPNGImgpaths.GetSize()==0)
	{
		AfxMessageBox(_T("����û�а�װЧ��ͼ!"), MB_ICONINFORMATION);
		::CreateDirectory (g_path7, NULL);
	}
	TerminateThread();
	CStringArray *pArray=&m_AryPNGImgpaths;
	m_vPNGFile.clear();
	for(  i=0; i<pArray->GetSize (); i++)
	{
		CString filePath=pArray->ElementAt (i);
		filePath.MakeLower();
		m_vPNGFile.push_back(filePath);
	}

	m_hThread = (HANDLE)_beginthreadex(NULL,0, LoadThumbNail16,(LPVOID)this,0/* CREATE_SUSPENDED*/,&m_dwThreadID); 
	m_bRunning=true;
}

void ShowEffectDlg::OnButton2() 
{   
	POSITION pos;
	pos=m_ListPNG.GetFirstSelectedItemPosition();	
	if(pos==NULL)
	{
		return;
	}
	int selpos=m_ListPNG.GetNextSelectedItem(pos); 
	if(AfxMessageBox("ȷ��ɾ����?", MB_YESNO|MB_ICONINFORMATION)!=IDYES)return;


	CString   str=m_AryPNGImgpaths.ElementAt(selpos);
	CString   spath=str.Left (str.ReverseFind('\\')+1);
	spath+="s";
	spath+=str.Right (str.GetLength ()-str.ReverseFind ('\\')-1);
	spath.Replace ("png","jpg");
	::DeleteFile(str);			// ɾ��Ч��ͼ�е�jpg�ļ�;
	::DeleteFile(spath);		// ɾ��Ч��ͼ�е�s��jpg�ļ�;
	m_AryPNGImgpaths.RemoveAt(selpos);
	m_ListPNG.DeleteItem(selpos);	
	m_nPNGIndex=0;
	m_nJPGIndex=0;

}

void ShowEffectDlg::OnLButtonDown(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	//	SetCapture();
	//	m_startpt=point;
	CDialog::OnLButtonDown(nFlags, point);
}

void ShowEffectDlg::OnMouseMove(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	/*	if(GetCapture()!=this)return;
	if(m_rc.Width ()>m_rcscreen.Width ())
	{
	if(m_rc.left <m_rcscreen.left && point.x>m_startpt.x)
	{
	int dt=min(point.x-m_startpt.x, m_rcscreen.left-m_rc.left);
	m_rc.left +=dt;
	m_rc.right +=dt;
	}
	else if(m_rc.right >m_rcscreen.right && point.x<m_startpt.x)
	{
	int dt=min(m_startpt.x-point.x, m_rc.right-m_rcscreen.right);
	m_rc.left -=dt;
	m_rc.right -=dt;
	}
	}

	if(m_rc.Height ()>m_rcscreen.Height ())
	{
	if(m_rc.top <m_rcscreen.top && point.y>m_startpt.y)
	{
	int dt=min(point.y-m_startpt.y, m_rcscreen.top-m_rc.top);
	m_rc.top +=dt;
	m_rc.bottom +=dt;
	}
	else if(m_rc.bottom >m_rcscreen.bottom && point.y<m_startpt.y)
	{
	int dt=min(m_startpt.y-point.y, m_rc.bottom-m_rcscreen.bottom);
	m_rc.top -=dt;
	m_rc.bottom -=dt;
	}
	}

	m_startpt=point;
	RcChange();*/
	CDialog::OnMouseMove(nFlags, point);
}

void ShowEffectDlg::OnLButtonUp(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	/*	if(GetCapture()!=this)return;
	ReleaseCapture();*/
	CDialog::OnLButtonUp(nFlags, point);
}

BOOL ShowEffectDlg::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt) 
{
	// TODO: Add your message handler code here and/or call default
	/*	if(m_pImage==NULL)return 1;
	if(zDelta>0)
	{
	m_fscale*=1.2;
	int dtx=(m_fscale*m_rcbak.Width ()-m_rc.Width ())/2.0;
	int dty=(m_fscale*m_rcbak.Height ()-m_rc.Height ())/2.0;

	m_rc.left -=dtx;
	m_rc.right +=dtx;	
	m_rc.top -=dty;
	m_rc.bottom +=dty;
	}
	else
	{
	if(m_fscale<=1)return 1;
	m_fscale/=1.2;
	if(m_fscale<1)m_fscale=1;
	int dtx=(m_fscale*m_rcbak.Width ()-m_rc.Width ())/2.0;
	int dty=(m_fscale*m_rcbak.Height ()-m_rc.Height ())/2.0;

	m_rc.left -=dtx;
	m_rc.right +=dtx;	
	m_rc.top -=dty;
	m_rc.bottom +=dty;

	if(m_rcbak.Height ()==m_rcscreen.Height ())
	{
	if(m_rc.top <m_rcscreen.top && m_rc.bottom < m_rcscreen.bottom )
	{
	dtx=m_rcscreen.bottom -m_rc.bottom;
	m_rc.top +=dtx;
	m_rc.bottom +=dtx;
	}
	else if(m_rc.top >m_rcscreen.top && m_rc.bottom > m_rcscreen.bottom )
	{
	dtx=m_rc.top-m_rcscreen.top;
	m_rc.top -=dtx;
	m_rc.bottom -=dtx;
	}

	dtx=m_rc.Width ();
	m_rc.left =(m_rcscreen.Width ()-dtx)/2;
	m_rc.right =m_rc.left +dtx;
	}

	if(m_rcbak.Width ()==m_rcscreen.Width ())
	{
	if(m_rc.left <m_rcscreen.left && m_rc.right < m_rcscreen.right )
	{
	dtx=m_rcscreen.right -m_rc.right;
	m_rc.left +=dtx;
	m_rc.right +=dtx;
	}
	else if(m_rc.left >m_rcscreen.left && m_rc.right > m_rcscreen.right )
	{
	dtx=m_rc.left-m_rcscreen.left;
	m_rc.left -=dtx;
	m_rc.right -=dtx;
	}

	dtx=m_rc.Height ();
	m_rc.top =(m_rcscreen.Height ()-dtx)/2;
	m_rc.bottom =m_rc.top +dtx;

	}
	}
	RcChange();*/
	return CDialog::OnMouseWheel(nFlags, zDelta, pt);
}


void ShowEffectDlg::OnClickList1(NMHDR* pNMHDR, LRESULT* pResult) 
{
	// TODO: Add your control notification handler code here
	POSITION pos;
	pos=m_ListPNG.GetFirstSelectedItemPosition();	
	if(pos==NULL)
	{
		return;
	}
	m_nPNGIndex=m_ListPNG.GetNextSelectedItem(pos);
	m_bLoadPNG=1;	
	MakeEffect();
	*pResult = 0;
}

void ShowEffectDlg::OnTimer(UINT nIDEvent) 
{
	// TODO: Add your message handler code here and/or call default
	KillTimer(nIDEvent);
	MakeEffect();
}

void ShowEffectDlg::OnClickList2(NMHDR* pNMHDR, LRESULT* pResult) 
{
	// TODO: Add your control notification handler code here
	POSITION pos;
	pos=m_ListJPG.GetFirstSelectedItemPosition();	
	if(pos==NULL)
	{
		return;
	}
	m_nJPGIndex=m_ListJPG.GetNextSelectedItem(pos);	
	m_bLoadJPG=1;
	MakeEffect();	
	*pResult = 0;
}

int GetLengFromPt(CPoint pt1, CPoint pt2)
{
	return (pt1.x-pt2.x)*(pt1.x-pt2.x)+(pt1.y-pt2.y)*(pt1.y-pt2.y);
}

int GetLengFromPt2(CPoint pt1, CPoint pt2)
{
	return sqrt((float)(pt1.x-pt2.x)*(pt1.x-pt2.x)+(pt1.y-pt2.y)*(pt1.y-pt2.y));
}

void ShowEffectDlg::MakeEffect()
{
	// Jeff.m_AryPNGImgpaths,����ԭƬ\Ч��ͼ\ Ŀ¼�µ�����PNGͼƬ;;
	if(m_AryPNGImgpaths.GetSize()==0)
		return;

	// m_pbmp:������ʾPNGЧ��ͼ��Bimap����PNG+������Ƭ �϶�Ϊһ�Ľ����;
	if ( m_pImgFinalShow == NULL )
		return;

	Graphics graph(m_pImgFinalShow);

	// ����������ȫ����͸��ɫ���;
	graph.Clear(Color(255,255,255,255));
	if(m_bLoadJPG)
	{// �����µ�JPG��Ƭ;
		if(m_pImgJPG)
			delete m_pImgJPG;
		m_pImgJPG = NULL;
	}

	if(m_bLoadPNG)
	{// �����µ�PNGЧ��ͼ;
		if(m_pImgPNG)
			delete m_pImgPNG;
		m_pImgPNG=NULL;

		if(m_pImgPNGbake)
			delete m_pImgPNGbake;
		m_pImgPNGbake=NULL;

		// m_pImageΪ��ʾ��PNGЧ��ͼBitmap����;LoadImageFromBufָ����������PNG��Ƭ��ΪЧ��ͼ��ʾ;
		LoadImageFromBuf((Image**)&m_pImgPNG, m_AryPNGImgpaths.ElementAt(m_nPNGIndex));

		if(m_pPhotopatharray->GetSize())
		{
			GetRgn(m_pImgPNG);
		}

		m_pImgPNGbake = m_pImgPNG->Clone(0,0,m_pImgPNG->GetWidth(),m_pImgPNG->GetHeight(),PixelFormat32bppARGB );
	}

	int width,height;
	width=m_pImgPNG->GetWidth();
	height=m_pImgPNG->GetHeight();
	if(width==0 || height==0)
		return;

	InitRc(m_pImgPNG);

	CPoint pt1,pt2,pt3;
	int leng1,leng2,leng3;
	CPoint curpt;
	int leng;
	Graphics graph2(m_pImgPNG);

	// m_pPhotopatharray�����˵���Ƭ;
	if(m_pPhotopatharray->GetSize())
	{
		if(m_bLoadJPG)
		{// ���ع˿���Ƭ;
			LoadImageFromBuf(&m_pImgJPG, m_pPhotopatharray->ElementAt(m_nJPGIndex));
		}

		int i;
		for(int aa = 0; aa < RCARRARCOUNT; aa++)
		{
			leng1 = leng2 = leng3 = 10000000;
			for( i = 0; i < m_rcarray[aa].GetSize(); i += 2)
			{
				curpt.x = m_rcarray[aa].ElementAt(i);
				curpt.y = m_rcarray[aa].ElementAt(i+1);

				leng = GetLengFromPt(CPoint(0,0), curpt);
				if(leng<leng1)
				{
					leng1=leng;
					pt1=curpt;
				}
				leng=GetLengFromPt(CPoint(m_pImgPNG->GetWidth(),0), curpt);
				if(leng<leng2)
				{
					leng2=leng;
					pt2=curpt;
				}
				leng=GetLengFromPt(CPoint(0,m_pImgPNG->GetHeight()), curpt);
				if(leng<leng3)
				{
					leng3=leng;
					pt3=curpt;
				}
			}
			if(m_rcarray[aa].GetSize ())
			{		 
				pt1.x*=m_tempscale;
				pt1.y*=m_tempscale;
				pt2.x*=m_tempscale;
				pt2.y*=m_tempscale;
				pt3.x*=m_tempscale;
				pt3.y*=m_tempscale;
				Point destinationPoints[] = {
					Point(pt1.x, pt1.y),   // destination for upper-left point of original
					Point(pt2.x, pt2.y),  // destination for upper-right point of original
					Point(pt3.x, pt3.y)		// destination for lower-left point of original 
				};  
					//			graph2.DrawImage(m_pPhoto, destinationPoints, 3); 

					int lengx=GetLengFromPt2(pt1, pt2);
					int lengy=GetLengFromPt2(pt1, pt3);
					/*	CString ss;
					ss.Format("pt1:%d,%d pt2:%d,%d leng:%d", pt1.x, pt1.y,pt2.x, pt2.y,lengx);
					AfxMessageBox(ss);

					ss.Format("pt1:%d,%d pt3:%d,%d leng:%d", pt1.x, pt1.y,pt3.x, pt3.y,lengy);
					AfxMessageBox(ss);*/

					CRect rc(0,0,m_pImgJPG->GetWidth(),m_pImgJPG->GetHeight());
					RectFitDes(lengx,lengy,rc);
					graph2.DrawImage(
						m_pImgJPG,
						destinationPoints,
						3,
						rc.left,
						rc.top,
						rc.Width(),
						rc.Height(),
						UnitPixel,
						NULL,
						NULL,
						NULL);
			}
		}
		///////

		graph2.DrawImage(m_pImgPNGbake, 0, 0); 

	}

	Rect destinationRect( m_rc.left , m_rc.top , m_rc.Width (), m_rc.Height () );
	graph.DrawImage(m_pImgPNG, destinationRect, 0,0,width,height,UnitPixel);

	CRect rc;
	GetClientRect(rc);
	rc.left +=110;
	rc.right -=110;
	InvalidateRect(rc);

	m_bLoadPNG=0;
	m_bLoadJPG=0;
}

// Jeff.pBmpImage2:�����غõ�PNGЧ����Ƭ;
// ��ȡPNGЧ��ͼ��͸������;
/************************************************************************/
/* 
	������GetRgn
	��������ȡָ��Bitmap��������ʾ��ͼ���͸������;
	������
	pImgPNG[IN] Ҫ��ȡ͸�������Bitmap����ָ��;
	���أ�
	ע�⣺
*/
/************************************************************************/
void ShowEffectDlg::GetRgn(IN Bitmap *pImgPNG)
{
	m_tempscale=1.0;
	if(pImgPNG==NULL)return;

	// pBmpImage
	Bitmap *pBmpImage=NULL;
	BOOL bdelete=0;

	// .���PNGЧ����Ƭ��������800
	// Bitemap::GetWidth() ��ȡ��ͼ���ͼ��߶ȣ�������Ϊ��λ;
	if(pImgPNG->GetWidth()>800 || pImgPNG->GetHeight()>800)
	{	
		bdelete=1;
		CRect rc(0,0,800,800);

		// GetWidth()�ij�����CRect�ij����Dz�һ���ĵ�λֵ,��Ҫת���ʺ�ͼƬ�ı���;(һ����ͼƬ�����سߴ�,һ��DC�Ĵ�С�ߴ�)
		RectFitDes(pImgPNG->GetWidth(), pImgPNG->GetHeight(), rc);

		// ���ʺ�ͼƬ������������ʾ�豸������װ��ͼƬ;
		pBmpImage=new Bitmap(rc.Width (), rc.Height (), PixelFormat32bppARGB );
		Graphics graphic(pBmpImage);
		graphic.Clear(Color(0,0,0,0));
		graphic.DrawImage(pImgPNG, 0,0,pBmpImage->GetWidth(), pBmpImage->GetHeight() );
		m_tempscale=(float)pImgPNG->GetWidth()/(float)pBmpImage->GetWidth();
	}
	else
		pBmpImage=pImgPNG;

	// BitmapData��������ڴ�����������Ϣ�������������ݵ�λͼͼ��ľ�������Ķ���
	BitmapData bitmapData;
	UINT* pixels;
	Rect rc(0, 0, pBmpImage->GetWidth(), pBmpImage->GetHeight() );

	// ָ����ʽ��ȡpBmpImage���ͼƬ���ص�bitmapData��;
	pBmpImage->LockBits(
		rc,							// ���ݱ����ص�������;
		ImageLockModeRead,			// ������ʽ������д;
		PixelFormat32bppARGB,		// ���ݱ���ĸ�ʽ;
		&bitmapData);				// �洢���ݵĶ���;

	// Write to the temporary buffer provided by LockBits. RGB
	// Scan0:һ����ָ�뵽��һɨ���ߵĿ�ʼ
	pixels = (UINT*)bitmapData.Scan0;	

	// Stride:
	// һ��INTֵ��λͼ������һ��ɨ����ָ�����ֽ��������ֵ�Ǹ����Ե����ϵ�λͼͼ��
	DWORD wids=bitmapData.Stride/4;	// ����4,�պ�ΪColor::alpha \red  \green \blue ��ɫ��ֻ��PNG����alphaɫ��;

	Color color;
	Color color1,color2,color3,color4,color5,color6,color7,color8;

	// m_rcarray����,���ڼ�¼PNGͼƬ���alphaɫС��200�����ص�����;
	BYTE R,G,B;
	for(int aa=0; aa<RCARRARCOUNT; aa++)
		m_rcarray[aa].RemoveAll();	// Jeff.�����ǰ��;

	for( INT row = 0; row < rc.Height; ++row)
	{
		for(INT col = 0; col < rc.Width-1; ++col)
		{
			// ����һ��ȡ4�������color����;
			color.SetValue(pixels[row * wids + col]);

			// Color::GetA() ������ȡ��Color�����alpha����(���������ɫ��alpha����)��
			if(color.GetA() < 200)	
			{
				CArray<int,int>*pArray=NULL;
				for(int aa=0; aa<RCARRARCOUNT; aa++)
				{
					if(m_rcarray[aa].GetSize() && pArray==NULL)
					{
						double x=m_rcarray[aa].ElementAt(0);
						double y=m_rcarray[aa].ElementAt(1);

						int x0=(int)x;
						int y0=(int)y;

						double dtx=col-x;
						double dty=row-y;

						if(abs(dtx)>abs(dty))
						{	
							if(dty)
							{
								dtx/=abs(dty);
								dty/=abs(dty);
							}
							else if(dtx>0)
								dtx=1;
							else if(dtx<0)
								dtx=-1;
						}
						else
						{	
							if(dtx)
							{
								dty/=abs(dtx);
								dtx/=abs(dtx);
							}
							else if(dty>0)
								dty=1;
							else if(dtx<0)
								dty=-1;
						}	

						if(dtx>3)
						{
							double step=dtx/3.0;
							dtx/=step;
							dty/=step;
						}
						if(dty>3)
						{
							double step=dty/3.0;
							dtx/=step;
							dty/=step;
						}
						BOOL bFind=0;
						while(1)
						{
							x+=dtx;
							y+=dty;
							if(x>=(rc.Width-1) || x<1)break;
							if(y>=(rc.Height-1) || y<1)break;
							if(col>x0)
							{
								if(x<x0)
								{
									break;
								}
								if(x>col)
								{	
									break;
								}
							}
							if(col<x0)
							{
								if(x>x0)
								{	
									break;
								}
								if(x<col)
								{	
									break;
								}
							}

							if(row>y0)
							{
								if(y<y0)
								{	
									break;
								}
								if(y>row)
								{	
									break;
								}
							}
							if(row<y0)
							{
								if(y>y0)
								{	
									break;
								}
								if(y<row)
								{	
									break;
								}
							}
							color.SetValue(pixels[(int)y * wids + (int)x]);
							if(color.GetA()==255)
							{				
								color1.SetValue(pixels[(int)(y-1) * wids + (int)(x-1)]);
								color2.SetValue(pixels[(int)(y-1) * wids + (int)(x-0)]);
								color3.SetValue(pixels[(int)(y-1) * wids + (int)(x+1)]);
								color4.SetValue(pixels[(int)(y-0) * wids + (int)(x-1)]);
								color5.SetValue(pixels[(int)(y-0) * wids + (int)(x+1)]);
								color6.SetValue(pixels[(int)(y+1) * wids + (int)(x-1)]);
								color7.SetValue(pixels[(int)(y+1) * wids + (int)(x-0)]);
								color8.SetValue(pixels[(int)(y+1) * wids + (int)(x+1)]);
								if(color1.GetA()==255 && color2.GetA()==255 && color3.GetA()==255 && color4.GetA()==255 && color5.GetA()==255 && color6.GetA()==255 && color7.GetA()==255 && color8.GetA()==255)
								{
									bFind=1;
									break;
								}
							}
						}
						if(bFind==0)
							pArray=&(m_rcarray[aa]);
					}
				}


				if(pArray==NULL)
				{
					BOOL bcontinue=1;
					for(int yy=0; yy<RCARRARCOUNT; yy++)
					{
						if(m_rcarray[yy].GetSize()==0)
						{
							pArray=&(m_rcarray[yy]);
							bcontinue=0;
							break;
						}
					}
					if(bcontinue)continue;
				}
				pArray->Add(col);	// x����;
				pArray->Add(row);	// y����;
			}
		}
	}
	pBmpImage->UnlockBits(&bitmapData);

	if(bdelete)delete pBmpImage;
}