// EProDlg.cpp : implementation file
//

#include "stdafx.h"
#include "EPro.h"
#include "EProDlg.h"
#include "FuncCode.h"
#include "LastFileDialog.h"
#include "winuser.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
extern CString m_strAppPath;

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}
  
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CEProDlg dialog

CEProDlg::CEProDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CEProDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CEProDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	m_bWorkDetectPro=FALSE;
	m_bWorkOpenFile=FALSE;
	m_bWorkDetectChip=FALSE;
	m_bWorkErase=FALSE;
	m_bWorkWrite=FALSE;
	m_bWorkRead=FALSE;
	m_bWorkCheck=FALSE;
	m_bAutoWork=FALSE;
	m_nWrCount=0;
	m_nMsg=0;
}

void CEProDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CEProDlg)
	DDX_Control(pDX, IDC_PROGRESS, m_Progress);
	DDX_Control(pDX, IDC_LIST_MSG, m_listMsg);
	DDX_Control(pDX, IDC_EDIT_BUF2, m_editBuf2);
	DDX_Control(pDX, IDC_EDIT_BUF1, m_editBuf1);
	DDX_Control(pDX, IDC_TAB, m_Tab);
	DDX_Control(pDX, IDC_CHIPS, m_hlChips);
	DDX_Control(pDX, IDC_COMBO_LOCKBITS, m_comboLockBits);
	DDX_Control(pDX, IDC_COMBO_CHIPTYPE, m_comboChipType);
	DDX_Control(pDX, IDC_BUTTON_LOCK, m_btLock);
	DDX_Control(pDX, IDC_BUTTON_CHIPDETECT, m_btDetectChip);
	DDX_Control(pDX, IDC_BUTTON_WRITE, m_btWrite);
	DDX_Control(pDX, IDC_BUTTON_SAVEFILE, m_btSaveFile);
	DDX_Control(pDX, IDC_BUTTON_READ, m_btRead);
	DDX_Control(pDX, IDC_BUTTON_OPENFILE, m_btOpenFile);
	DDX_Control(pDX, IDC_BUTTON_ERASE, m_btErase);
	DDX_Control(pDX, IDC_BUTTON_CHECK, m_btCheck);
	DDX_Control(pDX, IDC_BUTTON_AUTO, m_btAuto);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CEProDlg, CDialog)
	//{{AFX_MSG_MAP(CEProDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_MESSAGE(TCN_XT_SELCHANGE, OnTabSelChange)
	ON_MESSAGE(XTWM_PROPERTYGRID_NOTIFY, OnGridNotify)
	ON_MESSAGE(WM_PRO_MSG,OnProMsg)
	ON_BN_CLICKED(IDC_BUTTON_OPENFILE, OnButtonOpenfile)
	ON_BN_CLICKED(IDC_BUTTON_CHIPDETECT, OnButtonChipdetect)
	ON_BN_CLICKED(IDC_BUTTON_SAVEFILE, OnButtonSavefile)
	ON_BN_CLICKED(IDC_BUTTON_ERASE, OnButtonErase)
	ON_BN_CLICKED(IDC_BUTTON_WRITE, OnButtonWrite)
	ON_BN_CLICKED(IDC_BUTTON_READ, OnButtonRead)
	ON_BN_CLICKED(IDC_BUTTON_CHECK, OnButtonCheck)
	ON_BN_CLICKED(IDC_BUTTON_AUTO, OnButtonAuto)
	ON_BN_CLICKED(IDC_BUTTON_LOCK, OnButtonLock)
	ON_BN_CLICKED(IDC_CHIPS, OnChips)
	ON_WM_DESTROY()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CEProDlg message handlers

BOOL CEProDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	
	InitInterface();

	m_Pro.m_nSerialPort=m_nPortSel;
	m_Pro.m_nBaudSel=m_nBaudSel;
	TRACE("m_nProType:%d\n",m_nProType);
	m_Pro.InitPro(this,m_nProType,m_nIspSpd);
	m_Pro.LoadChipList();
	m_comboChipType.SetCurSel(m_InfoSave.m_nChipSel);
	EnableHotKey(m_bHotKey);
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CEProDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CEProDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CEProDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CEProDlg::OnCancel() 
{
	// TODO: Add extra cleanup here
	SaveInfoSave();
	CDialog::OnCancel();
}

void CEProDlg::OnOK() 
{
	OnButtonAuto();
}

