/*******************************************************************************
  TPI - flexible but useless plug-in framework.
  Copyright (C) 2002-2009 Silky

  This library is free software; you can redistribute it and/or modify it under
  the terms of the GNU Lesser General Public License as published by the Free
  Software Foundation; either version 2.1 of the License, or (at your option)
  any later version.

  This library is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
  for more details.

  You should have received a copy of the GNU Lesser General Public License along
  with this library; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

  $Id: frm_main.cpp 151 2009-11-22 12:53:02Z sirakaba $
*******************************************************************************/

#include "lychee.h"

#include "frm_main.h"
#include "cls_filedroptarget.h"
#include "dlg_make.h"
#include "dlg_process.h"
#include "functions.h"

#include <wx/arrimpl.cpp>

WX_DEFINE_OBJARRAY(ArrayTPI_FILEINFO);

#define SetMenuToolState(id, state) this->toolbar->EnableTool(XRCID(id), state); this->menubar->Enable(XRCID(id), state)

//******************************************************************************
//    グローバル変数
//******************************************************************************

wxImageList g_hIconT(16, 16), g_hIconLL(32, 32), g_hIconLS(16, 16);
int g_nSortColumn;
bool g_fSortAscend;

//******************************************************************************
// MainFrame
//******************************************************************************

MainFrame::MainFrame(): wxFrame(), conf(wxEmptyString, wxEmptyString, FE_DIR_BIN wxT("lychee.conf"), wxEmptyString, wxCONFIG_USE_LOCAL_FILE | wxCONFIG_USE_RELATIVE_PATH)
{
}

MainFrame::~MainFrame()
{
	wxCommandEvent e;
	this->OnArcClose(e);

	// 設定を記録。
	if (! this->IsIconized() && ! this->IsMaximized())
	{
		int a, b;
		this->GetSize(& a, & b);
		this->conf.Write(wxT("Window-Width"), a);
		this->conf.Write(wxT("Window-Height"), b);
		this->GetPosition(& a, & b);
		this->conf.Write(wxT("Window-X"), a);
		this->conf.Write(wxT("Window-Y"), b);
	}
	this->conf.Write(wxT("Splitter-Pos"), this->window_splitter->GetSashPosition());

	// ツールバー/ステータスバー関連。
	this->conf.Write(wxT("StatusBar-Show"), this->statusbar->IsShown());
	this->conf.Write(wxT("ToolBar-Show"),   this->toolbar->IsShown());

	// ListView関連。
	this->conf.Write(wxT("ListView-IconMode"), this->menubar->IsChecked(XRCID("Exe_View_Icons")) ? 1 : this->menubar->IsChecked(XRCID("Exe_View_List")) ? 2 : 0);
	if (this->menubar->IsChecked(XRCID("Exe_View_Details")))
	{
		this->conf.Write(wxT("ListView-C-Filename"), this->list_ctrl->GetColumnWidth(0));
		this->conf.Write(wxT("ListView-C-Unpacked"), this->list_ctrl->GetColumnWidth(1));
		this->conf.Write(wxT("ListView-C-Packed"), this->list_ctrl->GetColumnWidth(2));
		this->conf.Write(wxT("ListView-C-Ratio"), this->list_ctrl->GetColumnWidth(3));
		this->conf.Write(wxT("ListView-C-Method"), this->list_ctrl->GetColumnWidth(4));
		this->conf.Write(wxT("ListView-C-Attr"), this->list_ctrl->GetColumnWidth(5));
		this->conf.Write(wxT("ListView-C-Lastmodified"), this->list_ctrl->GetColumnWidth(6));
		this->conf.Write(wxT("ListView-C-Path"), this->list_ctrl->GetColumnWidth(7));
		this->conf.Write(wxT("ListView-C-Type"), this->list_ctrl->GetColumnWidth(8));
		this->conf.Write(wxT("ListView-C-No"), this->list_ctrl->GetColumnWidth(9));
		this->conf.Write(wxT("ListView-SortColumn"), g_nSortColumn);
		this->conf.Write(wxT("ListView-SortAscend"), g_fSortAscend);
	}

	this->Close(true);
}

//******************************************************************************
// Event Table.
//******************************************************************************

BEGIN_EVENT_TABLE(MainFrame, wxFrame)
	EVT_INIT_DIALOG(      MainFrame::OnInit)
	// Menu
	EVT_MENU(XRCID("Arc_Create"),  MainFrame::OnArcCreate)
	EVT_MENU(XRCID("Arc_Open"),    MainFrame::OnArcOpen)
	EVT_MENU(XRCID("Arc_Close"),   MainFrame::OnArcClose)
	EVT_MENU(XRCID("Arc_Add"),     MainFrame::OnArcAdd)
	EVT_MENU(XRCID("Arc_SFX"),     MainFrame::OnArcConvert)
	EVT_MENU(XRCID("Arc_UnSFX"),   MainFrame::OnArcConvert)
	EVT_MENU(XRCID("Exe_Exit"),    MainFrame::OnExit)
	EVT_MENU(XRCID("Arc_Extract"), MainFrame::OnArcExtract)
	EVT_MENU(XRCID("Arc_Delete"),  MainFrame::OnArcDelete)
	EVT_MENU(XRCID("Arc_Test"),    MainFrame::OnArcTest)
	EVT_MENU(XRCID("Arc_Repair"),  MainFrame::OnArcRepair)
	EVT_MENU(XRCID("Exe_View_Icons"),  MainFrame::OnViewMode)
	EVT_MENU(XRCID("Exe_View_Details"),MainFrame::OnViewMode)
	EVT_MENU(XRCID("Exe_View_List"),   MainFrame::OnViewMode)
	EVT_MENU(XRCID("Exe_View_ToolBar"),MainFrame::OnShowToolBar)
	EVT_MENU(XRCID("Exe_View_StatusBar"),MainFrame::OnShowStatusBar)
	EVT_MENU(XRCID("Exe_View_SelectAll"),MainFrame::OnSelectAll)
	// TreeView
	EVT_TREE_SEL_CHANGED(XRCID("TreeView"), MainFrame::OnTreeChanged)
	EVT_TREE_BEGIN_DRAG( XRCID("TreeView"), MainFrame::OnTreeBeginDrag)
	// ListView
	EVT_LIST_ITEM_ACTIVATED(XRCID("ListView"), MainFrame::OnListItemDClick)
	EVT_LIST_BEGIN_DRAG(    XRCID("ListView"), MainFrame::OnListBeginDrag)
	// Filter
	EVT_TEXT(XRCID("tcFilter"), MainFrame::OnFilter)
