#include "CPxaEditor.h"
#include "resource.h"
#include "CMainEditor.h"
#include "CPxaEditorGrid.h"

IMPLEMENT_DYNAMIC(CPxaEditor, CDialog)

BEGIN_MESSAGE_MAP(CPxaEditor, CDialog)
	ON_COMMAND(IDOK, &CPxaEditor::OnEnterKey)
	ON_WM_SHOWWINDOW()
	ON_WM_SIZE()
	ON_WM_MOVING()
	ON_COMMAND(ID_EDIT_PXA, &CPxaEditor::OnEditPxa)
	ON_COMMAND(ID_EDIT_PNG, &CPxaEditor::OnEditPng)
	ON_COMMAND(ID_OPEN_FOLDER, &CPxaEditor::OnOpenFolder)
	ON_COMMAND(ID_UPDATE_LIST, &CPxaEditor::OnUpdateList)
	ON_COMMAND(ID_OPEN_FILE, &CPxaEditor::OnOpenFile)
	ON_COMMAND(ID_SAVE_FILE, &CPxaEditor::OnSaveFile)
	ON_COMMAND(ID_CLOSE_FILE, &CPxaEditor::OnCloseFile)
	ON_COMMAND(ID_UNDO, &CPxaEditor::OnUndo)
	ON_COMMAND(ID_REDO, &CPxaEditor::OnRedo)
	ON_COMMAND(ID_COPY, &CPxaEditor::OnCopy)
	ON_COMMAND(ID_PASTE, &CPxaEditor::OnPaste)
	ON_COMMAND(ID_CUT, &CPxaEditor::OnCut)
	ON_COMMAND(ID_SHOW_BK, &CPxaEditor::OnShowBk)
	ON_COMMAND(ID_SHOW_GRID, &CPxaEditor::OnShowGrid)
	ON_COMMAND(ID_GRID_SETTING, &CPxaEditor::OnGridSetting)
	ON_COMMAND(ID_BRUSH_WND, &CPxaEditor::OnBrushWnd)
	ON_COMMAND(ID_RESET_WND_POS, &CPxaEditor::OnResetWndPos)
	ON_LBN_DBLCLK(IDC_LIST_PNGLIST, &CPxaEditor::OnLbnDblclkListPnglist)
END_MESSAGE_MAP()

CPxaEditor::CPxaEditor(CWnd* pParent)
	: CDialog(IDD_CPXAEDITOR, pParent)
{
}

CPxaEditor::~CPxaEditor()
{
}

void CPxaEditor::Draw()
{
	pDrawWnd.Draw();
}

void CPxaEditor::Load(CString filename)
{
	saved.clear();
	undoRedo.Clear();
	//读取数据文件
	pngfile = filename;
	CString str = filename;
	str = str.Left(filename.ReverseFind(L'.'));
	str.Append(L".pxa");
	pxafile = str;
	//子窗口载入
	pDrawWnd.Load(pngfile);
	//载入文件数据
	FILE* fp;
	_wfopen_s(&fp, pxafile.GetString(), L"rb");
	if (fp)
	{
		fseek(fp, 0, SEEK_END);
		size_t fileLen = ftell(fp);
		fseek(fp, 0, SEEK_SET);
		std::vector<BYTE> cbuff;
		cbuff.resize(fileLen);
		fread_s(cbuff.data(), fileLen, fileLen, 1, fp);
		fclose(fp);
		std::vector<BYTE> byte_buff;
		size_t len = 0;
		ZLibUncompressData(&byte_buff, &len, cbuff.data(), fileLen);
		CString xml = (wchar_t*)byte_buff.data();
		XMLLoad(xml);//读取pxa数据
		//赋值
		StepCopyToSaved();
	}
	else
		Save();
	UpdateMenuState();//更新撤销重做菜单状态
	UpdateWindowTitle();//更新窗口标题
	Draw();
}