void CEProDlg::InitInterface()//初始化界面
{
	// Enable/Disable XP GUI Mode
    xtAfxData.bXPMode = TRUE;
    // Enable/Disable Menu Shadows
    xtAfxData.bMenuShadows = TRUE;
	//初始化指示按钮控件
	m_btOpenFile.InitButton(this,TRUE,TRUE,IDI_OPENFILE);
	m_btSaveFile.InitButton(this,FALSE,FALSE,IDI_SAVEFILE);
	m_btErase.InitButton(this,TRUE,TRUE,IDI_ERASE,IDI_ERASE2);
	m_btWrite.InitButton(this,TRUE,TRUE,IDI_WRITE,IDI_WRITE2);
	m_btRead.InitButton(this,TRUE,TRUE,IDI_READ,IDI_READ2);
	m_btCheck.InitButton(this,TRUE,TRUE,IDI_CHECK,IDI_CHECK2);
	m_btAuto.InitButton(this,FALSE,TRUE,IDI_AUTO);
	m_btDetectChip.InitButton(this);
	m_btLock.InitButton(this);

	m_Tab.InsertItem(0,"缓冲1");
	m_Tab.InsertItem(1,"缓冲2");
	m_Tab.InsertItem(2,"状态");
	m_Tab.InsertItem(3,"设置");

	m_Grid.Create(CRect(2000,2000,2000,2000),this,IDI_GRID);
	m_pProSetting=m_Grid.AddCategory("编程器");
	m_pSelPro=m_pProSetting->AddChildItem(new CXTPropertyGridItem("编程器类型",""));
	m_pSelPro->SetDescription("选择Easy 51Pro串行编程器还是并口下载线?(重启程序生效)");
	m_pProList = m_pSelPro->GetConstraints();
	m_pProList->AddConstraint("使用Easy 51Pro串行编程器");
	m_pProList->AddConstraint("使用Easy ISP下载线");
	m_pProList->AddConstraint("使用Atmel ByteBlaster下载线");
	m_pProList->AddConstraint("使用Altera ByteBlaster 下载线");
	m_pSelPro->SetFlags(pgiHasComboButton);

	m_pSelPort = m_pProSetting->AddChildItem(new CXTPropertyGridItem("串口",""));
	m_pSelPort->SetDescription("选择Easy 51Pro串行编程器使用的端口.(重启程序生效)");
	m_pPortList= m_pSelPort->GetConstraints();
	m_pPortList->AddConstraint("COM 1");
	m_pPortList->AddConstraint("COM 2");
	m_pPortList->AddConstraint("COM 3");
	m_pPortList->AddConstraint("COM 4");
	SetPortSel(0);
	m_pSelPort->SetFlags(pgiHasComboButton);

	m_pSelBaud = m_pProSetting->AddChildItem(new CXTPropertyGridItem("波特率",""));
	m_pSelBaud->SetDescription("选择Easy 51Pro串行编程器通讯时使用的波特率.(重启程序生效)");
	m_pBaudList= m_pSelBaud->GetConstraints();
	m_pBaudList->AddConstraint("9600");
	m_pBaudList->AddConstraint("19200");
	m_pBaudList->AddConstraint("28800");
	m_pBaudList->AddConstraint("57600");
	SetBaudSel(0);
	m_pSelBaud->SetFlags(pgiHasComboButton);
	
	m_pSelIspSpd = m_pProSetting->AddChildItem(new CXTPropertyGridItem("下载线性能",""));
	m_pSelIspSpd->SetDescription("根据下载线的稳定状况设置速度.(重启程序生效)");
	m_pIspSpdList = m_pSelIspSpd->GetConstraints();
	m_pIspSpdList->AddConstraint("一般");
	m_pIspSpdList->AddConstraint("较快");
	m_pIspSpdList->AddConstraint("最快");
	m_pSelIspSpd->SetFlags(pgiHasComboButton);

	m_pProSetting->Expand();

	m_pSysSetting=m_Grid.AddCategory("系统");
	m_pDetectBegin=m_pSysSetting->AddChildItem(new CXTPropertyGridItemBool("自动检测器件",TRUE));
	m_pDetectBegin->SetDescription("[自动完成]时是否先检测器件?");
	m_pSound=m_pSysSetting->AddChildItem(new CXTPropertyGridItemBool("使用声音提示",TRUE));
	m_pSound->SetDescription("编程成功或失败将会有不同的声音提示.");
	m_pHotKey=m_pSysSetting->AddChildItem(new CXTPropertyGridItemBool("使用热键",TRUE));
	m_pHotKey->SetDescription("按下热键后相当于点击了[自动完成].");
	m_pSysSetting->Expand();
	m_Grid.SetCustomColors( RGB(182, 189,210), 0, RGB(182, 189,210,), RGB(233, 243,247 ), 0);
	
	m_editBuf1.SetData(m_Pro.m_pWriteBuf,0x10000,0x10000);
	m_editBuf1.SetOptions(TRUE, TRUE, TRUE, FALSE);
	m_editBuf1.SetBPR(8);
	m_editBuf1.EnableCaret(TRUE);
	m_editBuf1.SetAddressBase(0);
	m_editBuf1.RedrawWindow();
	m_editBuf1.m_bAllowDeletes=FALSE;
	m_editBuf2.SetData(m_Pro.m_pReadBuf,0x10000,0x10000);
	m_editBuf2.SetOptions(TRUE, TRUE, TRUE, FALSE);
	m_editBuf2.SetBPR(8);
	m_editBuf2.EnableCaret(TRUE);
	m_editBuf2.SetAddressBase(0);
	m_editBuf2.RedrawWindow();
	m_editBuf2.m_bAllowDeletes=FALSE;
	
	m_comboLockBits.InsertString(0,"Lock Bit-1");
	m_comboLockBits.InsertString(1,"Lock Bit-2");
	m_comboLockBits.InsertString(2,"Lock Bit-3");
	m_comboLockBits.SetCurSel(0);
	m_Progress.ShowWindow(SW_HIDE);

	LoadInfoSave();
	EnableCtrl(TRUE);
}