END_EVENT_TABLE()

//******************************************************************************
// Event handler.
//******************************************************************************

void MainFrame::OnInit(wxInitDialogEvent&)
{
	// XRCと結びつけ。
	this->menubar    = this->GetMenuBar();
	this->toolbar    = this->GetToolBar();
	this->statusbar = XRCCTRL(* this, "statusbar", wxStatusBar);
	this->tree_ctrl = XRCCTRL(* this, "TreeView", wxTreeCtrl);
	this->list_ctrl = XRCCTRL(* this, "ListView", myListCtrl);
	this->window_splitter = XRCCTRL(* this, "window_splitter", wxSplitterWindow);
	this->tcFilter  = XRCCTRL(* this->toolbar, "tcFilter", wxTextCtrl);

	// 設定を読み込み。
	this->SetSize(this->conf.Read(wxT("Window-X"), 0l), this->conf.Read(wxT("Window-Y"), 0l), this->conf.Read(wxT("Window-Width"), 800), this->conf.Read(wxT("Window-Height"), 400));
	wxTheMimeTypesManager->Initialize(wxMAILCAP_ALL);

	// 初期値設定。
	{
		wxIcon icon;
		icon.CopyFromBitmap(wxBitmap(FE_DIR_S_ICO wxT("app.png"), wxBITMAP_TYPE_ANY));
		this->SetIcon(icon);
	}
	wxCommandEvent e;
	this->OnArcClose(e);

	// スプリッター設定。
	this->window_splitter->SetSashPosition(this->conf.Read(wxT("Splitter-Pos"), 200));

	// リストビュー設定。
	int nIconMode = this->conf.Read(wxT("ListView-IconMode"), 0l);
	e.SetId(nIconMode == 1 ? XRCID("Exe_View_Icons") : (nIconMode == 2 ? XRCID("Exe_View_List") : XRCID("Exe_View_Details")));
	this->OnViewMode(e);
	// wxGTKでは直接wxLC_VIRTUALを指定しないと反映されない。
	this->list_ctrl->SetSingleStyle(wxLC_VIRTUAL);
	this->list_ctrl->InsertColumn(0, wxT("Filename"),      wxLIST_FORMAT_LEFT,   this->conf.Read(wxT("ListView-C-Filename"), 140));
	this->list_ctrl->InsertColumn(1, wxT("Unpacked"),      wxLIST_FORMAT_RIGHT,  this->conf.Read(wxT("ListView-C-Unpacked"), 80));
	this->list_ctrl->InsertColumn(2, wxT("Packed"),        wxLIST_FORMAT_RIGHT,  this->conf.Read(wxT("ListView-C-Packed"), 80));
	this->list_ctrl->InsertColumn(3, wxT("Ratio"),         wxLIST_FORMAT_RIGHT,  this->conf.Read(wxT("ListView-C-Ratio"), 50));
	this->list_ctrl->InsertColumn(4, wxT("Method"),        wxLIST_FORMAT_LEFT,   this->conf.Read(wxT("ListView-C-Method"), 60));
	this->list_ctrl->InsertColumn(5, wxT("Attr"),          wxLIST_FORMAT_LEFT,   this->conf.Read(wxT("ListView-C-Attr"), 50));
	this->list_ctrl->InsertColumn(6, wxT("Last modified"), wxLIST_FORMAT_RIGHT,  this->conf.Read(wxT("ListView-C-Lastmodified"), 150));
	this->list_ctrl->InsertColumn(7, wxT("Path"),          wxLIST_FORMAT_LEFT,   this->conf.Read(wxT("ListView-C-Path"), 100));
	this->list_ctrl->InsertColumn(8, wxT("Type"),          wxLIST_FORMAT_LEFT,   this->conf.Read(wxT("ListView-C-Type"), 100));
	this->list_ctrl->InsertColumn(9, wxT("No."),           wxLIST_FORMAT_RIGHT,  this->conf.Read(wxT("ListView-C-No"), 35));
	g_nSortColumn = this->conf.Read(wxT("ListView-SortColumn"), 9);
	g_fSortAscend = this->conf.Read(wxT("ListView-SortAscend"), 1) == 1;
	this->list_ctrl->SetDropTarget(new myFileDropTarget(this));

	// ツールバー/ステータスバー設定。
	int nStatusBarParts[] = {70, 70, 180, 50, -1};
	this->statusbar->SetFieldsCount(5, nStatusBarParts);
	this->SetStatusBarPane(-1);
	bool fShow = this->conf.Read(wxT("StatusBar-Show"), 1) == 1;
	this->menubar->Check(XRCID("Exe_View_StatusBar"), fShow);
	this->statusbar->Show(fShow);
	fShow = this->conf.Read(wxT("ToolBar-Show"), 1) == 1;
	this->menubar->Check(XRCID("Exe_View_ToolBar"), fShow);
	this->toolbar->Show(fShow);

	// コマンドライン読み込み。
	this->cmdLine.SetSwitchChars(wxT("-"));
	this->cmdLine.AddSwitch(wxT("x"), wxEmptyString, wxT("(command) Extract filenames in archive."));
	this->cmdLine.AddSwitch(wxT("l"), wxEmptyString, wxT("(command) List archive(default)."));
	this->cmdLine.AddParam(wxT("archive"),   wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL);
	this->cmdLine.AddParam(wxT("filenames"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE);
	if (this->cmdLine.Parse() == 0)
	{
		if (this->cmdLine.GetParamCount() == 0)
		{
			return;
		}

		// 書庫を開く。
		this->fnArchive = wxFileName(this->cmdLine.GetParam(0));
		this->fnArchive.Normalize(wxPATH_NORM_ALL, this->szCurrentPath);
		this->OnArcOpen(e);
		if (this->cmdLine.Found(wxT("x")))
		{
			// 書庫を展開。
			this->OnArcExtract(e);
			this->Close(true);
		}
	}
}

// MenuBar

void MainFrame::OnExit(wxCommandEvent&)
{
	this->Close(true);
}

void MainFrame::OnArcCreate(wxCommandEvent& e)
{
	TPI_SWITCHES swInfo;
	swInfo.pCustomSwitches = NULL;

	// 作成ダイアログを設定。
	MakeDialog mkDlg;
	::wxXmlResource::Get()->Load(FE_DIR_S_XRC wxT("dlg_make.xrc"));
	::wxXmlResource::Get()->LoadDialog(& mkDlg, this, wxT("dlg_make"));

	if (e.GetClientData() == NULL)
	{
		// 処理対象のファイルを選択。
		wxFileDialog fd(this, wxT("Choose files to compress"), this->conf.Read(wxT("LastOpenPath"), ::wxGetCwd()));
		fd.SetWindowStyleFlag(wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE);
		if (fd.ShowModal() == wxID_CANCEL)
		{
			return;
		}
		swInfo.fnDestinationDirectory = wxFileName::DirName(fd.GetDirectory());
		this->conf.Write(wxT("LastOpenPath"), fd.GetDirectory());
		this->statusbar->SetStatusText(swInfo.fnDestinationDirectory.GetFullPath(), 4);

		fd.GetFilenames(mkDlg.files);
	}
	else
	{
		mkDlg.files = * (wxArrayString *) e.GetClientData();
		swInfo.fnDestinationDirectory = wxFileName::DirName(wxFileName(mkDlg.files[0]).GetPath());
		// 相対パスに変換。
		for (size_t n = 0; n < mkDlg.files.GetCount(); n++)
		{
			wxFileName fn(mkDlg.files[n]);
			bool fIsDir = fn.DirExists() && ! fn.FileExists();
			fn.MakeRelativeTo(swInfo.fnDestinationDirectory.GetPath());
			mkDlg.files[n] = fn.GetFullPath();
			if (fIsDir)
			{
				mkDlg.files[n] += fn.GetPathSeparator();
			}
		}
	}

	this->OnArcClose(e);
	mkDlg.InitDialog();
	mkDlg.cbDir->SetValue(swInfo.fnDestinationDirectory.GetPath());
	// 書庫名はファイル名の拡張子より前、もしくはディレクトリ名。
	this->fnArchive = wxFileName(mkDlg.files[0]);
	this->fnArchive.SetName(mkDlg.files.GetCount() == 1 ? (this->fnArchive.GetName().IsEmpty() ? this->fnArchive.GetDirs().Last() : this->fnArchive.GetName()) : swInfo.fnDestinationDirectory.GetDirs().Last());
	this->fnArchive.SetPath(swInfo.fnDestinationDirectory.GetPath());
	mkDlg.cbFileName->SetValue(this->fnArchive.GetName());

	// ダイアログを表示。
	if (mkDlg.ShowModal() == wxID_CANCEL)
	{
		this->statusbar->SetStatusText(wxEmptyString, 4);
		return;
	}
	this->statusbar->SetStatusText(wxEmptyString, 4);

	// 各種設定。
	swInfo.fStoreDirectoryPathes= ! mkDlg.cbIgnorePath->IsChecked();
	swInfo.fMakeSFX			    = mkDlg.cbMakeSFX->IsChecked();
	swInfo.fSolid               = mkDlg.cbSolid->IsChecked();
	swInfo.fMMOptimize          = mkDlg.cbMMOptimize->IsChecked();
	swInfo.fEncryptHeader       = mkDlg.cbEncryptHeader->IsChecked();
	swInfo.sCompressLevel       = mkDlg.scLevel->GetValue();
	swInfo.sRecoveryRecord      = mkDlg.scRR->GetValue();
	swInfo.szPassword           = mkDlg.tcPassword->GetValue();
	swInfo.szKeyFile            = mkDlg.tcKeyfile->GetValue();
	swInfo.szComment            = mkDlg.tcComment->GetValue();
	{
		wxULongLong_t ll;
		mkDlg.cbSplitSize->GetValue().ToULongLong(& ll);
		swInfo.llSplitSize      = ll;
	}

	// TPIを読み込み。
	int nSelected = mkDlg.chType->GetSelection();
	this->fnArchive = wxFileName(mkDlg.cbDir->GetValue(), mkDlg.cbFileName->GetValue(), swInfo.fMakeSFX ? EXE_EXT : mkDlg.afInfo[nSelected].szSuffix.BeforeFirst(wxT(';')));
	if (! tpi.InitLibrary(mkDlg.afInfo[nSelected].szTPIName, this->fnArchive.GetFullPath(), mkDlg.afInfo[nSelected].llTypeId))
	{
		::ErrDlg(wxT("InitLibrary()!"), this);
		return;
	}

	// コールバック関数を設定。
	if (! tpi.SetCallbackProc(TPICallbackProc))
	{
		::ErrDlg(wxT("SetCallbackProc()!"), this);
	}

	// 処理を行う。
	ProcessDialog procDlg;
	procDlg.InitDialog();
	procDlg.Show(true);
	if (! tpi.Command(TPI_COMMAND_ADD, & swInfo, this->fnArchive.GetFullPath(), mkDlg.files))
	{
		this->ErrorCheck(tpi.nErrorCode);
		return;
	}
	procDlg.Show(false);
	tpi.FreeLibrary();

	if (mkDlg.cbOpenAfter->IsChecked())
	{
		// 作成先を開く。
#ifdef __WINDOWS__
		::wxExecute(wxT("explorer ") + swInfo.fnDestinationDirectory.GetFullPath());
#endif
	}

	if (mkDlg.cbExitAfter->IsChecked())
	{
		// 終了。
		this->Close(true);
	}

	// 終了しない場合は書庫を開く。
	this->OnArcOpen(e);
}

void MainFrame::OnArcOpen(wxCommandEvent& e)
{
	// 書庫を選択。
	if (e.GetId() == XRCID("Arc_Open"))
	{
		wxFileDialog fd(this);
		fd.SetDirectory(this->conf.Read(wxT("LastOpenPath"), ::wxGetCwd()));
		fd.SetWindowStyleFlag(wxFD_OPEN | wxFD_FILE_MUST_EXIST);
		if (fd.ShowModal() == wxID_CANCEL)
		{
			return;
		}
		this->conf.Write(wxT("LastOpenPath"), fd.GetDirectory());
		this->fnArchive = wxFileName(fd.GetPath());
	}
	this->OnArcClose(e);

	// 進捗ダイアログ表示。
	ProcessDialog procDlg;
	procDlg.InitDialog();
	procDlg.Show(true);

	// TPIを読み込み、最初のコールバックを送信。
	TPI_PROCESSINFO piInfo;
	piInfo.uMessage = TPI_MESSAGE_STATUS;
	piInfo.uStatus = 0x1000;
	piInfo.llProcessedSize = 0;
	piInfo.fiInfo.fnFileName = this->fnArchive;
	piInfo.fiInfo.llUnpackedSize = this->LoadTPI(this->fnArchive.GetFullPath());
	if ((signed) piInfo.fiInfo.llUnpackedSize.ToULong() == -1)
	{
		procDlg.Show(false);
		tpi.FreeLibrary();
		::ErrDlg(wxT("No plug-in supporting this archive was found!"), this);
		return;
	}
	TPICallbackProc(TPI_NOTIFY_COMMON, & piInfo);

	// コールバック関数を設定。
	tpi.SetCallbackProc(TPICallbackProc);

	// 配列のサイズを確保。
	this->fileinfo.Alloc(piInfo.fiInfo.llUnpackedSize.ToULong());

	// 書庫を開く。
	if (! tpi.OpenArchive(this->fnArchive.GetFullPath()))
	{
		procDlg.Show(false);
		tpi.FreeLibrary();
		::ErrDlg(wxT("OpenArchive()!"), this);
		return;
	}

	// 書庫のアイコンを取得し、書庫ルートを作成。
	g_hIconT.Add(wxBitmap(FE_DIR_S_ICO wxT("folder_closed.png"), wxBITMAP_TYPE_ANY));
	g_hIconT.Add(wxBitmap(FE_DIR_S_ICO wxT("folder_open.png"), wxBITMAP_TYPE_ANY));
	this->tree_ctrl->SetImageList(& g_hIconT);
	wxTreeItemId
		idRoot = this->tree_ctrl->AddRoot(wxEmptyString),
#ifdef __WINDOWS__
		idArchive = this->tree_ctrl->AppendItem(idRoot, piInfo.fiInfo.fnFileName.GetFullName(), g_hIconT.Add(GetFileTypeIcon(piInfo.fiInfo.fnFileName))),
#else
		idArchive = this->tree_ctrl->AppendItem(idRoot, piInfo.fiInfo.fnFileName.GetFullName(), g_hIconT.Add(GetFileTypeIcon(piInfo.fiInfo.fnFileName).ConvertToImage().Rescale(16, 16))),
#endif
		idArcRoot = this->tree_ctrl->AppendItem(idRoot, wxT("-----"), 0, 1);

	// ファイル情報をロード。
	if (tpi.GetFileInformation(& piInfo.fiInfo, true))
	{
		piInfo.uStatus = 0x1001;
		do
		{
			piInfo.llProcessedSize++;
			if (this->ErrorCheck(TPICallbackProc(TPI_NOTIFY_COMMON, & piInfo)) == TPI_CALLBACK_CANCEL)
			{
				procDlg.Show(false);
				tpi.CloseArchive();
				wxCommandEvent e;
				this->OnArcClose(e);
				return;
			}

			// ツリービューに反映。
			TreeView_CheckNewerItem(this->tree_ctrl, idArcRoot, piInfo.fiInfo.fnFileName.GetPath(), true);

			// ディレクトリ属性を含むものについては除去。
			if (piInfo.fiInfo.dwAttribute & TPI_ATTRIBUTE_DIRECTORY)
			{
				continue;
			}

			// セキュリティチェック。
			// DTV検査。
			if (piInfo.fiInfo.fnFileName.GetPathWithSep().Find(wxT("..")) != wxNOT_FOUND)
			{
				piInfo.fiInfo.uDanger = TRUE;
				::WrnDlg(wxT("This archive may have Directory Traversal Vulnerability(DTV) problem, and some danger files may be extracted to the unexpected system directory! You should use the \"Ignore file pathes\" option when extracting this archive.\nDanger file is:\n") + piInfo.fiInfo.szStoredName, this);
			}
			// 空白の連続による拡張子偽装を検査。
			if (piInfo.fiInfo.fnFileName.GetFullName().Find(wxT("        ")) != wxNOT_FOUND)
			{
				piInfo.fiInfo.uDanger = TRUE;
				::WrnDlg(wxT("This archive may contain extension-disguised files whose real extension is hidden by using many blank charactor and you may mistake that it is a \"safe\" file. Don\'t execute these files carelessly.\nDanger file is:\n") + piInfo.fiInfo.szStoredName, this);
			}
			// Unicode制御文字を検査。
			for (wxChar c = 0x200c; c <= 0x206f; c++)
			{
				if (piInfo.fiInfo.fnFileName.GetFullName().Find(c) != wxNOT_FOUND)
				{
					piInfo.fiInfo.uDanger = TRUE;
					::WrnDlg(wxT("This archive may contain extension-disguised files whose real extension is hidden by using Unicode control character and you may mistake that it is a \"safe\" file. Don\'t execute these files carelessly.\nDanger file is:\n") + piInfo.fiInfo.szStoredName, this);
				}
				switch (c)
				{
				case 0x200f: c = 0x2027; break;
				case 0x202e: c = 0x2060; break;
				}
			}

			// 情報を保存してカウントアップ。
			this->fileinfo.Add(piInfo.fiInfo);
		}
		while (tpi.GetFileInformation(& piInfo.fiInfo, false));
	}

	// 書庫の情報を取得。
	TPI_ARCHIVEINFO aiInfo;
	if (! tpi.GetArchiveInformation(& aiInfo))
	{
		procDlg.Show(false);
		tpi.FreeLibrary();
		::ErrDlg(wxT("GetArchiveInformation()!"), this);
		return;
	}
	this->szComment = aiInfo.szComment;

	// 書庫を閉じる。
	if (! tpi.CloseArchive())
	{
		::ErrDlg(wxT("CloseArchive()!"), this);
	}

	// 以下、UI処理。
	this->fileinfo.Shrink();
	this->tree_ctrl->ExpandAll();
	this->tree_ctrl->ScrollTo(idArchive);
	this->tree_ctrl->SelectItem(idArchive);
	this->list_ctrl->atDangerItem.SetTextColour(* wxRED);

	// ステータスバー設定。
	this->statusbar->SetStatusText(aiInfo.fiInfo.szTypeName, 0);
	this->statusbar->SetStatusText(wxString::Format(wxT("%d file(s)"), this->fileinfo.GetCount()), 1);
	this->statusbar->SetStatusText(aiInfo.llUnpackedSize.ToString() + wxT(" B -> ") + aiInfo.llPackedSize.ToString() + wxT(" B"), 2);
	this->statusbar->SetStatusText(wxString::Format(wxT("%3.1f%%"), aiInfo.wCompressRatio / 10.0), 3);
	this->statusbar->SetStatusText(this->fnArchive.GetFullPath(), 4);

	// ツールバー・メニューバー設定。
	SetMenuToolState("Arc_Close",   true);
	SetMenuToolState("Arc_Add",     (aiInfo.fiInfo.llSupportedCommand & TPI_COMMAND_ADD)   == TPI_COMMAND_ADD   && aiInfo.fiInfo.fArchive);
	SetMenuToolState("Arc_SFX",     (aiInfo.fiInfo.llSupportedCommand & TPI_COMMAND_SFX)    == TPI_COMMAND_SFX   && aiInfo.nSFXType == 0);
	SetMenuToolState("Arc_UnSFX",   (aiInfo.fiInfo.llSupportedCommand & TPI_COMMAND_UNSFX)  == TPI_COMMAND_UNSFX && aiInfo.nSFXType != 0);
	SetMenuToolState("Arc_Extract", (aiInfo.fiInfo.llSupportedCommand & TPI_COMMAND_EXTRACT)== TPI_COMMAND_EXTRACT);
	SetMenuToolState("Arc_Delete",  (aiInfo.fiInfo.llSupportedCommand & TPI_COMMAND_DELETE) == TPI_COMMAND_DELETE && aiInfo.fiInfo.fArchive);
	SetMenuToolState("Arc_Test",    (aiInfo.fiInfo.llSupportedCommand & TPI_COMMAND_TEST)   == TPI_COMMAND_TEST);
	SetMenuToolState("Arc_Repair",  (aiInfo.fiInfo.llSupportedCommand & TPI_COMMAND_REPAIR) == TPI_COMMAND_REPAIR);

	procDlg.Show(false);
}

void MainFrame::OnArcClose(wxCommandEvent&)
{
	// ツリービュー・リストビュー設定。
	this->tree_ctrl->DeleteAllItems();
	this->list_ctrl->DeleteAllItems();
	this->list_ctrl->showFileInfo.Clear();

	// ツールバー・メニューバー設定。
	SetMenuToolState("Arc_Close",   false);
	SetMenuToolState("Arc_Add",     false);
	SetMenuToolState("Arc_SFX",     false);
	SetMenuToolState("Arc_UnSFX",   false);
	SetMenuToolState("Arc_Extract", false);
	SetMenuToolState("Arc_Delete",  false);
	SetMenuToolState("Arc_Test",    false);
	SetMenuToolState("Arc_Repair",  false);

	for (int i = 0; i < this->statusbar->GetFieldsCount(); i++)
	{
		this->statusbar->SetStatusText(wxEmptyString, i);
	}
	this->fileinfo.Clear();
	this->szComment.Clear();

	g_hIconT.RemoveAll();
	g_hIconLL.RemoveAll();
	g_hIconLS.RemoveAll();
	this->tpi.FreeLibrary();
}

void MainFrame::OnArcAdd(wxCommandEvent& e)
{
	// 処理対象のファイルを選択。
	wxArrayString files;
	wxFileDialog fd(this, wxT("Choose files to add"), this->conf.Read(wxT("LastOpenPath"), ::wxGetCwd()));
	fd.SetWindowStyleFlag(wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE);
	if (fd.ShowModal() == wxID_CANCEL)
	{
		return;
	}
	fd.GetFilenames(files);
	this->conf.Write(wxT("LastOpenPath"), fd.GetDirectory());

	// 各種設定。
	TPI_SWITCHES swInfo;
	swInfo.fnDestinationDirectory = wxFileName::DirName(fd.GetDirectory());
	swInfo.fMakeSFX = false;
	swInfo.pCustomSwitches = NULL;

	ProcessDialog procDlg;
	procDlg.InitDialog();
	procDlg.Show(true);
	if (! this->tpi.Command(TPI_COMMAND_ADD, & swInfo, this->fnArchive.GetFullPath(), files))
	{
		this->ErrorCheck(tpi.nErrorCode);
	}
	procDlg.Show(false);

	// 書庫を再読み込み。
	this->OnArcOpen(e);
}

void MainFrame::OnArcConvert(wxCommandEvent& e)
{
	TPI_SWITCHES swInfo;
	swInfo.fMakeSFX = e.GetId() == XRCID("Arc_SFX");

	// 保存先を尋ねる。
	wxFileDialog fd(this, swInfo.fMakeSFX ? wxT("Save as SFX") : wxT("Save as normal archive"), this->fnArchive.GetPath(), this->fnArchive.GetName() + (swInfo.fMakeSFX ? EXE_EXT : (wxString) wxEmptyString));
	fd.SetWindowStyleFlag(wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
	if (fd.ShowModal() == wxID_CANCEL)
	{
		return;
	}
	swInfo.fnDestinationDirectory = wxFileName::DirName(fd.GetDirectory());
	this->conf.Write(wxT("LastOpenPath"), fd.GetDirectory());

	wxArrayString files;
	files.Add(fd.GetPath());

	ProcessDialog procDlg;
	procDlg.InitDialog();
	procDlg.Show(true);
	if (! this->tpi.Command(swInfo.fMakeSFX ? TPI_COMMAND_SFX : TPI_COMMAND_UNSFX, & swInfo, this->fnArchive.GetFullPath(), files))
	{
		this->ErrorCheck(tpi.nErrorCode);
	}
	procDlg.Show(false);
}

void MainFrame::OnArcExtract(wxCommandEvent& e)
{
	TPI_SWITCHES swInfo;
	swInfo.pCustomSwitches = NULL;

	// モード取得。通常は0, 実行なら1, ファイルDnDなら2、ディレクトリDnDなら3。
	int nMode = e.GetInt();
	// 実行時のみ使用。
	wxFileType * ftFile = NULL;

	// 展開ダイアログを作成。DnDまたは実行時は表示しない。
	MakeDialog mkDlg;
	::wxXmlResource::Get()->Load(FE_DIR_S_XRC wxT("dlg_make.xrc"));
	::wxXmlResource::Get()->LoadDialog(& mkDlg, this, wxT("dlg_make"));
	mkDlg.bIsMake = false;
	mkDlg.files   = MakeTargetFileList(this, nMode == 1);

	if (nMode != 0)
	{
		if (nMode == 1)
		{
			// コマンドを取得。
			ftFile = wxTheMimeTypesManager->GetFileTypeFromExtension(wxFileName(mkDlg.files[0]).GetExt());
			if (! ftFile)
			{
				// 種類が取得できないときは設定を読み込む。初期設定ではテキストとみなす。
				ftFile = wxTheMimeTypesManager->GetFileTypeFromExtension(this->conf.Read(wxT("DefaultExt"), wxT("txt")));
				if (! ftFile)
				{
					::ErrDlg(wxT("Unable to get the file type!"), this);
					return;
				}
			}
		}

		// 作業ディレクトリ作成。
		swInfo.fStoreDirectoryPathes = false;
		wxString szDestDirBase = nMode == 3 ? this->tree_ctrl->GetItemText(this->tree_ctrl->GetSelection()) : wxT("tpi_tmp");
		if (szDestDirBase == wxT("-----"))
		{
			// 書庫ルートのときは書庫名にしておく。
			szDestDirBase = this->fnArchive.GetName();
		}
		swInfo.fnDestinationDirectory = MakeDirPath(wxFileName::DirName(::wxGetCwd()), szDestDirBase, true);
		if (! swInfo.fnDestinationDirectory.IsOk())
		{
			::ErrDlg(wxT("Unable to make the temporary directory!"), this);
			return;
		}
	}
	else
	{
		mkDlg.InitDialog();
		if (mkDlg.ShowModal() == wxID_CANCEL)
		{
			return;
		}

		// 各種設定。
		swInfo.fStoreDirectoryPathes = ! mkDlg.cbIgnorePath->IsChecked();
		swInfo.fnDestinationDirectory = wxFileName::DirName(mkDlg.cbDir->GetValue());
		swInfo.szPassword = mkDlg.tcPassword->GetValue();
		swInfo.szKeyFile  = mkDlg.tcKeyfile->GetValue();

		// 必要なら書庫名でディレクトリを作成する。
		if (WillMakeDirByArcName(this, & mkDlg))
		{
			swInfo.fnDestinationDirectory = MakeDirPath(swInfo.fnDestinationDirectory, this->fnArchive.GetName(), true);
			if (! swInfo.fnDestinationDirectory.IsOk())
			{
				::ErrDlg(wxT("Unable to make the destination directory!"), this);
				return;
			}
		}
	}

	ProcessDialog procDlg;
	procDlg.InitDialog();
	procDlg.Show(true);
	if (! this->tpi.Command(TPI_COMMAND_EXTRACT, & swInfo, this->fnArchive.GetFullPath(), mkDlg.files))
	{
		this->ErrorCheck(tpi.nErrorCode);
	}
	procDlg.Show(false);

	if (nMode == 0)
	{
		if (mkDlg.cbOpenAfter->IsChecked())
		{
			// 展開先を開く。
#ifdef __WINDOWS__
			::wxExecute(wxT("explorer ") + swInfo.fnDestinationDirectory.GetFullPath());
#endif
		}

		if (mkDlg.cbExitAfter->IsChecked())
		{
			// 終了。
			this->Close(true);
		}
	}
	else
	{
		wxArrayString asFiles;
		if (nMode == 1)
		{
			// コマンドを実行。
			asFiles.Add(swInfo.fnDestinationDirectory.GetPathWithSep() + wxFileName(mkDlg.files[0]).GetFullName());
			if (tpi.nErrorCode == TPI_ERROR_SUCCESS)
			{
#ifdef __LINUX__
				// Linuxでは引用符で囲む必要がある。
				::wxExecute(ftFile->GetOpenCommand(wxT('"') + asFiles[0] + wxT('"')), wxEXEC_SYNC);
#else
				::wxExecute(ftFile->GetOpenCommand(asFiles[0]), wxEXEC_SYNC);
#endif
			}
		}
		else
		{
			// 展開対象を決定。
			wxFileDataObject objFile;
			for (size_t i = 0; i < mkDlg.files.GetCount(); i++)
			{
				wxString szFileName = swInfo.fnDestinationDirectory.GetPathWithSep() + wxFileName(mkDlg.files[i]).GetFullName();
				if (nMode == 2)
				{
					// リストに追加。
					objFile.AddFile(szFileName);
				}
				asFiles.Add(szFileName);
			}
			if (nMode == 3)
			{
				objFile.AddFile(swInfo.fnDestinationDirectory.GetPath());
			}

			// DnD開始。
			wxDropSource dropSource(objFile, this);
			if (dropSource.DoDragDrop() != wxDragMove)
			{
#ifdef __LINUX__
				// Linuxではまだ処理が終わっていない(コンテキストメニューが表示されている)ので、とりあえず3秒だけ待つ。
				sleep(3);
#endif
			}
		}

		// ファイルと一時ディレクトリを削除。
		for (size_t i = 0; i < asFiles.GetCount(); i++)
		{
			::wxRemoveFile(asFiles[i]);
		}
		::wxRmdir(swInfo.fnDestinationDirectory.GetFullPath());
	}
}

void MainFrame::OnArcDelete(wxCommandEvent& e)
{
	// 全ファイル削除は危険ではないかと。
	if (this->list_ctrl->GetSelectedItemCount() == 0)
	{
		return;
	}

	if (::AskDlg(wxT("Are you sure to delete selected files?"), this) == wxNO)
	{
		return;
	}

	// 各種設定。
	TPI_SWITCHES swInfo;
	ProcessDialog procDlg;
	procDlg.InitDialog();
	procDlg.Show(true);
	if (! this->tpi.Command(TPI_COMMAND_DELETE, & swInfo, this->fnArchive.GetFullPath(), MakeTargetFileList(this, false)))
	{
		this->ErrorCheck(tpi.nErrorCode);
	}
	procDlg.Show(false);	

	// 書庫を再読み込みする。
	this->OnArcOpen(e);
}

void MainFrame::OnArcTest(wxCommandEvent&)
{
	TPI_SWITCHES swInfo;
	ProcessDialog procDlg;
	procDlg.InitDialog();
	procDlg.Show(true);
	if (this->tpi.Command(TPI_COMMAND_TEST, & swInfo, this->fnArchive.GetFullPath(), MakeTargetFileList(this, false)))
	{
		::MsgDlg(wxT("This is a correct archive."), & procDlg, wxICON_INFORMATION);
	}
	else
	{
		this->ErrorCheck(tpi.nErrorCode);
	}
	procDlg.Show(false);
}

void MainFrame::OnArcRepair(wxCommandEvent&)
{
	TPI_SWITCHES swInfo;
	ProcessDialog procDlg;
	procDlg.InitDialog();
	procDlg.Show(true);
	if (! this->tpi.Command(TPI_COMMAND_REPAIR, & swInfo, this->fnArchive.GetFullPath(), MakeTargetFileList(this, false)))
	{
		this->ErrorCheck(tpi.nErrorCode);
	}
	procDlg.Show(false);	
}

void MainFrame::OnViewMode(wxCommandEvent & e)
{
	int n = e.GetId();
	this->menubar->Check(n, true);
	this->list_ctrl->SetSingleStyle(wxLC_REPORT, n == XRCID("Exe_View_Details"));
	this->list_ctrl->SetSingleStyle(wxLC_ICON,   n == XRCID("Exe_View_Icons"));
	this->list_ctrl->SetSingleStyle(wxLC_LIST,   n == XRCID("Exe_View_List"));
}

void MainFrame::OnShowToolBar(wxCommandEvent & e)
{
	this->toolbar->Show(e.IsChecked());
}

void MainFrame::OnShowStatusBar(wxCommandEvent & e)
{
	this->statusbar->Show(e.IsChecked());
}

void MainFrame::OnSelectAll(wxCommandEvent &)
{
	for (int i = 0; i < this->list_ctrl->GetItemCount(); i++)
	{
		this->list_ctrl->Select(i, true);
	}
}

// TreeView

void MainFrame::OnTreeChanged(wxTreeEvent& e)
{
	// ツリービューからパスを取得。
	wxString szNodePath = TreeView_GetItemPath(this->tree_ctrl, e.GetItem());
	// リストビューを初期化。
	this->list_ctrl->showFileInfo.Clear();
	this->list_ctrl->DeleteAllItems();
	g_hIconLL.RemoveAll();
	g_hIconLS.RemoveAll();

	// 現在のアイテムの選択状態を無効にしておく。
	long nSelected = this->list_ctrl->GetFirstSelected();
	while (nSelected != -1)
	{
		this->list_ctrl->Select(nSelected, false);
		nSelected = this->list_ctrl->GetNextSelected(nSelected);
	}

	// アイコン設定。
	this->list_ctrl->SetImageList(& g_hIconLL, wxIMAGE_LIST_NORMAL);
	this->list_ctrl->SetImageList(& g_hIconLS, wxIMAGE_LIST_SMALL);

	// 配列と比較し、パスが一致しなければ消す。
	for (size_t i = 0; i < this->fileinfo.GetCount(); i++)
	{
		// パスを比較。
		if (szNodePath == wxT("*") || szNodePath == this->fileinfo[i].fnFileName.GetPath())
		{
			// 項目がフォルダであるなら無視。
			if (this->fileinfo[i].fnFileName.IsDir() || ! TreeView_CheckNewerItem(this->tree_ctrl, this->tree_ctrl->GetLastChild(this->tree_ctrl->GetRootItem()), this->fileinfo[i].fnFileName.GetFullPath(), false))
			{
				continue;
			}

			// フィルタにかからなければ無視。
			if (this->fileinfo[i].fnFileName.GetFullName().MakeLower().Find(this->tcFilter->GetValue().MakeLower()) == wxNOT_FOUND)
			{
				continue;
			}

			this->list_ctrl->showFileInfo.Add(this->fileinfo[i]);
		}
	}

	// ソートして表示。
	this->list_ctrl->showFileInfo.Sort(& ListCtrlCompareProc);
	this->list_ctrl->SetItemCount(this->list_ctrl->showFileInfo.GetCount());
}

void MainFrame::OnTreeBeginDrag(wxTreeEvent& e)
{
	// TODO : アイテムが子階層を持っていても展開できない。
	this->tree_ctrl->SelectItem(e.GetItem());

	wxCommandEvent e1;
	e1.SetInt(3);
	this->OnArcExtract(e1);
}

// ListView

void MainFrame::OnListItemDClick(wxListEvent&)
{
	wxCommandEvent e;
	e.SetInt(1);
	this->OnArcExtract(e);
}

void MainFrame::OnListBeginDrag(wxListEvent&)
{
	if (this->list_ctrl->GetSelectedItemCount() == 0)
	{
		// アイテムを選択せずドラッグしようとした場合。
		return;
	}

	wxCommandEvent e;
	e.SetInt(2);
	this->OnArcExtract(e);
}

// Filter

void MainFrame::OnFilter(wxCommandEvent&)
{
	wxTreeEvent e;
	e.SetItem(this->tree_ctrl->GetSelection());
	this->OnTreeChanged(e);
}

// イベントハンドラ以外。

int MainFrame::LoadTPI(wxString szFileName)
{
	// TPIを読み込み。
	wxFileSystem fs;
	fs.ChangePathTo(FE_DIR_B_LIB, true);
	wxString szTPIName = fs.FindFirst(wxT("*" TPI_EXT), wxFILE);
	int nFileCount = -1;
	while (! szTPIName.IsEmpty())
	{
		// 対応確認。
		if (! tpi.InitLibrary(szTPIName, szFileName, 0) || ! tpi.CheckArchive(szFileName, & nFileCount) || nFileCount < 0)
		{
			tpi.FreeLibrary();
			szTPIName = fs.FindNext();
			continue;
		}
		break;
	}
	return nFileCount;
}

int MainFrame::ErrorCheck(int nErrorCode)
{
	switch (nErrorCode)
	{
	case TPI_ERROR_SUCCESS:
	case TPI_CALLBACK_CONTINUE:
		break;
	case TPI_ERROR_D_UNSUPPORTED:
		::ErrDlg(wxT("Sorry, this function is not supported yet."), this);
		break;
	case TPI_ERROR_D_SKIPPED:
	case TPI_CALLBACK_CANCEL:
		::ErrDlg(wxT("This operation is canceled by the user."), this);
		break;
	default:
		::ErrDlg(wxT("Error code is ") + wxString::Format(wxT("%d."), nErrorCode), this);
	}
	return nErrorCode;
}