void CPxaEditor::StaticLoad(CString pxaName, CPXAEDITOR_DATATYPE_PXA* pxaList, int* outTileW, int* outTileH, bool* outInterArea)
{
	CString pxafile;
	pxafile.Format(L"./data/pxa/%s.pxa", pxaName.GetString());
	pxaList->clear();
	//载入文件数据
	FILE* fp;
	_wfopen_s(&fp, pxafile.GetString(), L"rb");
	if (fp)
	{
		fseek(fp, 0, SEEK_END);
		size_t fileLen = ftell(fp);
		fseek(fp, 0, SEEK_SET);
		std::vector<BYTE> cbuff;
		cbuff.resize(fileLen);
		fread_s(cbuff.data(), fileLen, fileLen, 1, fp);
		fclose(fp);
		std::vector<BYTE> byte_buff;
		size_t len = 0;
		ZLibUncompressData(&byte_buff, &len, cbuff.data(), fileLen);
		CString xml = (wchar_t*)byte_buff.data();
		StaticXMLLoad(xml, pxaList, outTileW, outTileH, outInterArea);//读取pxa数据
	}
	else
	{
		//如果文件不存在则使用nullpxa
		*outTileW = 16;
		*outTileH = 16;
	}
}

void CPxaEditor::Save()
{
	StepCopyToSaved();
	CString xml = XMLSaved();//写入pid数据
	//数据压缩
	std::vector<BYTE> compressData;
	size_t compressData_len;
	ZLibCompressData(&compressData, &compressData_len, xml.GetString(), ((size_t)xml.GetLength() + 1) * sizeof(wchar_t));//加入\0符
	//文件数据写入
	FILE* fp = nullptr;
	_wfopen_s(&fp, pxafile.GetString(), L"wb+");
	if (!fp)
	{
		CString err;
		err.Format(L"写入%s失败\n文件可能正在被占用", pxafile.GetString());
		MessageBox(err.GetString(), L"文件写入失败", MB_ICONINFORMATION);
		return;
	}
	fwrite(compressData.data(), compressData_len, 1, fp);
	fclose(fp);
	//更新窗口标题
	UpdateWindowTitle();
}

bool CPxaEditor::Close()
{
	if (!IsLoaded())
		return false;
	if (!CheckSaved())//如果未保存
	{
		switch (MessageBox(TEXT("想要保存已修改的数据吗？"), TEXT("修改的数据即将丢失"), MB_YESNOCANCEL | MB_ICONWARNING))
		{
		case IDYES:
			Save();
		case IDNO:
			break;
		case IDCANCEL:
			return true;
		}
	}
	ResetContext();
	return false;
}

CPXAEDITOR_DATATYPE_PXA* CPxaEditor::GetStep()
{
	return (CPXAEDITOR_DATATYPE_PXA*)undoRedo.GetStep(CPXAEDITOR_DATATYPE_PXA_STR);
}

void CPxaEditor::UpdateMenuState()
{
	if (undoRedo.UndoEmpty())
		GetMenu()->GetSubMenu(CPXAEDITOR_MENUINDEX_EDIT)->EnableMenuItem(ID_UNDO, MF_DISABLED);
	else
		GetMenu()->GetSubMenu(CPXAEDITOR_MENUINDEX_EDIT)->EnableMenuItem(ID_UNDO, MF_ENABLED);
	if (undoRedo.RedoEmpty())
		GetMenu()->GetSubMenu(CPXAEDITOR_MENUINDEX_EDIT)->EnableMenuItem(ID_REDO, MF_DISABLED);
	else
		GetMenu()->GetSubMenu(CPXAEDITOR_MENUINDEX_EDIT)->EnableMenuItem(ID_REDO, MF_ENABLED);
	if (IsLoaded())
	{
		GetMenu()->GetSubMenu(CPXAEDITOR_MENUINDEX_FILE)->EnableMenuItem(ID_SAVE_FILE, MF_ENABLED);
		GetMenu()->GetSubMenu(CPXAEDITOR_MENUINDEX_FILE)->EnableMenuItem(ID_CLOSE_FILE, MF_ENABLED);
		GetMenu()->GetSubMenu(CPXAEDITOR_MENUINDEX_EDIT)->EnableMenuItem(ID_COPY, MF_ENABLED);
		GetMenu()->GetSubMenu(CPXAEDITOR_MENUINDEX_EDIT)->EnableMenuItem(ID_PASTE, MF_ENABLED);
		GetMenu()->GetSubMenu(CPXAEDITOR_MENUINDEX_EDIT)->EnableMenuItem(ID_CUT, MF_ENABLED);
	}
	else
	{
		GetMenu()->GetSubMenu(CPXAEDITOR_MENUINDEX_FILE)->EnableMenuItem(ID_SAVE_FILE, MF_DISABLED);
		GetMenu()->GetSubMenu(CPXAEDITOR_MENUINDEX_FILE)->EnableMenuItem(ID_CLOSE_FILE, MF_DISABLED);
		GetMenu()->GetSubMenu(CPXAEDITOR_MENUINDEX_EDIT)->EnableMenuItem(ID_COPY, MF_DISABLED);
		GetMenu()->GetSubMenu(CPXAEDITOR_MENUINDEX_EDIT)->EnableMenuItem(ID_PASTE, MF_DISABLED);
		GetMenu()->GetSubMenu(CPXAEDITOR_MENUINDEX_EDIT)->EnableMenuItem(ID_CUT, MF_DISABLED);
	}
}