void CEProDlg::SelWnd(int nSel)//选择窗口
{
	m_Tab.SetCurSel(nSel);
	m_nWndSel=nSel;
	CRect CtrlRect,CtrlRect2;
	m_Tab.GetChildRect(CtrlRect2);
	m_Tab.GetWindowRect(&CtrlRect);
	ScreenToClient( &CtrlRect );
	CtrlRect.SetRect(CtrlRect.left+3,CtrlRect.top+3,CtrlRect.left+CtrlRect2.Width()+3,CtrlRect.top+CtrlRect2.Height()+3);
	if(nSel==0)
 	{

		m_editBuf1.SetWindowPos(NULL,CtrlRect.left,CtrlRect.top,CtrlRect.Width(),CtrlRect.Height(),SWP_SHOWWINDOW);
		m_editBuf2.SetWindowPos(NULL,2000,2000,0,0,SWP_HIDEWINDOW);
		m_listMsg.SetWindowPos(NULL,2000,2000,0,0,SWP_HIDEWINDOW);
		m_Grid.SetWindowPos(NULL,2000,2000,0,0,SWP_HIDEWINDOW);
 	}
 	else if(nSel==1)
 	{
		m_editBuf2.SetWindowPos(NULL,CtrlRect.left,CtrlRect.top,CtrlRect.Width(),CtrlRect.Height(),SWP_SHOWWINDOW);
		m_editBuf1.SetWindowPos(NULL,2000,2000,0,0,SWP_HIDEWINDOW);
		m_listMsg.SetWindowPos(NULL,2000,2000,0,0,SWP_HIDEWINDOW);
		m_Grid.SetWindowPos(NULL,2000,2000,0,0,SWP_HIDEWINDOW);
 	}
 	else if(nSel==2)
 	{
 		//m_edBuf1.ShowWindow(SW_HIDE);
 		//m_edBuf2.ShowWindow(SW_HIDE);
 		//m_List.ShowWindow(SW_SHOW);
		m_listMsg.SetWindowPos(NULL,CtrlRect.left,CtrlRect.top,CtrlRect.Width(),CtrlRect.Height(),SWP_SHOWWINDOW);
		m_editBuf2.SetWindowPos(NULL,2000,2000,0,0,SWP_HIDEWINDOW);
		m_editBuf1.SetWindowPos(NULL,2000,2000,0,0,SWP_HIDEWINDOW);
		m_Grid.SetWindowPos(NULL,2000,2000,0,0,SWP_HIDEWINDOW);
 	}
	else if(nSel==3)
	{
		m_Grid.SetWindowPos(NULL,CtrlRect.left-1,CtrlRect.top-1,CtrlRect.Width()+2,CtrlRect.Height()+2,SWP_SHOWWINDOW);
		m_editBuf2.SetWindowPos(NULL,2000,2000,0,0,SWP_HIDEWINDOW);
		m_editBuf1.SetWindowPos(NULL,2000,2000,0,0,SWP_HIDEWINDOW);
		m_listMsg.SetWindowPos(NULL,2000,2000,0,0,SWP_HIDEWINDOW);
	}
}

UINT CEProDlg::OnTabSelChange(WPARAM wParam, LPARAM lParam)
{
	//AfxMessageBox("OnTabSelChange");
	//CXTTabCtrl* pTabCtrl = (CXTTabCtrl*)lParam;
	int nSel=m_Tab.GetCurSel();
	SelWnd(nSel);
	return 0;
}

int CEProDlg::GetProType()
{
	return m_nProType=m_pProList->GetCurrent();
}

void CEProDlg::SetProType(int nProType)
{
	switch(nProType)
	{
	case 0:
		m_pSelPro->SetValue("使用Easy 51Pro串行编程器");
		m_pProList->SetCurrent(0);
		ShowMsg("使用Easy 51Pro串行编程器");
		break;
	case 1:
		m_pSelPro->SetValue("使用Easy ISP下载线");
		m_pProList->SetCurrent(1);
		ShowMsg("使用Easy ISP下载线");
		break;
	case 2:
		m_pSelPro->SetValue("使用Atmel ByteBlaster 下载线");
		m_pProList->SetCurrent(2);
		ShowMsg("使用Atmel ByteBlaster 下载线");
		break;
	case 3:
		m_pSelPro->SetValue("使用Altera ByteBlaster 下载线");
		m_pProList->SetCurrent(3);
		ShowMsg("使用Altera ByteBlaster 下载线");
		break;
	default:
		AfxMessageBox("请正确选择编程器类型!");
		break;
	} 
}

int CEProDlg::GetPortSel()
{
	return m_nPortSel=m_pPortList->GetCurrent()+1;
}

void CEProDlg::SetPortSel(int nPortSel)
{
	switch(nPortSel)
	{
	case 1:
		m_pSelPort->SetValue("COM 1");
		m_pPortList->SetCurrent(0);
		break;
	case 2:
		m_pSelPort->SetValue("COM 2");
		m_pPortList->SetCurrent(1);
		break;
	case 3:
		m_pSelPort->SetValue("COM 3");
		m_pPortList->SetCurrent(2);
		break;
	case 4:
		m_pSelPort->SetValue("COM 4");
		m_pPortList->SetCurrent(3);
		break;
	default:
		break;
	}
}

int CEProDlg::GetBaudSel()
{
	return m_nBaudSel=m_pBaudList->GetCurrent();
}

void CEProDlg::SetBaudSel(int nBaudSel)
{
	switch(nBaudSel)
	{
	case 0:
		m_pSelBaud->SetValue("9600");
		m_pBaudList->SetCurrent(0);
		break;
	case 1:
		m_pSelBaud->SetValue("19200");
		m_pBaudList->SetCurrent(1);
		break;
	case 2:
		m_pSelBaud->SetValue("28800");
		m_pBaudList->SetCurrent(2);
		break;
	case 3:
		m_pSelBaud->SetValue("57600");
		m_pBaudList->SetCurrent(3);
		break;
	default:
		break;
	}
}

int CEProDlg::GetIspSpd()
{
	return m_nIspSpd=m_pIspSpdList->GetCurrent();	
}

void CEProDlg::SetIspSpd(int nSpdSel)
{
	if(nSpdSel==0)
	{
		m_pSelIspSpd->SetValue("一般");
		m_pIspSpdList->SetCurrent(0);
	}
	else if(nSpdSel==1)
	{
		m_pSelIspSpd->SetValue("较快");
		m_pIspSpdList->SetCurrent(1);
	}
	else if(nSpdSel==2)
	{
		m_pSelIspSpd->SetValue("最快");
		m_pIspSpdList->SetCurrent(2);
	}
}

LRESULT CEProDlg::OnGridNotify(WPARAM wParam, LPARAM lParam)
{
	if(wParam == XT_PGN_ITEMVALUE_CHANGED)
	{
		TRACE("OnGridNotify(WPARAM wParam, LPARAM lParam)\n");
		CXTPropertyGridItem* pItem = (CXTPropertyGridItem*)lParam;
		CString strCaption,strValue;
		strCaption= pItem->GetCaption();
		if(strCaption=="自动检测器件")
		{
			strValue=pItem->GetValue();
			if(strValue=="True")
				m_bDetectBegin=TRUE;
			else
				m_bDetectBegin=FALSE;
		}
		else if(strCaption=="使用声音提示")
		{
			strValue=pItem->GetValue();
			if(strValue=="True")
				m_bSound=TRUE;
			else
				m_bSound=FALSE;
		}
		else if(strCaption=="使用热键")
		{
			strValue=pItem->GetValue();
			if(strValue=="True")
			{
				m_bHotKey=TRUE;
				CHotKeyDialog HotKeyDlg;
				HotKeyDlg.m_byteKey=m_byteKey;
				HotKeyDlg.m_byteMask=m_byteMask;
				EnableHotKey(FALSE);
				if(HotKeyDlg.DoModal()==IDOK)
				{
					m_byteKey=HotKeyDlg.m_byteKey;
					m_byteMask=HotKeyDlg.m_byteMask;
				}
				EnableHotKey(TRUE);
			}
			else
				m_bHotKey=FALSE;
		}
		TRACE(_T("Value Changed. Caption = %s, ID = %i, Value = %s\n"), 
			  pItem->GetCaption(), pItem->GetID(), pItem->GetValue());
	}
	return 0;
}


void CEProDlg::LoadInfoSave()
{
	CString strFile;
	strFile=m_strAppPath+"EasyPro_Info.ini";
	if(GetPrivateProfileStruct(
		"InfoSave",  // address of section name
		"m_InfoSave",     // address of key name
		&m_InfoSave,      // address of return buffer
		sizeof(InfoSave), // size of return buffer
		strFile))
	{
		SetProType(m_nProType=m_InfoSave.m_nProType);
		SetPortSel(m_nPortSel=m_InfoSave.m_nSerialPort);
		SetBaudSel(m_nBaudSel=m_InfoSave.m_nBaudSel);
		SetIspSpd(m_nIspSpd=m_InfoSave.m_nIspSpd);
		if(!(m_bDetectBegin=m_InfoSave.m_bDetectBegin))
			m_pDetectBegin->SetValue("False");
		if(!(m_bSound=m_InfoSave.m_bSound))
			m_pSound->SetValue("False");
		if(!(m_bHotKey=m_InfoSave.m_bHotKey))
			m_pHotKey->SetValue("False");
		m_byteKey=m_InfoSave.m_byteKey;
		m_byteMask=m_InfoSave.m_byteMask;
		m_btOpenFile.EnableAuto(m_InfoSave.m_bAutoOpenFile);
		m_btErase.EnableAuto(m_InfoSave.m_bAutoErase);
		m_btWrite.EnableAuto(m_InfoSave.m_bAutoWrite);
		m_btRead.EnableAuto(m_InfoSave.m_bAutoRead);
		m_btCheck.EnableAuto(m_InfoSave.m_bAutoCheck);
		ShowMsg("Easy 51Pro(v2.0)");
	}
	else
	{	//第一次启动
		ShowMsg("Easy 51Pro(v2.0)");
		ShowMsg("设计者:聂忠强  Email:nie_zq@163.net");
	}
	
}