void CPxaEditor::UpdateWindowTitle()
{
	CString windowTitle, appendStr;
	bool sav = CheckSaved();
	auto& view = *pDrawWnd.GetMyView();

	appendStr.Format(TEXT("地形编辑窗口 - "));
	windowTitle.Append(appendStr);
	if (view.cursorX_selected == 0 && view.cursorY_selected == 0)
		appendStr.Format(TEXT("未选中任何地形 - "));
	else
		appendStr.Format(TEXT("当前选中的地形：(%d,%d) - "), view.cursorX_selected, view.cursorY_selected);
	windowTitle.Append(appendStr);
	if (IsLoaded())
	{
		appendStr.Format(TEXT("已载入文件：%s"), pxafile.GetString());
		windowTitle.Append(appendStr);
		if (!sav)
			windowTitle.Append(TEXT("(未保存)"));
		else
			windowTitle.Append(TEXT("(已保存)"));
	}
	else
	{
		windowTitle.Append(TEXT("(未载入文件)"));
	}
	SetWindowText(windowTitle);
}

bool CPxaEditor::CheckSaved()
{
	auto& step = *GetStep();
	//排除无效id的改动
	CPXAEDITOR_DATATYPE_PXA l, r;
	for (auto& p : saved)
	{
		if (p.first == 0 ||
			p.second == 0)
			continue;
		l.insert(p);
	}
	for (auto& p : step)
	{
		if (p.first == 0 ||
			p.second == 0)
			continue;
		r.insert(p);
	}
	//其他条件
	bool bPxaTile = (pxa_tile_w_saved == (int)(*pPxa_tile_w) &&
		pxa_tile_h_saved == (int)(*pPxa_tile_h)) &&
		bInterArea_saved == bInterArea;
	return l == r && bPxaTile;
}

bool CPxaEditor::IsLoaded()
{
	return pxafile.GetLength() > 0;
}

void CPxaEditor::ResetContext()
{
	pxafile = L"";
	pngfile = L"";
	saved.clear();
	undoRedo.Clear();
	pDrawWnd.ResetContext();
	//更新撤销重做菜单状态
	UpdateMenuState();
	//更新窗口标题
	UpdateWindowTitle();
}

void CPxaEditor::XMLLoad(CString xml)
{
	std::vector<char> utf8_buff;
	UTF16ToUTF8(xml.GetString(), &utf8_buff);
	tinyxml2::XMLDocument xmlDoc;
	xmlDoc.Parse(utf8_buff.data());
	tinyxml2::XMLElement* elem = nullptr;
	//寻找TileSet元素
	for (tinyxml2::XMLElement* pElem = xmlDoc.FirstChildElement(); pElem; pElem = pElem->NextSiblingElement())
	{
		if (!strcmp(pElem->Name(), "TileSet"))
		{
			elem = pElem;
			break;
		}
	}
	if (elem)
	{
		//读取TileSet
		*pPxa_tile_w = (float)elem->IntAttribute("TileW");
		*pPxa_tile_h = (float)elem->IntAttribute("TileH");
		bInterArea = elem->BoolAttribute("InterArea");
		pDrawWnd.UpdateGrid();
	}
	//寻找Pxa元素
	elem = nullptr;
	for (tinyxml2::XMLElement* pElem = xmlDoc.FirstChildElement(); pElem; pElem = pElem->NextSiblingElement())
	{
		if (!strcmp(pElem->Name(), "Pxa"))
		{
			elem = pElem;
			break;
		}
	}
	if (elem == nullptr)
	{
		CString err;
		err.Format(L"文件%s找不到Pxa元素", pxafile.GetString());
		MessageBox(err.GetString(), L"文件载入错误", MB_ICONWARNING);
		return;
	}
	//遍历所有的ID元素
	for (elem = elem->FirstChildElement(); elem; elem = elem->NextSiblingElement())
	{
		//跳过不是Rect的元素
		if (strcmp(elem->Name(), "ID"))
			continue;
		//给step赋值
		auto& step = *((CPXAEDITOR_DATATYPE_PXA*)undoRedo.GetStep(CPXAEDITOR_DATATYPE_PXA_STR));
		int x = elem->IntAttribute("x");
		int y = elem->IntAttribute("y");
		int pxa = elem->IntAttribute("pxa");
		step[MAKELONG(x, y)] = pxa;
	}
}