void CEProDlg::SaveInfoSave()
{
	CString strFile;
	strFile=m_strAppPath+"EasyPro_Info.ini";
	m_InfoSave.m_nProType=GetProType();
	m_InfoSave.m_nSerialPort=GetPortSel();
	m_InfoSave.m_nBaudSel=GetBaudSel();
	m_InfoSave.m_nIspSpd=GetIspSpd();
	m_InfoSave.m_bDetectBegin=m_bDetectBegin;
	m_InfoSave.m_bSound=m_bSound;
	m_InfoSave.m_bHotKey=m_bHotKey;
	m_InfoSave.m_byteKey=m_byteKey;
	m_InfoSave.	m_byteMask=m_byteMask;
	m_InfoSave.m_bAutoOpenFile=m_btOpenFile.m_bAuto;
	m_InfoSave.m_bAutoErase=m_btErase.m_bAuto;
	m_InfoSave.m_bAutoWrite=m_btWrite.m_bAuto;
	m_InfoSave.m_bAutoRead=m_btRead.m_bAuto;
	m_InfoSave.m_bAutoCheck=m_btCheck.m_bAuto;
	m_InfoSave.m_nChipSel=m_comboChipType.GetCurSel();
	WritePrivateProfileStruct(
	 "InfoSave",// pointer to section name
	"m_InfoSave",  // pointer to key name
	 &m_InfoSave,  // pointer to buffer that contains data to add
	sizeof(InfoSave), // size, in bytes, of the buffer
	strFile);    // pointer to initialization filename
}

void CEProDlg::ShowMsg(CString strMsg)
{

	if(m_nWndSel!=2)
		SelWnd(2);
	m_listMsg.InsertString(m_nMsg,strMsg);
	m_listMsg.SetCurSel(m_nMsg);
	//m_List.GetText(m_nMsg,m_str1);
	m_nMsg++;
}


UINT CEProDlg::OnProMsg(WPARAM dwMsg,LPARAM dwMsg2)
{
	BOOL bWork=FALSE;
	CString strMsg1,strMsg2,strMsg3;
	switch(dwMsg)
	{
	case PRO_INIT_SERIAL_SEC:
		ShowMsg("初始化串口通讯完成.");
		m_Pro.DetectPro(m_comboChipType.GetCurSel());
		return 0;
	case PRO_INIT_SERIAL_ER:
		ShowMsg("初始化串口通讯失败.");
		break;
	case PRO_INIT_PARALLEL_SEC:
		ShowMsg("初始化并口完成.");
		return 0;
	case PRO_INIT_PARALLEL_ER:
		ShowMsg("初始化并口失败.");
		break;
	case PRO_AVAILABLE:
		ShowMsg("编程器:就绪.");
		WorkProc(TRUE,FALSE);
		return 0;
	case PRO_INVALID:
		ShowMsg("编程器:不可用.");
		break;
	case PRO_INIT_SERIAL_NOT:
		ShowMsg("未初始化串口.");
		break;
	case PRO_RCV_ER:
		ShowMsg("接收数据时发生错误.");
		break;
	case PRO_RD_SIGN:
		ShowMsg("编程器:检测到特征字.");
		bWork=TRUE;
		break;
	case PRO_DETECTCHIP_SEC:
		strMsg1.Format("(特征字:%02x %02x %02x).",m_Pro.SignByte[0],m_Pro.SignByte[1],m_Pro.SignByte[2]);
		ShowMsg("编程器:检测到器件"+strMsg1);
		strMsg1=m_Pro.GetCurChip()->Name;
		strMsg2.Format(" - ROM容量:%dK字节.",m_Pro.GetCurChip()->RomSize);
		strMsg3.Format(" 编程电压:%.2fV.",m_Pro.GetCurChip()->ProVol);
		strMsg1=strMsg1+strMsg2+strMsg3;
		ShowMsg(strMsg1);
		bWork=TRUE;
		break;
	case PRO_DETECTCHIP_ER:
		strMsg1.Format("(特征字:%02x %02x %02x).",m_Pro.SignByte[0],m_Pro.SignByte[1],m_Pro.SignByte[2]);
		ShowMsg("编程器:没检测到器件"+strMsg1);
		bWork=FALSE;
		break;
	case PRO_ERASE:
		ShowMsg("编程器:擦除器件完成.");
		bWork=TRUE;
		break;
	case PRO_WRITE_BEGIN:
		ShowMsg("编程器:写器件开始.");
		strMsg1.Format("写入%d字节...",m_Pro.GetMinLength(m_Pro.m_pWriteBuf,0x10000));
		ShowMsg(strMsg1);
		return 0;
	case PRO_WRITE_BLOCK:
		if(m_Pro.m_nDataLength==1 && m_Pro.m_nDataLength==0)
			return 0;
		m_Progress.ShowWindow(SW_SHOW);
		strMsg1.Format("正在写:%04x/%04x",m_Pro.m_nAddr-1,m_Pro.m_nDataLength-1);
		strMsg1.MakeUpper();
		m_Progress.SetText(strMsg1);
		m_Progress.SetPos(m_Pro.m_nAddr*100/(m_Pro.m_nDataLength-1));
		return 0;
	case PRO_WRITE_OVER:
		ShowMsg("编程器:写器件完成.");
		m_Progress.SetPos(100);
		m_Progress.SetText("写器件完成");
		m_Progress.Invalidate(FALSE);
		m_nWrCount++;
		bWork=TRUE;
		if(m_bWorkRead || m_bWorkCheck && m_nProType==0)
			return 0;
		break;
	case PRO_WRITE_ER:
		ShowMsg("编程器:写器件时发生错误.");
		break;
	case PRO_READ_BEGIN:
		ShowMsg("编程器:读器件开始.");
		return 0;
	case PRO_READ_BLOCK:
		if(m_Pro.m_nDataLength==1 && m_Pro.m_nDataLength==0)
			return 0;
		m_Progress.ShowWindow(SW_SHOW);
		strMsg1.Format("正在读:%04x/%04x",m_Pro.m_nAddr-1,m_Pro.m_nDataLength-1);
		strMsg1.MakeUpper();
			m_Progress.SetText(strMsg1);
			m_Progress.SetPos(m_Pro.m_nAddr*100/(m_Pro.m_nDataLength-1));
		return 0;
	case PRO_READ_OVER:
		ShowMsg("编程器:读器件完成.");
		m_Progress.SetPos(100);
		m_Progress.SetText("读器件完成");
		m_Progress.Invalidate(FALSE);
		m_editBuf2.SetData(m_Pro.m_pReadBuf,0x10000);
		ShowMsg("数据已经保存到缓冲2.");
		if(m_bCheck)
			bWork=CheckData();
		else
			bWork=TRUE;
		break;
	case PRO_LOCK_BIT:
		ShowMsg("编程器:写锁定位完成.");
		bWork=TRUE;
		break;
	case PRO_WORK_INVALID:
		ShowMsg("编程器:无效的操作.");
		break;
	default:
		break;
	}
	WorkProc(bWork);
	return 0;
}

void CEProDlg::EnableCtrl(BOOL bEn)
{
	TRACE("EnableCtrl(%d)\n",bEn);
	m_btDetectChip.SetIndicator(FALSE);
	m_btOpenFile.SetIndicator(FALSE);
	m_btSaveFile.SetIndicator(FALSE);
	m_btErase.SetIndicator(FALSE);
	m_btWrite.SetIndicator(FALSE);
	m_btRead.SetIndicator(FALSE);
	m_btCheck.SetIndicator(FALSE);
	m_btLock.SetIndicator(FALSE);
	m_btAuto.SetIndicator(FALSE);
	
	if(bEn==TRUE)
	{	
		m_bWorkDetectPro=FALSE;
		m_bWorkOpenFile=FALSE;
		m_bWorkDetectChip=FALSE;
		m_bWorkErase=FALSE;
		m_bWorkWrite=FALSE;
		m_bWorkRead=FALSE;
		m_bWorkCheck=FALSE;
		m_bAutoWork=FALSE;

		m_btOpenFile.m_bUse=TRUE;
		m_btDetectChip.m_bUse=TRUE;
		m_btSaveFile.m_bUse=TRUE;
		m_btErase.m_bUse=TRUE;
		m_btWrite.m_bUse=TRUE;
		m_btRead.m_bUse=TRUE;
		m_btCheck.m_bUse=TRUE;
		m_btLock.m_bUse=TRUE;
		m_btAuto.m_bUse=TRUE;
		m_comboChipType.EnableWindow(TRUE);
		m_comboLockBits.EnableWindow(TRUE);
	}
	else
	{
	
		m_btOpenFile.m_bUse=FALSE;
		m_btDetectChip.m_bUse=FALSE;
		m_btSaveFile.m_bUse=FALSE;
		m_btErase.m_bUse=FALSE;
		m_btWrite.m_bUse=FALSE;
		m_btRead.m_bUse=FALSE;
		m_btCheck.m_bUse=FALSE;
		m_btLock.m_bUse=FALSE;
		m_btAuto.m_bUse=FALSE;
		m_comboChipType.EnableWindow(FALSE);
		m_comboLockBits.EnableWindow(FALSE);
	}
}

void CEProDlg::OnButtonOpenfile() 
{
	// TODO: Add your control notification handler code here
	static CLastFileDialog m_FileDlg(TRUE,"bin",NULL,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,"二进制文件(*.bin)|*.bin|Intel Hex文件(*.hex)|*.hex|");
	if(m_btOpenFile.m_bUse)
	{
		if(m_FileDlg.DoModal()==IDOK)
		{
			m_strOpenFile=m_FileDlg.GetLastFileName();
			//AfxMessageBox(m_strOpenFile);
			m_strOpenFileExt=m_FileDlg.GetLastFileExt(); 
			//AfxMessageBox(m_strOpenFileExt);
			m_strOpenFileExt.MakeUpper();
			OpenFile();
		}
	}
}