void CPxaEditor::StaticXMLLoad(CString xml, CPXAEDITOR_DATATYPE_PXA* pxaList, int* outTileW, int* outTileH, bool* outInterArea)
{
	std::vector<char> utf8_buff;
	UTF16ToUTF8(xml.GetString(), &utf8_buff);
	tinyxml2::XMLDocument xmlDoc;
	xmlDoc.Parse(utf8_buff.data());
	tinyxml2::XMLElement* elem = nullptr;
	//寻找TileSet元素
	for (tinyxml2::XMLElement* pElem = xmlDoc.FirstChildElement(); pElem; pElem = pElem->NextSiblingElement())
	{
		if (!strcmp(pElem->Name(), "TileSet"))
		{
			elem = pElem;
			break;
		}
	}
	if (elem)
	{
		//读取TileSet
		*outTileW = elem->IntAttribute("TileW");
		*outTileH = elem->IntAttribute("TileH");
		if (outInterArea)
			*outInterArea = elem->BoolAttribute("InterArea");
	}
	//寻找Pxa元素
	elem = nullptr;
	for (tinyxml2::XMLElement* pElem = xmlDoc.FirstChildElement(); pElem; pElem = pElem->NextSiblingElement())
	{
		if (!strcmp(pElem->Name(), "Pxa"))
		{
			elem = pElem;
			break;
		}
	}
	if (elem == nullptr)
	{
		CString err;
		err.Format(L"xml找不到Pxa元素");
		::MessageBox(nullptr, err.GetString(), L"文件载入错误", MB_ICONWARNING);
		return;
	}
	//遍历所有的ID元素
	for (elem = elem->FirstChildElement(); elem; elem = elem->NextSiblingElement())
	{
		//跳过不是Rect的元素
		if (strcmp(elem->Name(), "ID"))
			continue;
		//给step赋值
		auto& step = *pxaList;
		int x = elem->IntAttribute("x");
		int y = elem->IntAttribute("y");
		int pxa = elem->IntAttribute("pxa");
		step[MAKELONG(x, y)] = pxa;
	}
}

MyUndoRedo* CPxaEditor::GetMyUndoRedo()
{
	return &undoRedo;
}

CString CPxaEditor::XMLSaved()
{
	//写入xml文件
	tinyxml2::XMLDocument xmlDoc;
	//写入TileSet元素
	auto elem_tileSet = xmlDoc.NewElement("TileSet");
	elem_tileSet->SetAttribute("TileW", (int)(*pPxa_tile_w));
	elem_tileSet->SetAttribute("TileH", (int)(*pPxa_tile_h));
	elem_tileSet->SetAttribute("InterArea", bInterArea);
	xmlDoc.InsertEndChild(elem_tileSet);
	//写入Pxa元素
	auto elem_pxa = xmlDoc.NewElement("Pxa");
	xmlDoc.InsertEndChild(elem_pxa);
	//写入Pxa数据
	for (auto& p : saved)
	{
		if (p.first == 0 ||
			p.second == 0)
			continue;
		auto y = (int)HIWORD(p.first);
		auto x = (int)LOWORD(p.first);

		auto elem_tile = xmlDoc.NewElement("ID");
		elem_tile->SetAttribute("x", x);
		elem_tile->SetAttribute("y", y);
		elem_tile->SetAttribute("pxa", p.second);
		elem_pxa->InsertEndChild(elem_tile);
	}
	//写出到文件
	tinyxml2::XMLPrinter xmlPrinter;
	xmlDoc.Print(&xmlPrinter);
	std::vector<wchar_t> wchar_buff;
	UTF8ToUTF16(xmlPrinter.CStr(), &wchar_buff);
	return CString(wchar_buff.data());
}