BOOL CEProDlg::OpenFile()
{
	
	if(m_strOpenFile!="")
	{
		if(m_fileOpen.Open(m_strOpenFile,CFile::shareCompat|CFile::modeRead,NULL))
		{
			int nFileSize;
			nFileSize=m_fileOpen.GetLength();
			if(m_strOpenFileExt=="HEX")
			{
				char* pFileBuf=(char*)GlobalAlloc(GMEM_FIXED,nFileSize+1);
				memset(pFileBuf,0,nFileSize+1);
				m_fileOpen.Read(pFileBuf,nFileSize);
				HexToBin(pFileBuf,m_Pro.m_pWriteBuf);
				GlobalFree(pFileBuf);
			}
			else
			{
				if(nFileSize>0x10000)  nFileSize=0x10000;
				memset(m_Pro.m_pWriteBuf,0xff,0x10000);
				m_fileOpen.Read(m_Pro.m_pWriteBuf,nFileSize);
			}
			m_editBuf1.SetData(m_Pro.m_pWriteBuf,0x10000);
			m_fileOpen.Close();
			CString strFileSize;
			strFileSize.Format("(%d字节).",nFileSize);
			ShowMsg("读入文件 "+m_strOpenFile+" 到缓冲1"+strFileSize);
			WorkProc(TRUE,FALSE);
		}
		else
		{
			ShowMsg("打开文件失败.");
			WorkProc(FALSE);
			return FALSE;
		}
	}
	else
	{
		ShowMsg("请先打开文件.");
		WorkProc(FALSE);
		return FALSE;
	}
	return TRUE;

}


void CEProDlg::WorkProc(BOOL bWork,BOOL bBeep)
{
	TRACE("WorkProc(%d)\n",bWork);
	if(!bWork)
	{
		if(bBeep)
			BeepError();
		EnableCtrl(TRUE);
		return;
	}
	if(m_bWorkOpenFile)
	{
		m_bWorkOpenFile=FALSE;
		OpenFile();
		return;
	}
	if(m_bWorkDetectPro)
	{
		m_Pro.DetectPro(m_comboChipType.GetCurSel());
		m_bWorkDetectPro=FALSE;
		return;
	}
	if(m_bWorkDetectChip)
	{
		m_Pro.DetectChip(m_comboChipType.GetCurSel());
		m_bWorkDetectChip=FALSE;
		return;
	}
	if(m_bWorkErase)
	{
		EnableCtrl(FALSE);
		m_btErase.SetIndicator(TRUE);
		m_Pro.Erase(m_comboChipType.GetCurSel());
		m_bWorkErase=FALSE;
		return;
	}
	if(m_bWorkWrite)
	{
		EnableCtrl(FALSE);
		m_editBuf1.GetData(m_Pro.m_pWriteBuf,0x000);
		m_btWrite.SetIndicator(TRUE);
		m_Pro.Write(m_comboChipType.GetCurSel());
		m_bWorkWrite=FALSE;
		return;
	}
	if(m_bWorkRead)
	{
		EnableCtrl(FALSE);
		m_btRead.SetIndicator(TRUE);
		m_bCheck=FALSE;
		m_Pro.m_bCheck=FALSE;
		m_Pro.Read(m_comboChipType.GetCurSel());
		m_bWorkRead=FALSE;
		return;
	}
	if(m_bWorkCheck)
	{
		EnableCtrl(FALSE);
		m_btCheck.SetIndicator(TRUE);
		m_bCheck=TRUE;
		if(m_nWrCount==0)
			m_Pro.m_bCheck=FALSE;
		else
			m_Pro.m_bCheck=TRUE;
		m_Pro.Read(m_comboChipType.GetCurSel());
		m_bWorkCheck=FALSE;
		return;
	}
	m_bAutoWork=FALSE;
	EnableCtrl(TRUE);
	if(bBeep)
		BeepOk();
}


void CEProDlg::OnButtonChipdetect() 
{
	// TODO: Add your control notification handler code here
	if(!m_btDetectChip.m_bUse)
		return;

	EnableCtrl(TRUE);
	m_bAutoWork=FALSE;
	m_bWorkDetectChip=TRUE;
	WorkProc(TRUE);
}

void CEProDlg::OnButtonSavefile() 
{
	// TODO: Add your control notification handler code here
	if(!m_btSaveFile.m_bUse)
		return;

	UINT nFileLength;
	CString strFileInfo;
	static CFileDialog m_FileDlg(FALSE,"bin",NULL,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,"二进制文件(*.bin)|*.bin|");
	if(m_FileDlg.DoModal()==IDOK)
	{
		
		if(m_fileSave.Open(m_FileDlg.GetPathName(),CFile::shareCompat|CFile::modeCreate|CFile::modeWrite,NULL))
		{
			m_editBuf2.GetData(m_Pro.m_pReadBuf,0x10000);
			m_fileSave.Write(m_Pro.m_pReadBuf,nFileLength=m_Pro.GetMinLength(m_Pro.m_pReadBuf,0x10000));
			strFileInfo.Format("%d字节",nFileLength);
			ShowMsg("缓冲2保存到文件 "+m_FileDlg.GetPathName()+"("+strFileInfo+").");
			m_fileSave.Close();
		}

	}	
}

void CEProDlg::OnButtonErase() 
{
	// TODO: Add your control notification handler code here
	if(!m_btErase.m_bUse)
		return;
	EnableCtrl(TRUE);
	m_bAutoWork=FALSE;
	m_bWorkErase=TRUE;
	WorkProc(TRUE);
}