void CPxaEditor::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	static_pxaList = (CStatic*)GetDlgItem(IDC_STATIC_PXALIST);
	DDX_Control(pDX, IDC_LIST_PNGLIST, listbox_pxaList);
	static_pxaEditor = (CStatic*)GetDlgItem(IDC_STATIC_PXAEDITOR);
}

int CPxaEditor::GetSelectPxaValue()
{
	auto& view = *pBrushWnd.GetMyView();
	return view.cursorX_selected + view.cursorY_selected * view.count_w;
}

void* CPxaEditor_Pxa_NewData()
{
	return new CPXAEDITOR_DATATYPE_PXA();
}
void* CPxaEditor_Pxa_NewCopyOfData(void* data)
{
	CPXAEDITOR_DATATYPE_PXA* pStep = (CPXAEDITOR_DATATYPE_PXA*)data;
	CPXAEDITOR_DATATYPE_PXA* pNewStep = new CPXAEDITOR_DATATYPE_PXA();
	*pNewStep = *pStep;
	return pNewStep;
}
void CPxaEditor_Pxa_ReleaseData(void* data)
{
	CPXAEDITOR_DATATYPE_PXA* pStep = (CPXAEDITOR_DATATYPE_PXA*)data;
	delete pStep;
}

BOOL CPxaEditor::OnInitDialog()
{
	CDialog::OnInitDialog();
	//载入快捷键
	LOADHOTKEY(IDR_ACC_PIDEDITOR);
	//设置应用程序图标
	auto hIcon = AfxGetApp()->LoadIcon(IDI_ICON_PXA);
	SetIcon(hIcon, true);
	//设置撤销重做功能
	MyUndoRedoDataOp op_pid;
	op_pid.NewData = CPxaEditor_Pxa_NewData;
	op_pid.NewCopyOfData = CPxaEditor_Pxa_NewCopyOfData;
	op_pid.ReleaseData = CPxaEditor_Pxa_ReleaseData;
	undoRedo.AddDataType(CPXAEDITOR_DATATYPE_PXA_STR, op_pid);
	//设置listbox_pxaList
	listbox_pxaList.SetMenu(IDR_CPXAEDITOR_RMENU, IDR_CPXAEDITOR_RMENU_NOSEL);
	//初始化子窗口
	pDrawWnd.pParentEditor = this;
	pDrawWnd.Create(IDD_CPXAEDITOR_DRAW, this);
	pDrawWnd.ShowWindow(SW_SHOW);
	pBrushWnd.pParentEditor = this;
	pBrushWnd.Create(IDD_CPXAEDITOR_BRUSH, this);
	//设置初始化
	pPxa_tile_w = &pDrawWnd.GetMyView()->grid_w;
	pPxa_tile_h = &pDrawWnd.GetMyView()->grid_h;
	showGrid = false;
	OnShowGrid();//启用网格
	showBk = false;
	OnShowBk();//启用透明背景
	//更新列表
	OnUpdateList();
	//重置窗口位置
	OnResetWndPos();
	//更新撤销重做菜单状态
	UpdateMenuState();
	//更新窗口标题
	UpdateWindowTitle();
	return 0;
}

MyView* CPxaEditor::GetBrushView()
{
	return pBrushWnd.GetMyView();
}

void CPxaEditor::OnCancel()
{
	if (Close())
		return;
	ShowWindow(SW_HIDE);
}

void CPxaEditor::OnEnterKey()
{
}

void CPxaEditor::OnShowWindow(BOOL bShow, UINT nStatus)
{
	CDialog::OnShowWindow(bShow, nStatus);
	auto mainEditor = (CMainEditor*)pMainEditor;
	if (bShow)
	{
		pBrushWnd.ShowWindow(SW_SHOW);
		mainEditor->GetMenu()->GetSubMenu(CMAINEDITOR_MENUINDEX_GAMEEDITOR)->CheckMenuItem(ID_PXA_EDITOR, MF_BYCOMMAND | MF_CHECKED);
	}
	else
	{
		pBrushWnd.ShowWindow(SW_HIDE);
		mainEditor->GetMenu()->GetSubMenu(CMAINEDITOR_MENUINDEX_GAMEEDITOR)->CheckMenuItem(ID_PXA_EDITOR, MF_BYCOMMAND | MF_UNCHECKED);
	}
}

BOOL CPxaEditor::PreTranslateMessage(MSG* pMsg)
{
	HOTKEYPROC;
}

void CPxaEditor::OnSize(UINT nType, int cx, int cy)
{
	CDialog::OnSize(nType, cx, cy);

	if (!static_pxaList)
		return;
	auto dpi = MyGetDPI();
	//贴图列表
	int x, y, w, h;
	x = DPISCALE(10);
	y = DPISCALE(10);
	w = DPISCALE(200);
	h = cy - DPISCALE(20);
	static_pxaList->MoveWindow(x, y, w, h);
	y += DPISCALE(20);
	h -= DPISCALE(20);
	listbox_pxaList.MoveWindow(x, y, w, h);
	//ID编辑器
	x = DPISCALE(220);
	y = DPISCALE(10);
	w = cx - DPISCALE(230);
	h = cy - DPISCALE(20);
	static_pxaEditor->MoveWindow(x, y, w, h);
	y += DPISCALE(20);
	h -= DPISCALE(20);
	w -= DPISCALE(1);
	pDrawWnd.MoveWindow(x, y, w, h);
}

void CPxaEditor::OnMoving(UINT fwSide, LPRECT pRect)
{
	CDialog::OnMoving(fwSide, pRect);
	OnResetWndPos();
}


void CPxaEditor::OnEditPxa()
{
	if (Close())
		return;
	int sel = listbox_pxaList.GetCurSel();
	CString name;
	listbox_pxaList.GetText(sel, name);
	CString filename;
	filename.Format(L"./data/pxa/%s", name.GetString());
	Load(filename);
}


void CPxaEditor::OnEditPng()
{
	int selIndex = listbox_pxaList.GetCurSel();
	if (selIndex < 0)
		return;
	wchar_t buff[MAX_PATH];
	CString filepath;
	GetModuleFileNameW(nullptr, buff, _countof(buff));
	filepath = buff;
	auto index = filepath.ReverseFind(L'\\');
	filepath.Delete(index, filepath.GetLength() - index);
	filepath.Append(L"\\data\\pxa\\");
	CString pngfile;

	listbox_pxaList.GetText(selIndex, pngfile);
	filepath.Append(pngfile);

	CString cmd;
	cmd.Format(L"explorer \"%s\"", filepath.GetString());
	MyWinExec(cmd.GetString());
}


void CPxaEditor::OnOpenFolder()
{
	std::vector<char> utf8_buff;
	wchar_t buff[MAX_PATH];
	CString filepath;
	GetModuleFileNameW(nullptr, buff, _countof(buff));
	filepath = buff;
	auto index = filepath.ReverseFind(L'\\');
	filepath.Delete(index, filepath.GetLength() - index);
	filepath.Append(L"\\data\\pxa\\");

	CString cmd;
	index = listbox_pxaList.GetCurSel();
	if (index >= 0)
	{
		CString pngfile;
		listbox_pxaList.GetText(index, pngfile);
		filepath.Append(pngfile);
		cmd.Format(L"explorer /select,%s", filepath.GetString());
	}
	else
	{
		cmd.Format(L"explorer %s", filepath.GetString());
	}
	MyWinExec(cmd.GetString());
}


void CPxaEditor::OnUpdateList()
{
	
	listbox_pxaList.ResetContent();

	CFileFind finder;
	bool rs = finder.FindFile(L"./data/pxa/*.png");
	while (rs)
	{
		rs = finder.FindNextFile();
		CString str = finder.GetFileName();
		listbox_pxaList.AddString(str);
	}
}


void CPxaEditor::OnOpenFile()
{
	
	if (Close())
		return;
	wchar_t buff[MAX_PATH];
	CString filepath;
	GetModuleFileNameW(nullptr, buff, _countof(buff));
	filepath = buff;
	auto index = filepath.ReverseFind(L'\\');
	filepath.Delete(index, filepath.GetLength() - index);
	filepath.Append(L"\\data\\pxa\\");
	CFileDialog fd(TRUE, TEXT(""), TEXT(""), OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, TEXT("图像文件(*.png)|*.png|所有文件(*.*)|*.*||"), this);
	fd.m_ofn.lpstrInitialDir = filepath.GetString();
	if (fd.DoModal() != IDOK)
		return;
	Load(fd.GetPathName());
	UpdateMenuState();
	UpdateWindowTitle();
}