void CEProDlg::OnButtonWrite() 
{
	// TODO: Add your control notification handler code here
	if(!m_btWrite.m_bUse)
		return;
	EnableCtrl(TRUE);
	m_bAutoWork=FALSE;
	m_bWorkWrite=TRUE;
	WorkProc(TRUE);
}

void CEProDlg::OnButtonRead() 
{
	// TODO: Add your control notification handler code here
	if(!m_btRead.m_bUse)
		return;
	EnableCtrl(TRUE);
	m_bAutoWork=FALSE;
	m_bWorkRead=TRUE;
	WorkProc(TRUE);
}

void CEProDlg::OnButtonCheck() 
{
	// TODO: Add your control notification handler code here
	if(!m_btCheck.m_bUse)
		return;
	EnableCtrl(TRUE);
	m_bAutoWork=FALSE;
	m_bWorkCheck=TRUE;
	WorkProc(TRUE);	
}

void CEProDlg::OnButtonAuto() 
{
	// TODO: Add your control notification handler code here
	if(!m_btAuto.m_bUse)
		return;
	EnableCtrl(TRUE);
	m_listMsg.ResetContent( );
	m_nMsg=0;
	m_bWorkOpenFile=m_btOpenFile.m_bAuto;
	m_bWorkDetectPro=TRUE;
	m_bWorkDetectChip=m_bDetectBegin;
	m_bWorkErase=m_btErase.m_bAuto;
	m_bWorkWrite=m_btWrite.m_bAuto;
	m_bWorkRead=m_btRead.m_bAuto;
	m_bWorkCheck=m_btCheck.m_bAuto;
	m_bAutoWork=TRUE;
	WorkProc(TRUE);
}

void CEProDlg::OnButtonLock()
{
	// TODO: Add your control notification handler code here
	if(m_btLock.m_bUse)
		m_Pro.LockBit(m_comboChipType.GetCurSel(),m_comboLockBits.GetCurSel()+1);
}

BOOL CEProDlg::CheckData()
{
	UINT nPos,nCount=0;
	CString strMsg;
		
	ShowMsg("-------------------效验开始------------------");
		
	for(nPos=0;nPos<=0xffff;nPos++)
	{
		if(m_Pro.m_pWriteBuf[nPos]!=m_Pro.m_pReadBuf[nPos])
		{
			strMsg.Empty();
			nCount++;
			strMsg.Format("    %05d - 地址:%04x  写:%02x  读:%02x",nCount,nPos,m_Pro.m_pWriteBuf[nPos],m_Pro.m_pReadBuf[nPos]);
			strMsg.MakeUpper();
			m_listMsg.InsertString(m_nMsg,strMsg);	
			m_nMsg++;
		}
	}
		strMsg.Format("共发现%5d个单元不对!",nCount);
		ShowMsg(strMsg);
		ShowMsg("-------------------效验结束------------------");
		m_bCheck=FALSE;
		if(nCount==0)
			return TRUE;
		else
			return FALSE;	
}

void CEProDlg::OnChips() 
{
	// TODO: Add your control notification handler code here
	
	CString strChipManagerPath;
	strChipManagerPath=m_strAppPath+"ChipManager.exe";
	m_hlChips.EnableShellExecute(FALSE);
	ShellExecute(NULL, "open",strChipManagerPath ,NULL, NULL, SW_SHOW);
	//AfxMessageBox("OnChips() ");
}


void CEProDlg::EnableHotKey(BOOL bEn)
{
	static BOOL bOpenHotKey=FALSE;
	if(bEn)
	{
		if(bOpenHotKey=AddHotkey(this->GetSafeHwnd(),m_byteKey,m_byteMask))
			TRACE("AddHotkey: PASS\n");
	}
	else
	{
		if(bOpenHotKey)
		 DeleteHotkey(this->GetSafeHwnd(),m_byteKey,m_byteMask);
		TRACE("DeleteHotkey: PASS\n");
		bOpenHotKey=FALSE;
	}

}

LRESULT CEProDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) 
{
	// TODO: Add your specialized code here and/or call the base class
	//TRACE("WindowProc\n");
	if(message==WM_HOTKEY && lParam==WM_KEYDOWN)
	{
		OnButtonAuto();
	}
	return CDialog::WindowProc(message, wParam, lParam);
}

void CEProDlg::OnDestroy() 
{
	CDialog::OnDestroy();
	EnableHotKey(FALSE);
	// TODO: Add your message handler code here
	
}

extern BOOL m_bWin98;
void CEProDlg::BeepError()
{
	if(m_bSound)
		if(!m_bWin98)
			AfxBeginThread(BeepErrorThread,this);
		else
			MessageBeep(MB_ICONEXCLAMATION);
		::FlashWindow(this->GetSafeHwnd(),TRUE);
}

void CEProDlg::BeepOk()
{
	if(m_bSound)
		if(!m_bWin98)
			AfxBeginThread(BeepOkThread,this);
		else
			MessageBeep(MB_OK);
}


UINT CEProDlg::BeepOkThread(LPVOID Param)
{
	Beep(2000,30);
	Sleep(100);
	Beep(2000,30);
	Sleep(100);
	Beep(2000,30);
	return 0;
}

UINT CEProDlg::BeepErrorThread(LPVOID Param)
{
	Beep(410,150);
	return 0;
}