void CPxaEditor::OnSaveFile()
{
	
	if (!IsLoaded())
		return;
	Save();
}


void CPxaEditor::OnCloseFile()
{
	Close();
}


void CPxaEditor::OnUndo()
{
	undoRedo.Undo();
	UpdateMenuState();
	UpdateWindowTitle();
	Draw();
}


void CPxaEditor::OnRedo()
{
	undoRedo.Redo();
	UpdateMenuState();
	UpdateWindowTitle();
	Draw();
}


void CPxaEditor::OnCopy()
{
	if (!IsLoaded())
		return;
	pxaCopy = pDrawWnd.GetCopyPxa();
}


void CPxaEditor::OnPaste()
{
	if (!IsLoaded())
		return;
	pDrawWnd.SetCopyPxa(pxaCopy);
	UpdateMenuState();
	UpdateWindowTitle();
	Draw();
}


void CPxaEditor::OnCut()
{
	if (!IsLoaded())
		return;
	pxaCopy = pDrawWnd.GetCopyPxa();
	pDrawWnd.SetCopyPxa(0);
	UpdateMenuState();
	UpdateWindowTitle();
	Draw();
}


void CPxaEditor::OnShowBk()
{
	
	if (showBk)
	{
		showBk = false;
		GetMenu()->GetSubMenu(CPXAEDITOR_MENUINDEX_OPTION)->CheckMenuItem(ID_SHOW_BK, MF_BYCOMMAND | MF_UNCHECKED);
	}
	else
	{
		showBk = true;
		GetMenu()->GetSubMenu(CPXAEDITOR_MENUINDEX_OPTION)->CheckMenuItem(ID_SHOW_BK, MF_BYCOMMAND | MF_CHECKED);
	}
	Draw();
}


void CPxaEditor::OnShowGrid()
{
	
	if (showGrid)
	{
		showGrid = false;
		GetMenu()->GetSubMenu(CPXAEDITOR_MENUINDEX_OPTION)->CheckMenuItem(ID_SHOW_GRID, MF_BYCOMMAND | MF_UNCHECKED);
	}
	else
	{
		showGrid = true;
		GetMenu()->GetSubMenu(CPXAEDITOR_MENUINDEX_OPTION)->CheckMenuItem(ID_SHOW_GRID, MF_BYCOMMAND | MF_CHECKED);
	}
	Draw();
}


void CPxaEditor::OnGridSetting()
{
	CPxaEditorGrid dlg;
	dlg.outGridW = (int)(*pPxa_tile_w);
	dlg.outGridH = (int)(*pPxa_tile_h);
	dlg.outInterArea = bInterArea;
	if (dlg.DoModal() != IDOK)
		return;
	*pPxa_tile_w = (float)dlg.outGridW;
	*pPxa_tile_h = (float)dlg.outGridH;
	bInterArea = dlg.outInterArea;
	pDrawWnd.UpdateGrid();
	UpdateWindowTitle();
}


void CPxaEditor::OnBrushWnd()
{
	pBrushWnd.ShowWindow(pBrushWnd.IsWindowVisible() ? SW_HIDE : SW_SHOW);
}


void CPxaEditor::OnResetWndPos()
{
	CRect rcDst, rcSrc;
	GetWindowRect(rcDst);
	pBrushWnd.GetWindowRect(rcSrc);
	MoveToNeighborRect(rcDst, rcSrc, 1, 0);
	::MoveWindow(&pBrushWnd, rcSrc.left, rcSrc.top);
}

void CPxaEditor::OnLbnDblclkListPnglist()
{
	int selIndex = listbox_pxaList.GetCurSel();
	if (selIndex < 0)
		return;
	OnEditPxa();
}

void CPxaEditor::StepCopyToSaved()
{
	saved = *((CPXAEDITOR_DATATYPE_PXA*)undoRedo.GetStep(CPXAEDITOR_DATATYPE_PXA_STR));
	pxa_tile_w_saved = (int)(*pPxa_tile_w);
	pxa_tile_h_saved = (int)(*pPxa_tile_h);
	bInterArea_saved = bInterArea;
}
