Straw-man for dev process
[novacoin.git] / ui.cpp
diff --git a/ui.cpp b/ui.cpp
index d1163aa..1cb922f 100644 (file)
--- a/ui.cpp
+++ b/ui.cpp
-// Copyright (c) 2009-2010 Satoshi Nakamoto\r
-// Distributed under the MIT/X11 software license, see the accompanying\r
-// file license.txt or http://www.opensource.org/licenses/mit-license.php.\r
-\r
-#include "headers.h"\r
-#ifdef _MSC_VER\r
-#include <crtdbg.h>\r
-#endif\r
-\r
-void ThreadRequestProductDetails(void* parg);\r
-void ThreadRandSendTest(void* parg);\r
-bool GetStartOnSystemStartup();\r
-void SetStartOnSystemStartup(bool fAutoStart);\r
-\r
-\r
-\r
-DEFINE_EVENT_TYPE(wxEVT_UITHREADCALL)\r
-DEFINE_EVENT_TYPE(wxEVT_REPLY1)\r
-DEFINE_EVENT_TYPE(wxEVT_REPLY2)\r
-DEFINE_EVENT_TYPE(wxEVT_REPLY3)\r
-\r
-CMainFrame* pframeMain = NULL;\r
-CMyTaskBarIcon* ptaskbaricon = NULL;\r
-map<string, string> mapAddressBook;\r
-bool fRandSendTest = false;\r
-void RandSend();\r
-extern int g_isPainting;\r
-bool fClosedToTray = false;\r
-\r
-// Settings\r
-int fShowGenerated = true;\r
-int fMinimizeToTray = true;\r
-int fMinimizeOnClose = true;\r
-\r
-\r
-\r
-\r
-\r
-\r
-\r
-//////////////////////////////////////////////////////////////////////////////\r
-//\r
-// Util\r
-//\r
-\r
-void HandleCtrlA(wxKeyEvent& event)\r
-{\r
-    // Ctrl-a select all\r
-    wxTextCtrl* textCtrl = (wxTextCtrl*)event.GetEventObject();\r
-    if (event.GetModifiers() == wxMOD_CONTROL && event.GetKeyCode() == 'A')\r
-        textCtrl->SetSelection(-1, -1);\r
-    event.Skip();\r
-}\r
-\r
-bool Is24HourTime()\r
-{\r
-    //char pszHourFormat[256];\r
-    //pszHourFormat[0] = '\0';\r
-    //GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_ITIME, pszHourFormat, 256);\r
-    //return (pszHourFormat[0] != '0');\r
-    return true;\r
-}\r
-\r
-string DateStr(int64 nTime)\r
-{\r
-    // Can only be used safely here in the UI\r
-    return (string)wxDateTime((time_t)nTime).FormatDate();\r
-}\r
-\r
-string DateTimeStr(int64 nTime)\r
-{\r
-    // Can only be used safely here in the UI\r
-    wxDateTime datetime((time_t)nTime);\r
-    if (Is24HourTime())\r
-        return (string)datetime.Format("%x %H:%M");\r
-    else\r
-        return (string)datetime.Format("%x ") + itostr((datetime.GetHour() + 11) % 12 + 1) + (string)datetime.Format(":%M %p");\r
-}\r
-\r
-wxString GetItemText(wxListCtrl* listCtrl, int nIndex, int nColumn)\r
-{\r
-    // Helper to simplify access to listctrl\r
-    wxListItem item;\r
-    item.m_itemId = nIndex;\r
-    item.m_col = nColumn;\r
-    item.m_mask = wxLIST_MASK_TEXT;\r
-    if (!listCtrl->GetItem(item))\r
-        return "";\r
-    return item.GetText();\r
-}\r
-\r
-int InsertLine(wxListCtrl* listCtrl, const wxString& str0, const wxString& str1)\r
-{\r
-    int nIndex = listCtrl->InsertItem(listCtrl->GetItemCount(), str0);\r
-    listCtrl->SetItem(nIndex, 1, str1);\r
-    return nIndex;\r
-}\r
-\r
-int InsertLine(wxListCtrl* listCtrl, const wxString& str0, const wxString& str1, const wxString& str2, const wxString& str3, const wxString& str4)\r
-{\r
-    int nIndex = listCtrl->InsertItem(listCtrl->GetItemCount(), str0);\r
-    listCtrl->SetItem(nIndex, 1, str1);\r
-    listCtrl->SetItem(nIndex, 2, str2);\r
-    listCtrl->SetItem(nIndex, 3, str3);\r
-    listCtrl->SetItem(nIndex, 4, str4);\r
-    return nIndex;\r
-}\r
-\r
-int InsertLine(wxListCtrl* listCtrl, void* pdata, const wxString& str0, const wxString& str1, const wxString& str2, const wxString& str3, const wxString& str4)\r
-{\r
-    int nIndex = listCtrl->InsertItem(listCtrl->GetItemCount(), str0);\r
-    listCtrl->SetItemPtrData(nIndex, (wxUIntPtr)pdata);\r
-    listCtrl->SetItem(nIndex, 1, str1);\r
-    listCtrl->SetItem(nIndex, 2, str2);\r
-    listCtrl->SetItem(nIndex, 3, str3);\r
-    listCtrl->SetItem(nIndex, 4, str4);\r
-    return nIndex;\r
-}\r
-\r
-void SetSelection(wxListCtrl* listCtrl, int nIndex)\r
-{\r
-    int nSize = listCtrl->GetItemCount();\r
-    long nState = (wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED);\r
-    for (int i = 0; i < nSize; i++)\r
-        listCtrl->SetItemState(i, (i == nIndex ? nState : 0), nState);\r
-}\r
-\r
-int GetSelection(wxListCtrl* listCtrl)\r
-{\r
-    int nSize = listCtrl->GetItemCount();\r
-    for (int i = 0; i < nSize; i++)\r
-        if (listCtrl->GetItemState(i, wxLIST_STATE_FOCUSED))\r
-            return i;\r
-    return -1;\r
-}\r
-\r
-\r
-string HtmlEscape(const char* psz, bool fMultiLine=false)\r
-{\r
-    int len = 0;\r
-    for (const char* p = psz; *p; p++)\r
-    {\r
-             if (*p == '<') len += 4;\r
-        else if (*p == '>') len += 4;\r
-        else if (*p == '&') len += 5;\r
-        else if (*p == '"') len += 6;\r
-        else if (*p == ' ' && p > psz && p[-1] == ' ' && p[1] == ' ') len += 6;\r
-        else if (*p == '\n' && fMultiLine) len += 5;\r
-        else\r
-            len++;\r
-    }\r
-    string str;\r
-    str.reserve(len);\r
-    for (const char* p = psz; *p; p++)\r
-    {\r
-             if (*p == '<') str += "&lt;";\r
-        else if (*p == '>') str += "&gt;";\r
-        else if (*p == '&') str += "&amp;";\r
-        else if (*p == '"') str += "&quot;";\r
-        else if (*p == ' ' && p > psz && p[-1] == ' ' && p[1] == ' ') str += "&nbsp;";\r
-        else if (*p == '\n' && fMultiLine) str += "<br>\n";\r
-        else\r
-            str += *p;\r
-    }\r
-    return str;\r
-}\r
-\r
-string HtmlEscape(const string& str, bool fMultiLine=false)\r
-{\r
-    return HtmlEscape(str.c_str(), fMultiLine);\r
-}\r
-\r
-void AddToMyProducts(CProduct product)\r
-{\r
-    CProduct& productInsert = mapMyProducts[product.GetHash()];\r
-    productInsert = product;\r
-    InsertLine(pframeMain->m_listCtrlProductsSent, &productInsert,\r
-                product.mapValue["category"],\r
-                product.mapValue["title"].substr(0, 100),\r
-                product.mapValue["description"].substr(0, 100),\r
-                product.mapValue["price"],\r
-                "");\r
-}\r
-\r
-void CalledMessageBox(const string& message, const string& caption, int style, wxWindow* parent, int x, int y, int* pnRet, bool* pfDone)\r
-{\r
-    *pnRet = wxMessageBox(message, caption, style, parent, x, y);\r
-    *pfDone = true;\r
-}\r
-\r
-int ThreadSafeMessageBox(const string& message, const string& caption, int style, wxWindow* parent, int x, int y)\r
-{\r
-    if (mapArgs.count("-noui"))\r
-        return wxOK;\r
-\r
-#ifdef __WXMSW__\r
-    return wxMessageBox(message, caption, style, parent, x, y);\r
-#else\r
-    if (wxThread::IsMain())\r
-    {\r
-        return wxMessageBox(message, caption, style, parent, x, y);\r
-    }\r
-    else\r
-    {\r
-        int nRet = 0;\r
-        bool fDone = false;\r
-        UIThreadCall(bind(CalledMessageBox, message, caption, style, parent, x, y, &nRet, &fDone));\r
-        while (!fDone)\r
-            Sleep(100);\r
-        return nRet;\r
-    }\r
-#endif\r
-}\r
-\r
-\r
-\r
-\r
-\r
-\r
-\r
-\r
-\r
-\r
-//////////////////////////////////////////////////////////////////////////////\r
-//\r
-// Custom events\r
-//\r
-// If this code gets used again, it should be replaced with something like UIThreadCall\r
-\r
-set<void*> setCallbackAvailable;\r
-CCriticalSection cs_setCallbackAvailable;\r
-\r
-void AddCallbackAvailable(void* p)\r
-{\r
-    CRITICAL_BLOCK(cs_setCallbackAvailable)\r
-        setCallbackAvailable.insert(p);\r
-}\r
-\r
-void RemoveCallbackAvailable(void* p)\r
-{\r
-    CRITICAL_BLOCK(cs_setCallbackAvailable)\r
-        setCallbackAvailable.erase(p);\r
-}\r
-\r
-bool IsCallbackAvailable(void* p)\r
-{\r
-    CRITICAL_BLOCK(cs_setCallbackAvailable)\r
-        return setCallbackAvailable.count(p);\r
-    return false;\r
-}\r
-\r
-template<typename T>\r
-void AddPendingCustomEvent(wxEvtHandler* pevthandler, int nEventID, const T pbeginIn, const T pendIn)\r
-{\r
-    // Need to rewrite with something like UIThreadCall\r
-    // I'm tired of maintaining this hack that's only called by unfinished unused code,\r
-    // but I'm not willing to delete it because it serves as documentation of what the\r
-    // unfinished code was trying to do.\r
-    assert(("Unimplemented", 0));\r
-    //if (!pevthandler)\r
-    //    return;\r
-    //\r
-    //const char* pbegin = (pendIn != pbeginIn) ? &pbeginIn[0] : NULL;\r
-    //const char* pend = pbegin + (pendIn - pbeginIn) * sizeof(pbeginIn[0]);\r
-    //wxCommandEvent event(nEventID);\r
-    //wxString strData(wxChar(0), (pend - pbegin) / sizeof(wxChar) + 1);\r
-    //memcpy(&strData[0], pbegin, pend - pbegin);\r
-    //event.SetString(strData);\r
-    //event.SetInt(pend - pbegin);\r
-    //\r
-    //pevthandler->AddPendingEvent(event);\r
-}\r
-\r
-template<class T>\r
-void AddPendingCustomEvent(wxEvtHandler* pevthandler, int nEventID, const T& obj)\r
-{\r
-    CDataStream ss;\r
-    ss << obj;\r
-    AddPendingCustomEvent(pevthandler, nEventID, ss.begin(), ss.end());\r
-}\r
-\r
-void AddPendingReplyEvent1(void* pevthandler, CDataStream& vRecv)\r
-{\r
-    if (IsCallbackAvailable(pevthandler))\r
-        AddPendingCustomEvent((wxEvtHandler*)pevthandler, wxEVT_REPLY1, vRecv.begin(), vRecv.end());\r
-}\r
-\r
-void AddPendingReplyEvent2(void* pevthandler, CDataStream& vRecv)\r
-{\r
-    if (IsCallbackAvailable(pevthandler))\r
-        AddPendingCustomEvent((wxEvtHandler*)pevthandler, wxEVT_REPLY2, vRecv.begin(), vRecv.end());\r
-}\r
-\r
-void AddPendingReplyEvent3(void* pevthandler, CDataStream& vRecv)\r
-{\r
-    if (IsCallbackAvailable(pevthandler))\r
-        AddPendingCustomEvent((wxEvtHandler*)pevthandler, wxEVT_REPLY3, vRecv.begin(), vRecv.end());\r
-}\r
-\r
-CDataStream GetStreamFromEvent(const wxCommandEvent& event)\r
-{\r
-    wxString strData = event.GetString();\r
-    const char* pszBegin = strData.c_str();\r
-    return CDataStream(pszBegin, pszBegin + event.GetInt(), SER_NETWORK);\r
-}\r
-\r
-\r
-\r
-\r
-\r
-\r
-\r
-//////////////////////////////////////////////////////////////////////////////\r
-//\r
-// CMainFrame\r
-//\r
-\r
-CMainFrame::CMainFrame(wxWindow* parent) : CMainFrameBase(parent)\r
-{\r
-    Connect(wxEVT_UITHREADCALL, wxCommandEventHandler(CMainFrame::OnUIThreadCall), NULL, this);\r
-\r
-    // Init\r
-    fRefreshListCtrl = false;\r
-    fRefreshListCtrlRunning = false;\r
-    fOnSetFocusAddress = false;\r
-    fRefresh = false;\r
-    m_choiceFilter->SetSelection(0);\r
-    double dResize = 1.0;\r
-#ifdef __WXMSW__\r
-    SetIcon(wxICON(bitcoin));\r
-#else\r
-    SetIcon(bitcoin16_xpm);\r
-    wxFont fontTmp = m_staticText41->GetFont();\r
-    fontTmp.SetFamily(wxFONTFAMILY_TELETYPE);\r
-    m_staticTextBalance->SetFont(fontTmp);\r
-    m_staticTextBalance->SetSize(140, 17);\r
-    // & underlines don't work on the toolbar buttons on gtk\r
-    m_toolBar->ClearTools();\r
-    m_toolBar->AddTool(wxID_BUTTONSEND, "Send Coins", wxBitmap(send20_xpm), wxNullBitmap, wxITEM_NORMAL, wxEmptyString, wxEmptyString);\r
-    m_toolBar->AddTool(wxID_BUTTONRECEIVE, "Address Book", wxBitmap(addressbook20_xpm), wxNullBitmap, wxITEM_NORMAL, wxEmptyString, wxEmptyString);\r
-    m_toolBar->Realize();\r
-    // resize to fit ubuntu's huge default font\r
-    dResize = 1.20;\r
-    SetSize(dResize * GetSize().GetWidth(), 1.1 * GetSize().GetHeight());\r
-#endif\r
-    m_staticTextBalance->SetLabel(FormatMoney(GetBalance()) + "  ");\r
-    m_listCtrl->SetFocus();\r
-    ptaskbaricon = new CMyTaskBarIcon();\r
-\r
-    // Init column headers\r
-    int nDateWidth = DateTimeStr(1229413914).size() * 6 + 8;\r
-    if (!strstr(DateTimeStr(1229413914).c_str(), "2008"))\r
-        nDateWidth += 12;\r
-    m_listCtrl->InsertColumn(0, "",             wxLIST_FORMAT_LEFT,  dResize * 0);\r
-    m_listCtrl->InsertColumn(1, "",             wxLIST_FORMAT_LEFT,  dResize * 0);\r
-    m_listCtrl->InsertColumn(2, "Status",       wxLIST_FORMAT_LEFT,  dResize * 110);\r
-    m_listCtrl->InsertColumn(3, "Date",         wxLIST_FORMAT_LEFT,  dResize * nDateWidth);\r
-    m_listCtrl->InsertColumn(4, "Description",  wxLIST_FORMAT_LEFT,  dResize * 409 - nDateWidth);\r
-    m_listCtrl->InsertColumn(5, "Debit",        wxLIST_FORMAT_RIGHT, dResize * 79);\r
-    m_listCtrl->InsertColumn(6, "Credit",       wxLIST_FORMAT_RIGHT, dResize * 79);\r
-\r
-    //m_listCtrlProductsSent->InsertColumn(0, "Category",      wxLIST_FORMAT_LEFT,  100);\r
-    //m_listCtrlProductsSent->InsertColumn(1, "Title",         wxLIST_FORMAT_LEFT,  100);\r
-    //m_listCtrlProductsSent->InsertColumn(2, "Description",   wxLIST_FORMAT_LEFT,  100);\r
-    //m_listCtrlProductsSent->InsertColumn(3, "Price",         wxLIST_FORMAT_LEFT,  100);\r
-    //m_listCtrlProductsSent->InsertColumn(4, "",              wxLIST_FORMAT_LEFT,  100);\r
-\r
-    //m_listCtrlOrdersSent->InsertColumn(0, "Time",          wxLIST_FORMAT_LEFT,  100);\r
-    //m_listCtrlOrdersSent->InsertColumn(1, "Price",         wxLIST_FORMAT_LEFT,  100);\r
-    //m_listCtrlOrdersSent->InsertColumn(2, "",              wxLIST_FORMAT_LEFT,  100);\r
-    //m_listCtrlOrdersSent->InsertColumn(3, "",              wxLIST_FORMAT_LEFT,  100);\r
-    //m_listCtrlOrdersSent->InsertColumn(4, "",              wxLIST_FORMAT_LEFT,  100);\r
-\r
-    //m_listCtrlOrdersReceived->InsertColumn(0, "Time",            wxLIST_FORMAT_LEFT,  100);\r
-    //m_listCtrlOrdersReceived->InsertColumn(1, "Price",           wxLIST_FORMAT_LEFT,  100);\r
-    //m_listCtrlOrdersReceived->InsertColumn(2, "Payment Status",  wxLIST_FORMAT_LEFT,  100);\r
-    //m_listCtrlOrdersReceived->InsertColumn(3, "",                wxLIST_FORMAT_LEFT,  100);\r
-    //m_listCtrlOrdersReceived->InsertColumn(4, "",                wxLIST_FORMAT_LEFT,  100);\r
-\r
-    // Init status bar\r
-    int pnWidths[3] = { -100, 88, 290 };\r
-#ifndef __WXMSW__\r
-    pnWidths[1] = pnWidths[1] * 1.1 * dResize;\r
-    pnWidths[2] = pnWidths[2] * 1.1 * dResize;\r
-#endif\r
-    m_statusBar->SetFieldsCount(3, pnWidths);\r
-\r
-    // Fill your address text box\r
-    vector<unsigned char> vchPubKey;\r
-    if (CWalletDB("r").ReadDefaultKey(vchPubKey))\r
-        m_textCtrlAddress->SetValue(PubKeyToAddress(vchPubKey));\r
-\r
-    // Fill listctrl with wallet transactions\r
-    RefreshListCtrl();\r
-}\r
-\r
-CMainFrame::~CMainFrame()\r
-{\r
-    pframeMain = NULL;\r
-    delete ptaskbaricon;\r
-    ptaskbaricon = NULL;\r
-}\r
-\r
-void ExitTimeout(void* parg)\r
-{\r
-#ifdef __WXMSW__\r
-    Sleep(5000);\r
-    ExitProcess(0);\r
-#endif\r
-}\r
-\r
-void Shutdown(void* parg)\r
-{\r
-    static CCriticalSection cs_Shutdown;\r
-    static bool fTaken;\r
-    bool fFirstThread;\r
-    CRITICAL_BLOCK(cs_Shutdown)\r
-    {\r
-        fFirstThread = !fTaken;\r
-        fTaken = true;\r
-    }\r
-    static bool fExit;\r
-    if (fFirstThread)\r
-    {\r
-        fShutdown = true;\r
-        nTransactionsUpdated++;\r
-        DBFlush(false);\r
-        StopNode();\r
-        DBFlush(true);\r
-        CreateThread(ExitTimeout, NULL);\r
-        Sleep(10);\r
-        printf("Bitcoin exiting\n\n");\r
-        fExit = true;\r
-        exit(0);\r
-    }\r
-    else\r
-    {\r
-        while (!fExit)\r
-            Sleep(500);\r
-        Sleep(100);\r
-        ExitThread(0);\r
-    }\r
-}\r
-\r
-void CMainFrame::OnClose(wxCloseEvent& event)\r
-{\r
-    if (fMinimizeOnClose && event.CanVeto() && !IsIconized())\r
-    {\r
-        // Divert close to minimize\r
-        event.Veto();\r
-        fClosedToTray = true;\r
-        Iconize(true);\r
-    }\r
-    else\r
-    {\r
-        Destroy();\r
-        CreateThread(Shutdown, NULL);\r
-    }\r
-}\r
-\r
-void CMainFrame::OnIconize(wxIconizeEvent& event)\r
-{\r
-    // Hide the task bar button when minimized.\r
-    // Event is sent when the frame is minimized or restored.\r
-    // wxWidgets 2.8.9 doesn't have IsIconized() so there's no way\r
-    // to get rid of the deprecated warning.  Just ignore it.\r
-    if (!event.Iconized())\r
-        fClosedToTray = false;\r
-#ifndef __WXMSW__\r
-    // Tray is not reliable on Linux gnome\r
-    fClosedToTray = false;\r
-#endif\r
-    if (fMinimizeToTray && event.Iconized())\r
-        fClosedToTray = true;\r
-    Show(!fClosedToTray);\r
-    ptaskbaricon->Show(fMinimizeToTray || fClosedToTray);\r
-}\r
-\r
-void CMainFrame::OnMouseEvents(wxMouseEvent& event)\r
-{\r
-    RandAddSeed();\r
-    RAND_add(&event.m_x, sizeof(event.m_x), 0.25);\r
-    RAND_add(&event.m_y, sizeof(event.m_y), 0.25);\r
-}\r
-\r
-void CMainFrame::OnListColBeginDrag(wxListEvent& event)\r
-{\r
-     // Hidden columns not resizeable\r
-     if (event.GetColumn() <= 1 && !fDebug)\r
-        event.Veto();\r
-}\r
-\r
-int CMainFrame::GetSortIndex(const string& strSort)\r
-{\r
-#ifdef __WXMSW__\r
-    return 0;\r
-#else\r
-    // The wx generic listctrl implementation used on GTK doesn't sort,\r
-    // so we have to do it ourselves.  Remember, we sort in reverse order.\r
-    // In the wx generic implementation, they store the list of items\r
-    // in a vector, so indexed lookups are fast, but inserts are slower\r
-    // the closer they are to the top.\r
-    int low = 0;\r
-    int high = m_listCtrl->GetItemCount();\r
-    while (low < high)\r
-    {\r
-        int mid = low + ((high - low) / 2);\r
-        if (strSort.compare(m_listCtrl->GetItemText(mid).c_str()) >= 0)\r
-            high = mid;\r
-        else\r
-            low = mid + 1;\r
-    }\r
-    return low;\r
-#endif\r
-}\r
-\r
-void CMainFrame::InsertLine(bool fNew, int nIndex, uint256 hashKey, string strSort, const wxString& str2, const wxString& str3, const wxString& str4, const wxString& str5, const wxString& str6)\r
-{\r
-    string str0 = strSort;\r
-    long nData = *(long*)&hashKey;\r
-\r
-    // Find item\r
-    if (!fNew && nIndex == -1)\r
-    {\r
-        while ((nIndex = m_listCtrl->FindItem(nIndex, nData)) != -1)\r
-            if (GetItemText(m_listCtrl, nIndex, 1) == hashKey.ToString())\r
-                break;\r
-    }\r
-\r
-    // fNew is for blind insert, only use if you're sure it's new\r
-    if (fNew || nIndex == -1)\r
-    {\r
-        nIndex = m_listCtrl->InsertItem(GetSortIndex(strSort), str0);\r
-    }\r
-    else\r
-    {\r
-        // If sort key changed, must delete and reinsert to make it relocate\r
-        if (GetItemText(m_listCtrl, nIndex, 0) != str0)\r
-        {\r
-            m_listCtrl->DeleteItem(nIndex);\r
-            nIndex = m_listCtrl->InsertItem(GetSortIndex(strSort), str0);\r
-        }\r
-    }\r
-\r
-    m_listCtrl->SetItem(nIndex, 1, hashKey.ToString());\r
-    m_listCtrl->SetItem(nIndex, 2, str2);\r
-    m_listCtrl->SetItem(nIndex, 3, str3);\r
-    m_listCtrl->SetItem(nIndex, 4, str4);\r
-    m_listCtrl->SetItem(nIndex, 5, str5);\r
-    m_listCtrl->SetItem(nIndex, 6, str6);\r
-    m_listCtrl->SetItemData(nIndex, nData);\r
-}\r
-\r
-bool CMainFrame::DeleteLine(uint256 hashKey)\r
-{\r
-    long nData = *(long*)&hashKey;\r
-\r
-    // Find item\r
-    int nIndex = -1;\r
-    while ((nIndex = m_listCtrl->FindItem(nIndex, nData)) != -1)\r
-        if (GetItemText(m_listCtrl, nIndex, 1) == hashKey.ToString())\r
-            break;\r
-\r
-    if (nIndex != -1)\r
-        m_listCtrl->DeleteItem(nIndex);\r
-\r
-    return nIndex != -1;\r
-}\r
-\r
-string FormatTxStatus(const CWalletTx& wtx)\r
-{\r
-    // Status\r
-    if (!wtx.IsFinal())\r
-    {\r
-        if (wtx.nLockTime < 500000000)\r
-            return strprintf("Open for %d blocks", nBestHeight - wtx.nLockTime);\r
-        else\r
-            return strprintf("Open until %s", DateTimeStr(wtx.nLockTime).c_str());\r
-    }\r
-    else\r
-    {\r
-        int nDepth = wtx.GetDepthInMainChain();\r
-        if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)\r
-            return strprintf("%d/offline?", nDepth);\r
-        else if (nDepth < 6)\r
-            return strprintf("%d/unconfirmed", nDepth);\r
-        else\r
-            return strprintf("%d confirmations", nDepth);\r
-    }\r
-}\r
-\r
-string SingleLine(const string& strIn)\r
-{\r
-    string strOut;\r
-    bool fOneSpace = false;\r
-    foreach(int c, strIn)\r
-    {\r
-        if (isspace(c))\r
-        {\r
-            fOneSpace = true;\r
-        }\r
-        else if (c > ' ')\r
-        {\r
-            if (fOneSpace && !strOut.empty())\r
-                strOut += ' ';\r
-            strOut += c;\r
-            fOneSpace = false;\r
-        }\r
-    }\r
-    return strOut;\r
-}\r
-\r
-bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex)\r
-{\r
-    int64 nTime = wtx.nTimeDisplayed = wtx.GetTxTime();\r
-    int64 nCredit = wtx.GetCredit();\r
-    int64 nDebit = wtx.GetDebit();\r
-    int64 nNet = nCredit - nDebit;\r
-    uint256 hash = wtx.GetHash();\r
-    string strStatus = FormatTxStatus(wtx);\r
-    map<string, string> mapValue = wtx.mapValue;\r
-    wtx.nLinesDisplayed = 1;\r
-    nListViewUpdated++;\r
-\r
-    // Filter\r
-    if (wtx.IsCoinBase())\r
-    {\r
-        // Don't show generated coin until confirmed by at least one block after it\r
-        // so we don't get the user's hopes up until it looks like it's probably accepted.\r
-        //\r
-        // It is not an error when generated blocks are not accepted.  By design,\r
-        // some percentage of blocks, like 10% or more, will end up not accepted.\r
-        // This is the normal mechanism by which the network copes with latency.\r
-        //\r
-        // We display regular transactions right away before any confirmation\r
-        // because they can always get into some block eventually.  Generated coins\r
-        // are special because if their block is not accepted, they are not valid.\r
-        //\r
-        if (wtx.GetDepthInMainChain() < 2)\r
-        {\r
-            wtx.nLinesDisplayed = 0;\r
-            return false;\r
-        }\r
-\r
-        // View->Show Generated\r
-        if (!fShowGenerated)\r
-            return false;\r
-    }\r
-\r
-    // Find the block the tx is in\r
-    CBlockIndex* pindex = NULL;\r
-    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(wtx.hashBlock);\r
-    if (mi != mapBlockIndex.end())\r
-        pindex = (*mi).second;\r
-\r
-    // Sort order, unrecorded transactions sort to the top\r
-    string strSort = strprintf("%010d-%01d-%010u",\r
-        (pindex ? pindex->nHeight : INT_MAX),\r
-        (wtx.IsCoinBase() ? 1 : 0),\r
-        wtx.nTimeReceived);\r
-\r
-    // Insert line\r
-    if (nNet > 0 || wtx.IsCoinBase())\r
-    {\r
-        //\r
-        // Credit\r
-        //\r
-        string strDescription;\r
-\r
-        if (wtx.IsCoinBase())\r
-        {\r
-            // Coinbase\r
-            strDescription = "Generated";\r
-            if (nCredit == 0)\r
-            {\r
-                int64 nUnmatured = 0;\r
-                foreach(const CTxOut& txout, wtx.vout)\r
-                    nUnmatured += txout.GetCredit();\r
-                if (wtx.IsInMainChain())\r
-                {\r
-                    strDescription = strprintf("Generated (%s matures in %d more blocks)", FormatMoney(nUnmatured).c_str(), wtx.GetBlocksToMaturity());\r
-\r
-                    // Check if the block was requested by anyone\r
-                    if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)\r
-                        strDescription = "Generated - Warning: This block was not received by any other nodes and will probably not be accepted!";\r
-                }\r
-                else\r
-                {\r
-                    strDescription = "Generated (not accepted)";\r
-                }\r
-            }\r
-        }\r
-        else if (!mapValue["from"].empty() || !mapValue["message"].empty())\r
-        {\r
-            // Online transaction\r
-            if (!mapValue["from"].empty())\r
-                strDescription += "From: " + mapValue["from"];\r
-            if (!mapValue["message"].empty())\r
-            {\r
-                if (!strDescription.empty())\r
-                    strDescription += " - ";\r
-                strDescription += mapValue["message"];\r
-            }\r
-        }\r
-        else\r
-        {\r
-            // Offline transaction\r
-            foreach(const CTxOut& txout, wtx.vout)\r
-            {\r
-                if (txout.IsMine())\r
-                {\r
-                    vector<unsigned char> vchPubKey;\r
-                    if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey))\r
-                    {\r
-                        string strAddress = PubKeyToAddress(vchPubKey);\r
-                        if (mapAddressBook.count(strAddress))\r
-                        {\r
-                            //strDescription += "Received payment to ";\r
-                            //strDescription += "Received with address ";\r
-                            strDescription += "From: unknown, To: ";\r
-                            strDescription += strAddress;\r
-                            /// The labeling feature is just too confusing, so I hid it\r
-                            /// by putting it at the end where it runs off the screen.\r
-                            /// It can still be seen by widening the column, or in the\r
-                            /// details dialog.\r
-                            if (!mapAddressBook[strAddress].empty())\r
-                                strDescription += " (" + mapAddressBook[strAddress] + ")";\r
-                        }\r
-                    }\r
-                    break;\r
-                }\r
-            }\r
-        }\r
-\r
-        InsertLine(fNew, nIndex, hash, strSort,\r
-                   strStatus,\r
-                   nTime ? DateTimeStr(nTime) : "",\r
-                   SingleLine(strDescription),\r
-                   "",\r
-                   FormatMoney(nNet, true));\r
-    }\r
-    else\r
-    {\r
-        bool fAllFromMe = true;\r
-        foreach(const CTxIn& txin, wtx.vin)\r
-            fAllFromMe = fAllFromMe && txin.IsMine();\r
-\r
-        bool fAllToMe = true;\r
-        foreach(const CTxOut& txout, wtx.vout)\r
-            fAllToMe = fAllToMe && txout.IsMine();\r
-\r
-        if (fAllFromMe && fAllToMe)\r
-        {\r
-            // Payment to self\r
-            int64 nValue = wtx.vout[0].nValue;\r
-            InsertLine(fNew, nIndex, hash, strSort,\r
-                       strStatus,\r
-                       nTime ? DateTimeStr(nTime) : "",\r
-                       "Payment to yourself",\r
-                       "",\r
-                       "");\r
-            /// issue: can't tell which is the payment and which is the change anymore\r
-            //           FormatMoney(nNet - nValue, true),\r
-            //           FormatMoney(nValue, true));\r
-        }\r
-        else if (fAllFromMe)\r
-        {\r
-            //\r
-            // Debit\r
-            //\r
-            int64 nTxFee = nDebit - wtx.GetValueOut();\r
-            wtx.nLinesDisplayed = 0;\r
-            for (int nOut = 0; nOut < wtx.vout.size(); nOut++)\r
-            {\r
-                const CTxOut& txout = wtx.vout[nOut];\r
-                if (txout.IsMine())\r
-                    continue;\r
-\r
-                string strAddress;\r
-                if (!mapValue["to"].empty())\r
-                {\r
-                    // Online transaction\r
-                    strAddress = mapValue["to"];\r
-                }\r
-                else\r
-                {\r
-                    // Offline transaction\r
-                    uint160 hash160;\r
-                    if (ExtractHash160(txout.scriptPubKey, hash160))\r
-                        strAddress = Hash160ToAddress(hash160);\r
-                }\r
-\r
-                string strDescription = "To: ";\r
-                if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())\r
-                    strDescription += mapAddressBook[strAddress] + " ";\r
-                strDescription += strAddress;\r
-                if (!mapValue["message"].empty())\r
-                {\r
-                    if (!strDescription.empty())\r
-                        strDescription += " - ";\r
-                    strDescription += mapValue["message"];\r
-                }\r
-\r
-                int64 nValue = txout.nValue;\r
-                if (nOut == 0 && nTxFee > 0)\r
-                    nValue += nTxFee;\r
-\r
-                InsertLine(fNew, nIndex, hash, strprintf("%s-%d", strSort.c_str(), nOut),\r
-                           strStatus,\r
-                           nTime ? DateTimeStr(nTime) : "",\r
-                           SingleLine(strDescription),\r
-                           FormatMoney(-nValue, true),\r
-                           "");\r
-                wtx.nLinesDisplayed++;\r
-            }\r
-        }\r
-        else\r
-        {\r
-            //\r
-            // Mixed debit transaction, can't break down payees\r
-            //\r
-            bool fAllMine = true;\r
-            foreach(const CTxOut& txout, wtx.vout)\r
-                fAllMine = fAllMine && txout.IsMine();\r
-            foreach(const CTxIn& txin, wtx.vin)\r
-                fAllMine = fAllMine && txin.IsMine();\r
-\r
-            InsertLine(fNew, nIndex, hash, strSort,\r
-                       strStatus,\r
-                       nTime ? DateTimeStr(nTime) : "",\r
-                       "",\r
-                       FormatMoney(nNet, true),\r
-                       "");\r
-        }\r
-    }\r
-\r
-    return true;\r
-}\r
-\r
-void CMainFrame::RefreshListCtrl()\r
-{\r
-    fRefreshListCtrl = true;\r
-    ::wxWakeUpIdle();\r
-}\r
-\r
-void CMainFrame::OnIdle(wxIdleEvent& event)\r
-{\r
-    if (fRefreshListCtrl)\r
-    {\r
-        // Collect list of wallet transactions and sort newest first\r
-        bool fEntered = false;\r
-        vector<pair<unsigned int, uint256> > vSorted;\r
-        TRY_CRITICAL_BLOCK(cs_mapWallet)\r
-        {\r
-            printf("RefreshListCtrl starting\n");\r
-            fEntered = true;\r
-            fRefreshListCtrl = false;\r
-            vWalletUpdated.clear();\r
-\r
-            // Do the newest transactions first\r
-            vSorted.reserve(mapWallet.size());\r
-            for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)\r
-            {\r
-                const CWalletTx& wtx = (*it).second;\r
-                unsigned int nTime = UINT_MAX - wtx.GetTxTime();\r
-                vSorted.push_back(make_pair(nTime, (*it).first));\r
-            }\r
-            m_listCtrl->DeleteAllItems();\r
-        }\r
-        if (!fEntered)\r
-            return;\r
-\r
-        sort(vSorted.begin(), vSorted.end());\r
-\r
-        // Fill list control\r
-        for (int i = 0; i < vSorted.size();)\r
-        {\r
-            if (fShutdown)\r
-                return;\r
-            bool fEntered = false;\r
-            TRY_CRITICAL_BLOCK(cs_mapWallet)\r
-            {\r
-                fEntered = true;\r
-                uint256& hash = vSorted[i++].second;\r
-                map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);\r
-                if (mi != mapWallet.end())\r
-                    InsertTransaction((*mi).second, true);\r
-            }\r
-            if (!fEntered || i == 100 || i % 500 == 0)\r
-                wxYield();\r
-        }\r
-\r
-        printf("RefreshListCtrl done\n");\r
-\r
-        // Update transaction total display\r
-        MainFrameRepaint();\r
-    }\r
-    else\r
-    {\r
-        // Check for time updates\r
-        static int64 nLastTime;\r
-        if (GetTime() > nLastTime + 30)\r
-        {\r
-            TRY_CRITICAL_BLOCK(cs_mapWallet)\r
-            {\r
-                nLastTime = GetTime();\r
-                for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)\r
-                {\r
-                    CWalletTx& wtx = (*it).second;\r
-                    if (wtx.nTimeDisplayed && wtx.nTimeDisplayed != wtx.GetTxTime())\r
-                        InsertTransaction(wtx, false);\r
-                }\r
-            }\r
-        }\r
-    }\r
-}\r
-\r
-void CMainFrame::RefreshStatusColumn()\r
-{\r
-    static int nLastTop;\r
-    static CBlockIndex* pindexLastBest;\r
-    static unsigned int nLastRefreshed;\r
-\r
-    int nTop = max((int)m_listCtrl->GetTopItem(), 0);\r
-    if (nTop == nLastTop && pindexLastBest == pindexBest)\r
-        return;\r
-\r
-    TRY_CRITICAL_BLOCK(cs_mapWallet)\r
-    {\r
-        int nStart = nTop;\r
-        int nEnd = min(nStart + 100, m_listCtrl->GetItemCount());\r
-\r
-        if (pindexLastBest == pindexBest && nLastRefreshed == nListViewUpdated)\r
-        {\r
-            // If no updates, only need to do the part that moved onto the screen\r
-            if (nStart >= nLastTop && nStart < nLastTop + 100)\r
-                nStart = nLastTop + 100;\r
-            if (nEnd >= nLastTop && nEnd < nLastTop + 100)\r
-                nEnd = nLastTop;\r
-        }\r
-        nLastTop = nTop;\r
-        pindexLastBest = pindexBest;\r
-        nLastRefreshed = nListViewUpdated;\r
-\r
-        for (int nIndex = nStart; nIndex < min(nEnd, m_listCtrl->GetItemCount()); nIndex++)\r
-        {\r
-            uint256 hash((string)GetItemText(m_listCtrl, nIndex, 1));\r
-            map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);\r
-            if (mi == mapWallet.end())\r
-            {\r
-                printf("CMainFrame::RefreshStatusColumn() : tx not found in mapWallet\n");\r
-                continue;\r
-            }\r
-            CWalletTx& wtx = (*mi).second;\r
-            if (wtx.IsCoinBase() || wtx.GetTxTime() != wtx.nTimeDisplayed)\r
-            {\r
-                if (!InsertTransaction(wtx, false, nIndex))\r
-                    m_listCtrl->DeleteItem(nIndex--);\r
-            }\r
-            else\r
-                m_listCtrl->SetItem(nIndex, 2, FormatTxStatus(wtx));\r
-        }\r
-    }\r
-}\r
-\r
-void CMainFrame::OnPaint(wxPaintEvent& event)\r
-{\r
-    if (fRefresh)\r
-    {\r
-        fRefresh = false;\r
-        Refresh();\r
-    }\r
-    event.Skip();\r
-}\r
-\r
-\r
-unsigned int nNeedRepaint = 0;\r
-unsigned int nLastRepaint = 0;\r
-int64 nLastRepaintTime = 0;\r
-int64 nRepaintInterval = 500;\r
-\r
-void ThreadDelayedRepaint(void* parg)\r
-{\r
-    while (!fShutdown)\r
-    {\r
-        if (nLastRepaint != nNeedRepaint && GetTimeMillis() - nLastRepaintTime >= nRepaintInterval)\r
-        {\r
-            nLastRepaint = nNeedRepaint;\r
-            if (pframeMain)\r
-            {\r
-                printf("DelayedRepaint\n");\r
-                wxPaintEvent event;\r
-                pframeMain->fRefresh = true;\r
-                pframeMain->GetEventHandler()->AddPendingEvent(event);\r
-            }\r
-        }\r
-        Sleep(nRepaintInterval);\r
-    }\r
-}\r
-\r
-void MainFrameRepaint()\r
-{\r
-    // This is called by network code that shouldn't access pframeMain\r
-    // directly because it could still be running after the UI is closed.\r
-    if (pframeMain)\r
-    {\r
-        // Don't repaint too often\r
-        static int64 nLastRepaintRequest;\r
-        if (GetTimeMillis() - nLastRepaintRequest < 100)\r
-        {\r
-            nNeedRepaint++;\r
-            return;\r
-        }\r
-        nLastRepaintRequest = GetTimeMillis();\r
-\r
-        printf("MainFrameRepaint\n");\r
-        wxPaintEvent event;\r
-        pframeMain->fRefresh = true;\r
-        pframeMain->GetEventHandler()->AddPendingEvent(event);\r
-    }\r
-}\r
-\r
-void CMainFrame::OnPaintListCtrl(wxPaintEvent& event)\r
-{\r
-    if (ptaskbaricon)\r
-        ptaskbaricon->UpdateTooltip();\r
-\r
-    //\r
-    // Slower stuff\r
-    //\r
-    static int nTransactionCount;\r
-    bool fPaintedBalance = false;\r
-    if (GetTimeMillis() - nLastRepaintTime >= nRepaintInterval)\r
-    {\r
-        nLastRepaint = nNeedRepaint;\r
-        nLastRepaintTime = GetTimeMillis();\r
-\r
-        // Update listctrl contents\r
-        if (!vWalletUpdated.empty())\r
-        {\r
-            TRY_CRITICAL_BLOCK(cs_mapWallet)\r
-            {\r
-                string strTop;\r
-                if (m_listCtrl->GetItemCount())\r
-                    strTop = (string)m_listCtrl->GetItemText(0);\r
-                foreach(uint256 hash, vWalletUpdated)\r
-                {\r
-                    map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);\r
-                    if (mi != mapWallet.end())\r
-                        InsertTransaction((*mi).second, false);\r
-                }\r
-                vWalletUpdated.clear();\r
-                if (m_listCtrl->GetItemCount() && strTop != (string)m_listCtrl->GetItemText(0))\r
-                    m_listCtrl->ScrollList(0, INT_MIN/2);\r
-            }\r
-        }\r
-\r
-        // Balance total\r
-        TRY_CRITICAL_BLOCK(cs_mapWallet)\r
-        {\r
-            fPaintedBalance = true;\r
-            m_staticTextBalance->SetLabel(FormatMoney(GetBalance()) + "  ");\r
-\r
-            // Count hidden and multi-line transactions\r
-            nTransactionCount = 0;\r
-            for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)\r
-            {\r
-                CWalletTx& wtx = (*it).second;\r
-                nTransactionCount += wtx.nLinesDisplayed;\r
-            }\r
-        }\r
-    }\r
-    if (!vWalletUpdated.empty() || !fPaintedBalance)\r
-        nNeedRepaint++;\r
-\r
-    // Update status column of visible items only\r
-    RefreshStatusColumn();\r
-\r
-    // Update status bar\r
-    string strGen = "";\r
-    if (fGenerateBitcoins)\r
-        strGen = "    Generating";\r
-    if (fGenerateBitcoins && vNodes.empty())\r
-        strGen = "(not connected)";\r
-    m_statusBar->SetStatusText(strGen, 1);\r
-\r
-    string strStatus = strprintf("     %d connections     %d blocks     %d transactions", vNodes.size(), nBestHeight + 1, nTransactionCount);\r
-    m_statusBar->SetStatusText(strStatus, 2);\r
-\r
-    if (fDebug && GetTime() - nThreadSocketHandlerHeartbeat > 60)\r
-        m_statusBar->SetStatusText("     ERROR: ThreadSocketHandler has stopped", 0);\r
-\r
-    // Pass through to listctrl to actually do the paint, we're just hooking the message\r
-    m_listCtrl->Disconnect(wxEVT_PAINT, (wxObjectEventFunction)NULL, NULL, this);\r
-    m_listCtrl->GetEventHandler()->ProcessEvent(event);\r
-    m_listCtrl->Connect(wxEVT_PAINT, wxPaintEventHandler(CMainFrame::OnPaintListCtrl), NULL, this);\r
-}\r
-\r
-\r
-void UIThreadCall(boost::function0<void> fn)\r
-{\r
-    // Call this with a function object created with bind.\r
-    // bind needs all parameters to match the function's expected types\r
-    // and all default parameters specified.  Some examples:\r
-    //  UIThreadCall(bind(wxBell));\r
-    //  UIThreadCall(bind(wxMessageBox, wxT("Message"), wxT("Title"), wxOK, (wxWindow*)NULL, -1, -1));\r
-    //  UIThreadCall(bind(&CMainFrame::OnMenuHelpAbout, pframeMain, event));\r
-    if (pframeMain)\r
-    {\r
-        wxCommandEvent event(wxEVT_UITHREADCALL);\r
-        event.SetClientData((void*)new boost::function0<void>(fn));\r
-        pframeMain->GetEventHandler()->AddPendingEvent(event);\r
-    }\r
-}\r
-\r
-void CMainFrame::OnUIThreadCall(wxCommandEvent& event)\r
-{\r
-    boost::function0<void>* pfn = (boost::function0<void>*)event.GetClientData();\r
-    (*pfn)();\r
-    delete pfn;\r
-}\r
-\r
-void CMainFrame::OnMenuFileExit(wxCommandEvent& event)\r
-{\r
-    // File->Exit\r
-    Close(true);\r
-}\r
-\r
-void CMainFrame::OnMenuViewShowGenerated(wxCommandEvent& event)\r
-{\r
-    // View->Show Generated\r
-    fShowGenerated = event.IsChecked();\r
-    CWalletDB().WriteSetting("fShowGenerated", fShowGenerated);\r
-    RefreshListCtrl();\r
-}\r
-\r
-void CMainFrame::OnUpdateUIViewShowGenerated(wxUpdateUIEvent& event)\r
-{\r
-    event.Check(fShowGenerated);\r
-}\r
-\r
-void CMainFrame::OnMenuOptionsGenerate(wxCommandEvent& event)\r
-{\r
-    // Options->Generate Coins\r
-    GenerateBitcoins(event.IsChecked());\r
-}\r
-\r
-void CMainFrame::OnUpdateUIOptionsGenerate(wxUpdateUIEvent& event)\r
-{\r
-    event.Check(fGenerateBitcoins);\r
-}\r
-\r
-void CMainFrame::OnMenuOptionsChangeYourAddress(wxCommandEvent& event)\r
-{\r
-    // Options->Change Your Address\r
-    OnButtonChange(event);\r
-}\r
-\r
-void CMainFrame::OnMenuOptionsOptions(wxCommandEvent& event)\r
-{\r
-    // Options->Options\r
-    COptionsDialog dialog(this);\r
-    dialog.ShowModal();\r
-}\r
-\r
-void CMainFrame::OnMenuHelpAbout(wxCommandEvent& event)\r
-{\r
-    // Help->About\r
-    CAboutDialog dialog(this);\r
-    dialog.ShowModal();\r
-}\r
-\r
-void CMainFrame::OnButtonSend(wxCommandEvent& event)\r
-{\r
-    // Toolbar: Send\r
-    CSendDialog dialog(this);\r
-    dialog.ShowModal();\r
-}\r
-\r
-void CMainFrame::OnButtonAddressBook(wxCommandEvent& event)\r
-{\r
-    // Toolbar: Address Book\r
-    CAddressBookDialog dialogAddr(this, "", false);\r
-    if (dialogAddr.ShowModal() == 2)\r
-    {\r
-        // Send\r
-        CSendDialog dialogSend(this, dialogAddr.GetAddress());\r
-        dialogSend.ShowModal();\r
-    }\r
-}\r
-\r
-void CMainFrame::OnSetFocusAddress(wxFocusEvent& event)\r
-{\r
-    // Automatically select-all when entering window\r
-    m_textCtrlAddress->SetSelection(-1, -1);\r
-    fOnSetFocusAddress = true;\r
-    event.Skip();\r
-}\r
-\r
-void CMainFrame::OnMouseEventsAddress(wxMouseEvent& event)\r
-{\r
-    if (fOnSetFocusAddress)\r
-        m_textCtrlAddress->SetSelection(-1, -1);\r
-    fOnSetFocusAddress = false;\r
-    event.Skip();\r
-}\r
-\r
-void CMainFrame::OnButtonCopy(wxCommandEvent& event)\r
-{\r
-    // Copy address box to clipboard\r
-    if (wxTheClipboard->Open())\r
-    {\r
-        wxTheClipboard->SetData(new wxTextDataObject(m_textCtrlAddress->GetValue()));\r
-        wxTheClipboard->Close();\r
-    }\r
-}\r
-\r
-void CMainFrame::OnButtonChange(wxCommandEvent& event)\r
-{\r
-    CYourAddressDialog dialog(this, string(m_textCtrlAddress->GetValue()));\r
-    if (!dialog.ShowModal())\r
-        return;\r
-    string strAddress = (string)dialog.GetAddress();\r
-    if (strAddress != m_textCtrlAddress->GetValue())\r
-    {\r
-        uint160 hash160;\r
-        if (!AddressToHash160(strAddress, hash160))\r
-            return;\r
-        if (!mapPubKeys.count(hash160))\r
-            return;\r
-        CWalletDB().WriteDefaultKey(mapPubKeys[hash160]);\r
-        m_textCtrlAddress->SetValue(strAddress);\r
-    }\r
-}\r
-\r
-void CMainFrame::OnListItemActivatedAllTransactions(wxListEvent& event)\r
-{\r
-    uint256 hash((string)GetItemText(m_listCtrl, event.GetIndex(), 1));\r
-    CWalletTx wtx;\r
-    CRITICAL_BLOCK(cs_mapWallet)\r
-    {\r
-        map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);\r
-        if (mi == mapWallet.end())\r
-        {\r
-            printf("CMainFrame::OnListItemActivatedAllTransactions() : tx not found in mapWallet\n");\r
-            return;\r
-        }\r
-        wtx = (*mi).second;\r
-    }\r
-    CTxDetailsDialog dialog(this, wtx);\r
-    dialog.ShowModal();\r
-    //CTxDetailsDialog* pdialog = new CTxDetailsDialog(this, wtx);\r
-    //pdialog->Show();\r
-}\r
-\r
-void CMainFrame::OnListItemActivatedProductsSent(wxListEvent& event)\r
-{\r
-    CProduct& product = *(CProduct*)event.GetItem().GetData();\r
-    CEditProductDialog* pdialog = new CEditProductDialog(this);\r
-    pdialog->SetProduct(product);\r
-    pdialog->Show();\r
-}\r
-\r
-void CMainFrame::OnListItemActivatedOrdersSent(wxListEvent& event)\r
-{\r
-    CWalletTx& order = *(CWalletTx*)event.GetItem().GetData();\r
-    CViewOrderDialog* pdialog = new CViewOrderDialog(this, order, false);\r
-    pdialog->Show();\r
-}\r
-\r
-void CMainFrame::OnListItemActivatedOrdersReceived(wxListEvent& event)\r
-{\r
-    CWalletTx& order = *(CWalletTx*)event.GetItem().GetData();\r
-    CViewOrderDialog* pdialog = new CViewOrderDialog(this, order, true);\r
-    pdialog->Show();\r
-}\r
-\r
-\r
-\r
-\r
-\r
-\r
-\r
-//////////////////////////////////////////////////////////////////////////////\r
-//\r
-// CTxDetailsDialog\r
-//\r
-\r
-CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetailsDialogBase(parent)\r
-{\r
-    string strHTML;\r
-    strHTML.reserve(4000);\r
-    strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>";\r
-\r
-    int64 nTime = wtx.GetTxTime();\r
-    int64 nCredit = wtx.GetCredit();\r
-    int64 nDebit = wtx.GetDebit();\r
-    int64 nNet = nCredit - nDebit;\r
-\r
-\r
-\r
-    strHTML += "<b>Status:</b> " + FormatTxStatus(wtx);\r
-    int nRequests = wtx.GetRequestCount();\r
-    if (nRequests != -1)\r
-    {\r
-        if (nRequests == 0)\r
-            strHTML += ", has not been successfully broadcast yet";\r
-        else if (nRequests == 1)\r
-            strHTML += strprintf(", broadcast through %d node", nRequests);\r
-        else\r
-            strHTML += strprintf(", broadcast through %d nodes", nRequests);\r
-    }\r
-    strHTML += "<br>";\r
-\r
-    strHTML += "<b>Date:</b> " + (nTime ? DateTimeStr(nTime) : "") + "<br>";\r
-\r
-\r
-    //\r
-    // From\r
-    //\r
-    if (wtx.IsCoinBase())\r
-    {\r
-        strHTML += "<b>Source:</b> Generated<br>";\r
-    }\r
-    else if (!wtx.mapValue["from"].empty())\r
-    {\r
-        // Online transaction\r
-        if (!wtx.mapValue["from"].empty())\r
-            strHTML += "<b>From:</b> " + HtmlEscape(wtx.mapValue["from"]) + "<br>";\r
-    }\r
-    else\r
-    {\r
-        // Offline transaction\r
-        if (nNet > 0)\r
-        {\r
-            // Credit\r
-            foreach(const CTxOut& txout, wtx.vout)\r
-            {\r
-                if (txout.IsMine())\r
-                {\r
-                    vector<unsigned char> vchPubKey;\r
-                    if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey))\r
-                    {\r
-                        string strAddress = PubKeyToAddress(vchPubKey);\r
-                        if (mapAddressBook.count(strAddress))\r
-                        {\r
-                            strHTML += "<b>From:</b> unknown<br>";\r
-                            strHTML += "<b>To:</b> ";\r
-                            strHTML += HtmlEscape(strAddress);\r
-                            if (!mapAddressBook[strAddress].empty())\r
-                                strHTML += " (yours, label: " + mapAddressBook[strAddress] + ")";\r
-                            else\r
-                                strHTML += " (yours)";\r
-                            strHTML += "<br>";\r
-                        }\r
-                    }\r
-                    break;\r
-                }\r
-            }\r
-        }\r
-    }\r
-\r
-\r
-    //\r
-    // To\r
-    //\r
-    string strAddress;\r
-    if (!wtx.mapValue["to"].empty())\r
-    {\r
-        // Online transaction\r
-        strAddress = wtx.mapValue["to"];\r
-        strHTML += "<b>To:</b> ";\r
-        if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())\r
-            strHTML += mapAddressBook[strAddress] + " ";\r
-        strHTML += HtmlEscape(strAddress) + "<br>";\r
-    }\r
-\r
-\r
-    //\r
-    // Amount\r
-    //\r
-    if (wtx.IsCoinBase() && nCredit == 0)\r
-    {\r
-        //\r
-        // Coinbase\r
-        //\r
-        int64 nUnmatured = 0;\r
-        foreach(const CTxOut& txout, wtx.vout)\r
-            nUnmatured += txout.GetCredit();\r
-        if (wtx.IsInMainChain())\r
-            strHTML += strprintf("<b>Credit:</b> (%s matures in %d more blocks)<br>", FormatMoney(nUnmatured).c_str(), wtx.GetBlocksToMaturity());\r
-        else\r
-            strHTML += "<b>Credit:</b> (not accepted)<br>";\r
-    }\r
-    else if (nNet > 0)\r
-    {\r
-        //\r
-        // Credit\r
-        //\r
-        strHTML += "<b>Credit:</b> " + FormatMoney(nNet) + "<br>";\r
-    }\r
-    else\r
-    {\r
-        bool fAllFromMe = true;\r
-        foreach(const CTxIn& txin, wtx.vin)\r
-            fAllFromMe = fAllFromMe && txin.IsMine();\r
-\r
-        bool fAllToMe = true;\r
-        foreach(const CTxOut& txout, wtx.vout)\r
-            fAllToMe = fAllToMe && txout.IsMine();\r
-\r
-        if (fAllFromMe)\r
-        {\r
-            //\r
-            // Debit\r
-            //\r
-            foreach(const CTxOut& txout, wtx.vout)\r
-            {\r
-                if (txout.IsMine())\r
-                    continue;\r
-\r
-                if (wtx.mapValue["to"].empty())\r
-                {\r
-                    // Offline transaction\r
-                    uint160 hash160;\r
-                    if (ExtractHash160(txout.scriptPubKey, hash160))\r
-                    {\r
-                        string strAddress = Hash160ToAddress(hash160);\r
-                        strHTML += "<b>To:</b> ";\r
-                        if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())\r
-                            strHTML += mapAddressBook[strAddress] + " ";\r
-                        strHTML += strAddress;\r
-                        strHTML += "<br>";\r
-                    }\r
-                }\r
-\r
-                strHTML += "<b>Debit:</b> " + FormatMoney(-txout.nValue) + "<br>";\r
-            }\r
-\r
-            if (fAllToMe)\r
-            {\r
-                // Payment to self\r
-                /// issue: can't tell which is the payment and which is the change anymore\r
-                //int64 nValue = wtx.vout[0].nValue;\r
-                //strHTML += "<b>Debit:</b> " + FormatMoney(-nValue) + "<br>";\r
-                //strHTML += "<b>Credit:</b> " + FormatMoney(nValue) + "<br>";\r
-            }\r
-\r
-            int64 nTxFee = nDebit - wtx.GetValueOut();\r
-            if (nTxFee > 0)\r
-                strHTML += "<b>Transaction fee:</b> " + FormatMoney(-nTxFee) + "<br>";\r
-        }\r
-        else\r
-        {\r
-            //\r
-            // Mixed debit transaction\r
-            //\r
-            foreach(const CTxIn& txin, wtx.vin)\r
-                if (txin.IsMine())\r
-                    strHTML += "<b>Debit:</b> " + FormatMoney(-txin.GetDebit()) + "<br>";\r
-            foreach(const CTxOut& txout, wtx.vout)\r
-                if (txout.IsMine())\r
-                    strHTML += "<b>Credit:</b> " + FormatMoney(txout.GetCredit()) + "<br>";\r
-        }\r
-    }\r
-\r
-    strHTML += "<b>Net amount:</b> " + FormatMoney(nNet, true) + "<br>";\r
-\r
-\r
-    //\r
-    // Message\r
-    //\r
-    if (!wtx.mapValue["message"].empty())\r
-        strHTML += "<br><b>Message:</b><br>" + HtmlEscape(wtx.mapValue["message"], true) + "<br>";\r
-\r
-    if (wtx.IsCoinBase())\r
-        strHTML += "<br>Generated coins must wait 120 blocks before they can be spent.  When you generated this block, it was broadcast to the network to be added to the block chain.  If it fails to get into the chain, it will change to \"not accepted\" and not be spendable.  This may occasionally happen if another node generates a block within a few seconds of yours.<br>";\r
-\r
-\r
-    //\r
-    // Debug view\r
-    //\r
-    if (fDebug)\r
-    {\r
-        strHTML += "<hr><br>debug print<br><br>";\r
-        foreach(const CTxIn& txin, wtx.vin)\r
-            if (txin.IsMine())\r
-                strHTML += "<b>Debit:</b> " + FormatMoney(-txin.GetDebit()) + "<br>";\r
-        foreach(const CTxOut& txout, wtx.vout)\r
-            if (txout.IsMine())\r
-                strHTML += "<b>Credit:</b> " + FormatMoney(txout.GetCredit()) + "<br>";\r
-\r
-        strHTML += "<b>Inputs:</b><br>";\r
-        CRITICAL_BLOCK(cs_mapWallet)\r
-        {\r
-            foreach(const CTxIn& txin, wtx.vin)\r
-            {\r
-                COutPoint prevout = txin.prevout;\r
-                map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);\r
-                if (mi != mapWallet.end())\r
-                {\r
-                    const CWalletTx& prev = (*mi).second;\r
-                    if (prevout.n < prev.vout.size())\r
-                    {\r
-                        strHTML += HtmlEscape(prev.ToString(), true);\r
-                        strHTML += " &nbsp;&nbsp; " + FormatTxStatus(prev) + ", ";\r
-                        strHTML = strHTML + "IsMine=" + (prev.vout[prevout.n].IsMine() ? "true" : "false") + "<br>";\r
-                    }\r
-                }\r
-            }\r
-        }\r
-\r
-        strHTML += "<br><hr><br><b>Transaction:</b><br>";\r
-        strHTML += HtmlEscape(wtx.ToString(), true);\r
-    }\r
-\r
-\r
-\r
-    strHTML += "</font></html>";\r
-    string(strHTML.begin(), strHTML.end()).swap(strHTML);\r
-    m_htmlWin->SetPage(strHTML);\r
-    m_buttonOK->SetFocus();\r
-}\r
-\r
-void CTxDetailsDialog::OnButtonOK(wxCommandEvent& event)\r
-{\r
-    Close();\r
-    //Destroy();\r
-}\r
-\r
-\r
-\r
-\r
-\r
-//////////////////////////////////////////////////////////////////////////////\r
-//\r
-// COptionsDialog\r
-//\r
-\r
-COptionsDialog::COptionsDialog(wxWindow* parent) : COptionsDialogBase(parent)\r
-{\r
-    // Set up list box of page choices\r
-    m_listBox->Append("Main");\r
-    //m_listBox->Append("Test 2");\r
-    m_listBox->SetSelection(0);\r
-    SelectPage(0);\r
-#ifndef __WXMSW__\r
-    m_checkBoxMinimizeOnClose->SetLabel("&Minimize on close");\r
-    m_checkBoxStartOnSystemStartup->Enable(false); // not implemented yet\r
-#endif\r
-\r
-    // Init values\r
-    m_textCtrlTransactionFee->SetValue(FormatMoney(nTransactionFee));\r
-    m_checkBoxLimitProcessors->SetValue(fLimitProcessors);\r
-    m_spinCtrlLimitProcessors->Enable(fLimitProcessors);\r
-    m_spinCtrlLimitProcessors->SetValue(nLimitProcessors);\r
-    int nProcessors = wxThread::GetCPUCount();\r
-    if (nProcessors < 1)\r
-        nProcessors = 999;\r
-    m_spinCtrlLimitProcessors->SetRange(1, nProcessors);\r
-    m_checkBoxStartOnSystemStartup->SetValue(fTmpStartOnSystemStartup = GetStartOnSystemStartup());\r
-    m_checkBoxMinimizeToTray->SetValue(fMinimizeToTray);\r
-    m_checkBoxMinimizeOnClose->SetValue(fMinimizeOnClose);\r
-    m_checkBoxUseProxy->SetValue(fUseProxy);\r
-    m_textCtrlProxyIP->Enable(fUseProxy);\r
-    m_textCtrlProxyPort->Enable(fUseProxy);\r
-    m_staticTextProxyIP->Enable(fUseProxy);\r
-    m_staticTextProxyPort->Enable(fUseProxy);\r
-    m_textCtrlProxyIP->SetValue(addrProxy.ToStringIP());\r
-    m_textCtrlProxyPort->SetValue(addrProxy.ToStringPort());\r
-\r
-    m_buttonOK->SetFocus();\r
-}\r
-\r
-void COptionsDialog::SelectPage(int nPage)\r
-{\r
-    m_panelMain->Show(nPage == 0);\r
-    m_panelTest2->Show(nPage == 1);\r
-\r
-    m_scrolledWindow->Layout();\r
-    m_scrolledWindow->SetScrollbars(0, 0, 0, 0, 0, 0);\r
-}\r
-\r
-void COptionsDialog::OnListBox(wxCommandEvent& event)\r
-{\r
-    SelectPage(event.GetSelection());\r
-}\r
-\r
-void COptionsDialog::OnKillFocusTransactionFee(wxFocusEvent& event)\r
-{\r
-    int64 nTmp = nTransactionFee;\r
-    ParseMoney(m_textCtrlTransactionFee->GetValue(), nTmp);\r
-    m_textCtrlTransactionFee->SetValue(FormatMoney(nTmp));\r
-}\r
-\r
-void COptionsDialog::OnCheckBoxLimitProcessors(wxCommandEvent& event)\r
-{\r
-    m_spinCtrlLimitProcessors->Enable(event.IsChecked());\r
-}\r
-\r
-void COptionsDialog::OnCheckBoxUseProxy(wxCommandEvent& event)\r
-{\r
-    m_textCtrlProxyIP->Enable(event.IsChecked());\r
-    m_textCtrlProxyPort->Enable(event.IsChecked());\r
-    m_staticTextProxyIP->Enable(event.IsChecked());\r
-    m_staticTextProxyPort->Enable(event.IsChecked());\r
-}\r
-\r
-CAddress COptionsDialog::GetProxyAddr()\r
-{\r
-    // Be careful about byte order, addr.ip and addr.port are big endian\r
-    CAddress addr(m_textCtrlProxyIP->GetValue() + ":" + m_textCtrlProxyPort->GetValue());\r
-    if (addr.ip == INADDR_NONE)\r
-        addr.ip = addrProxy.ip;\r
-    int nPort = atoi(m_textCtrlProxyPort->GetValue());\r
-    addr.port = htons(nPort);\r
-    if (nPort <= 0 || nPort > USHRT_MAX)\r
-        addr.port = addrProxy.port;\r
-    return addr;\r
-}\r
-\r
-void COptionsDialog::OnKillFocusProxy(wxFocusEvent& event)\r
-{\r
-    m_textCtrlProxyIP->SetValue(GetProxyAddr().ToStringIP());\r
-    m_textCtrlProxyPort->SetValue(GetProxyAddr().ToStringPort());\r
-}\r
-\r
-\r
-void COptionsDialog::OnButtonOK(wxCommandEvent& event)\r
-{\r
-    OnButtonApply(event);\r
-    Close();\r
-}\r
-\r
-void COptionsDialog::OnButtonCancel(wxCommandEvent& event)\r
-{\r
-    Close();\r
-}\r
-\r
-void COptionsDialog::OnButtonApply(wxCommandEvent& event)\r
-{\r
-    CWalletDB walletdb;\r
-\r
-    int64 nPrevTransactionFee = nTransactionFee;\r
-    if (ParseMoney(m_textCtrlTransactionFee->GetValue(), nTransactionFee) && nTransactionFee != nPrevTransactionFee)\r
-        walletdb.WriteSetting("nTransactionFee", nTransactionFee);\r
-\r
-    int nPrevMaxProc = (fLimitProcessors ? nLimitProcessors : INT_MAX);\r
-    if (fLimitProcessors != m_checkBoxLimitProcessors->GetValue())\r
-    {\r
-        fLimitProcessors = m_checkBoxLimitProcessors->GetValue();\r
-        walletdb.WriteSetting("fLimitProcessors", fLimitProcessors);\r
-    }\r
-    if (nLimitProcessors != m_spinCtrlLimitProcessors->GetValue())\r
-    {\r
-        nLimitProcessors = m_spinCtrlLimitProcessors->GetValue();\r
-        walletdb.WriteSetting("nLimitProcessors", nLimitProcessors);\r
-    }\r
-    if (fGenerateBitcoins && (fLimitProcessors ? nLimitProcessors : INT_MAX) > nPrevMaxProc)\r
-        GenerateBitcoins(fGenerateBitcoins);\r
-\r
-    if (fTmpStartOnSystemStartup != m_checkBoxStartOnSystemStartup->GetValue())\r
-    {\r
-        fTmpStartOnSystemStartup = m_checkBoxStartOnSystemStartup->GetValue();\r
-        SetStartOnSystemStartup(fTmpStartOnSystemStartup);\r
-    }\r
-\r
-    if (fMinimizeToTray != m_checkBoxMinimizeToTray->GetValue())\r
-    {\r
-        fMinimizeToTray = m_checkBoxMinimizeToTray->GetValue();\r
-        walletdb.WriteSetting("fMinimizeToTray", fMinimizeToTray);\r
-        ptaskbaricon->Show(fMinimizeToTray || fClosedToTray);\r
-    }\r
-\r
-    if (fMinimizeOnClose != m_checkBoxMinimizeOnClose->GetValue())\r
-    {\r
-        fMinimizeOnClose = m_checkBoxMinimizeOnClose->GetValue();\r
-        walletdb.WriteSetting("fMinimizeOnClose", fMinimizeOnClose);\r
-    }\r
-\r
-    fUseProxy = m_checkBoxUseProxy->GetValue();\r
-    walletdb.WriteSetting("fUseProxy", fUseProxy);\r
-\r
-    addrProxy = GetProxyAddr();\r
-    walletdb.WriteSetting("addrProxy", addrProxy);\r
-}\r
-\r
-\r
-\r
-\r
-\r
-\r
-//////////////////////////////////////////////////////////////////////////////\r
-//\r
-// CAboutDialog\r
-//\r
-\r
-CAboutDialog::CAboutDialog(wxWindow* parent) : CAboutDialogBase(parent)\r
-{\r
-    m_staticTextVersion->SetLabel(strprintf("version 0.%d.%d beta", VERSION/100, VERSION%100));\r
-\r
-    // Workaround until upgrade to wxWidgets supporting UTF-8\r
-    wxString str = m_staticTextMain->GetLabel();\r
-#if !wxUSE_UNICODE\r
-    if (str.Find('Â') != wxNOT_FOUND)\r
-        str.Remove(str.Find('Â'), 1);\r
-#endif\r
-#ifndef __WXMSW__\r
-    SetSize(510, 380);\r
-#endif\r
-    m_staticTextMain->SetLabel(str);\r
-}\r
-\r
-void CAboutDialog::OnButtonOK(wxCommandEvent& event)\r
-{\r
-    Close();\r
-}\r
-\r
-\r
-\r
-\r
-\r
-\r
-//////////////////////////////////////////////////////////////////////////////\r
-//\r
-// CSendDialog\r
-//\r
-\r
-CSendDialog::CSendDialog(wxWindow* parent, const wxString& strAddress) : CSendDialogBase(parent)\r
-{\r
-    // Init\r
-    m_textCtrlAddress->SetValue(strAddress);\r
-    m_choiceTransferType->SetSelection(0);\r
-    m_bitmapCheckMark->Show(false);\r
-    fEnabledPrev = true;\r
-    m_textCtrlAddress->SetFocus();\r
-    //// todo: should add a display of your balance for convenience\r
-#ifndef __WXMSW__\r
-    wxFont fontTmp = m_staticTextInstructions->GetFont();\r
-    if (fontTmp.GetPointSize() > 9);\r
-        fontTmp.SetPointSize(9);\r
-    m_staticTextInstructions->SetFont(fontTmp);\r
-    SetSize(725, 380);\r
-#endif\r
-\r
-    // Set Icon\r
-    wxIcon iconSend;\r
-    iconSend.CopyFromBitmap(wxBitmap(send16noshadow_xpm));\r
-    SetIcon(iconSend);\r
-\r
-    wxCommandEvent event;\r
-    OnTextAddress(event);\r
-\r
-    // Fixup the tab order\r
-    m_buttonPaste->MoveAfterInTabOrder(m_buttonCancel);\r
-    m_buttonAddress->MoveAfterInTabOrder(m_buttonPaste);\r
-    this->Layout();\r
-}\r
-\r
-void CSendDialog::OnTextAddress(wxCommandEvent& event)\r
-{\r
-    // Check mark\r
-    bool fBitcoinAddress = IsValidBitcoinAddress(m_textCtrlAddress->GetValue());\r
-    m_bitmapCheckMark->Show(fBitcoinAddress);\r
-\r
-    // Grey out message if bitcoin address\r
-    bool fEnable = !fBitcoinAddress;\r
-    m_staticTextFrom->Enable(fEnable);\r
-    m_textCtrlFrom->Enable(fEnable);\r
-    m_staticTextMessage->Enable(fEnable);\r
-    m_textCtrlMessage->Enable(fEnable);\r
-    m_textCtrlMessage->SetBackgroundColour(wxSystemSettings::GetColour(fEnable ? wxSYS_COLOUR_WINDOW : wxSYS_COLOUR_BTNFACE));\r
-    if (!fEnable && fEnabledPrev)\r
-    {\r
-        strFromSave    = m_textCtrlFrom->GetValue();\r
-        strMessageSave = m_textCtrlMessage->GetValue();\r
-        m_textCtrlFrom->SetValue("Will appear as \"From: Unknown\"");\r
-        m_textCtrlMessage->SetValue("Can't include a message when sending to a Bitcoin address");\r
-    }\r
-    else if (fEnable && !fEnabledPrev)\r
-    {\r
-        m_textCtrlFrom->SetValue(strFromSave);\r
-        m_textCtrlMessage->SetValue(strMessageSave);\r
-    }\r
-    fEnabledPrev = fEnable;\r
-}\r
-\r
-void CSendDialog::OnKillFocusAmount(wxFocusEvent& event)\r
-{\r
-    // Reformat the amount\r
-    if (m_textCtrlAmount->GetValue().Trim().empty())\r
-        return;\r
-    int64 nTmp;\r
-    if (ParseMoney(m_textCtrlAmount->GetValue(), nTmp))\r
-        m_textCtrlAmount->SetValue(FormatMoney(nTmp));\r
-}\r
-\r
-void CSendDialog::OnButtonAddressBook(wxCommandEvent& event)\r
-{\r
-    // Open address book\r
-    CAddressBookDialog dialog(this, m_textCtrlAddress->GetValue(), true);\r
-    if (dialog.ShowModal())\r
-        m_textCtrlAddress->SetValue(dialog.GetAddress());\r
-}\r
-\r
-void CSendDialog::OnButtonPaste(wxCommandEvent& event)\r
-{\r
-    // Copy clipboard to address box\r
-    if (wxTheClipboard->Open())\r
-    {\r
-        if (wxTheClipboard->IsSupported(wxDF_TEXT))\r
-        {\r
-            wxTextDataObject data;\r
-            wxTheClipboard->GetData(data);\r
-            m_textCtrlAddress->SetValue(data.GetText());\r
-        }\r
-        wxTheClipboard->Close();\r
-    }\r
-}\r
-\r
-void CSendDialog::OnButtonSend(wxCommandEvent& event)\r
-{\r
-    CWalletTx wtx;\r
-    string strAddress = (string)m_textCtrlAddress->GetValue();\r
-\r
-    // Parse amount\r
-    int64 nValue = 0;\r
-    if (!ParseMoney(m_textCtrlAmount->GetValue(), nValue) || nValue <= 0)\r
-    {\r
-        wxMessageBox("Error in amount  ", "Send Coins");\r
-        return;\r
-    }\r
-    if (nValue > GetBalance())\r
-    {\r
-        wxMessageBox("Amount exceeds your balance  ", "Send Coins");\r
-        return;\r
-    }\r
-    if (nValue + nTransactionFee > GetBalance())\r
-    {\r
-        wxMessageBox(string("Total exceeds your balance when the ") + FormatMoney(nTransactionFee) + " transaction fee is included  ", "Send Coins");\r
-        return;\r
-    }\r
-\r
-    // Parse bitcoin address\r
-    uint160 hash160;\r
-    bool fBitcoinAddress = AddressToHash160(strAddress, hash160);\r
-\r
-    if (fBitcoinAddress)\r
-    {\r
-        // Send to bitcoin address\r
-        CScript scriptPubKey;\r
-        scriptPubKey << OP_DUP << OP_HASH160 << hash160 << OP_EQUALVERIFY << OP_CHECKSIG;\r
-\r
-        if (!SendMoney(scriptPubKey, nValue, wtx))\r
-            return;\r
-\r
-        wxMessageBox("Payment sent  ", "Sending...");\r
-    }\r
-    else\r
-    {\r
-        // Parse IP address\r
-        CAddress addr(strAddress);\r
-        if (!addr.IsValid())\r
-        {\r
-            wxMessageBox("Invalid address  ", "Send Coins");\r
-            return;\r
-        }\r
-\r
-        // Message\r
-        wtx.mapValue["to"] = strAddress;\r
-        wtx.mapValue["from"] = m_textCtrlFrom->GetValue();\r
-        wtx.mapValue["message"] = m_textCtrlMessage->GetValue();\r
-\r
-        // Send to IP address\r
-        CSendingDialog* pdialog = new CSendingDialog(this, addr, nValue, wtx);\r
-        if (!pdialog->ShowModal())\r
-            return;\r
-    }\r
-\r
-    if (!mapAddressBook.count(strAddress))\r
-        SetAddressBookName(strAddress, "");\r
-\r
-    EndModal(true);\r
-}\r
-\r
-void CSendDialog::OnButtonCancel(wxCommandEvent& event)\r
-{\r
-    // Cancel\r
-    EndModal(false);\r
-}\r
-\r
-\r
-\r
-\r
-\r
-\r
-//////////////////////////////////////////////////////////////////////////////\r
-//\r
-// CSendingDialog\r
-//\r
-\r
-CSendingDialog::CSendingDialog(wxWindow* parent, const CAddress& addrIn, int64 nPriceIn, const CWalletTx& wtxIn) : CSendingDialogBase(NULL) // we have to give null so parent can't destroy us\r
-{\r
-    addr = addrIn;\r
-    nPrice = nPriceIn;\r
-    wtx = wtxIn;\r
-    start = wxDateTime::UNow();\r
-    memset(pszStatus, 0, sizeof(pszStatus));\r
-    fCanCancel = true;\r
-    fAbort = false;\r
-    fSuccess = false;\r
-    fUIDone = false;\r
-    fWorkDone = false;\r
-#ifndef __WXMSW__\r
-    SetSize(1.2 * GetSize().GetWidth(), 1.05 * GetSize().GetHeight());\r
-#endif\r
-\r
-    SetTitle(strprintf("Sending %s to %s", FormatMoney(nPrice).c_str(), wtx.mapValue["to"].c_str()));\r
-    m_textCtrlStatus->SetValue("");\r
-\r
-    CreateThread(SendingDialogStartTransfer, this);\r
-}\r
-\r
-CSendingDialog::~CSendingDialog()\r
-{\r
-    printf("~CSendingDialog()\n");\r
-}\r
-\r
-void CSendingDialog::Close()\r
-{\r
-    // Last one out turn out the lights.\r
-    // fWorkDone signals that work side is done and UI thread should call destroy.\r
-    // fUIDone signals that UI window has closed and work thread should call destroy.\r
-    // This allows the window to disappear and end modality when cancelled\r
-    // without making the user wait for ConnectNode to return.  The dialog object\r
-    // hangs around in the background until the work thread exits.\r
-    if (IsModal())\r
-        EndModal(fSuccess);\r
-    else\r
-        Show(false);\r
-    if (fWorkDone)\r
-        Destroy();\r
-    else\r
-        fUIDone = true;\r
-}\r
-\r
-void CSendingDialog::OnClose(wxCloseEvent& event)\r
-{\r
-    if (!event.CanVeto() || fWorkDone || fAbort || !fCanCancel)\r
-    {\r
-        Close();\r
-    }\r
-    else\r
-    {\r
-        event.Veto();\r
-        wxCommandEvent cmdevent;\r
-        OnButtonCancel(cmdevent);\r
-    }\r
-}\r
-\r
-void CSendingDialog::OnButtonOK(wxCommandEvent& event)\r
-{\r
-    if (fWorkDone)\r
-        Close();\r
-}\r
-\r
-void CSendingDialog::OnButtonCancel(wxCommandEvent& event)\r
-{\r
-    if (fCanCancel)\r
-        fAbort = true;\r
-}\r
-\r
-void CSendingDialog::OnPaint(wxPaintEvent& event)\r
-{\r
-    if (strlen(pszStatus) > 130)\r
-        m_textCtrlStatus->SetValue(string("\n") + pszStatus);\r
-    else\r
-        m_textCtrlStatus->SetValue(string("\n\n") + pszStatus);\r
-    m_staticTextSending->SetFocus();\r
-    if (!fCanCancel)\r
-        m_buttonCancel->Enable(false);\r
-    if (fWorkDone)\r
-    {\r
-        m_buttonOK->Enable(true);\r
-        m_buttonOK->SetFocus();\r
-        m_buttonCancel->Enable(false);\r
-    }\r
-    if (fAbort && fCanCancel && IsShown())\r
-    {\r
-        strcpy(pszStatus, "CANCELLED");\r
-        m_buttonOK->Enable(true);\r
-        m_buttonOK->SetFocus();\r
-        m_buttonCancel->Enable(false);\r
-        m_buttonCancel->SetLabel("Cancelled");\r
-        Close();\r
-        wxMessageBox("Transfer cancelled  ", "Sending...", wxOK, this);\r
-    }\r
-    event.Skip();\r
-}\r
-\r
-\r
-//\r
-// Everything from here on is not in the UI thread and must only communicate\r
-// with the rest of the dialog through variables and calling repaint.\r
-//\r
-\r
-void CSendingDialog::Repaint()\r
-{\r
-    Refresh();\r
-    wxPaintEvent event;\r
-    GetEventHandler()->AddPendingEvent(event);\r
-}\r
-\r
-bool CSendingDialog::Status()\r
-{\r
-    if (fUIDone)\r
-    {\r
-        Destroy();\r
-        return false;\r
-    }\r
-    if (fAbort && fCanCancel)\r
-    {\r
-        memset(pszStatus, 0, 10);\r
-        strcpy(pszStatus, "CANCELLED");\r
-        Repaint();\r
-        fWorkDone = true;\r
-        return false;\r
-    }\r
-    return true;\r
-}\r
-\r
-bool CSendingDialog::Status(const string& str)\r
-{\r
-    if (!Status())\r
-        return false;\r
-\r
-    // This can be read by the UI thread at any time,\r
-    // so copy in a way that can be read cleanly at all times.\r
-    memset(pszStatus, 0, min(str.size()+1, sizeof(pszStatus)));\r
-    strlcpy(pszStatus, str.c_str(), sizeof(pszStatus));\r
-\r
-    Repaint();\r
-    return true;\r
-}\r
-\r
-bool CSendingDialog::Error(const string& str)\r
-{\r
-    fCanCancel = false;\r
-    fWorkDone = true;\r
-    Status(string("Error: ") + str);\r
-    return false;\r
-}\r
-\r
-void SendingDialogStartTransfer(void* parg)\r
-{\r
-    ((CSendingDialog*)parg)->StartTransfer();\r
-}\r
-\r
-void CSendingDialog::StartTransfer()\r
-{\r
-    // Make sure we have enough money\r
-    if (nPrice + nTransactionFee > GetBalance())\r
-    {\r
-        Error("You don't have enough money");\r
-        return;\r
-    }\r
-\r
-    // We may have connected already for product details\r
-    if (!Status("Connecting..."))\r
-        return;\r
-    CNode* pnode = ConnectNode(addr, 15 * 60);\r
-    if (!pnode)\r
-    {\r
-        Error("Unable to connect");\r
-        return;\r
-    }\r
-\r
-    // Send order to seller, with response going to OnReply2 via event handler\r
-    if (!Status("Requesting public key..."))\r
-        return;\r
-    pnode->PushRequest("checkorder", wtx, SendingDialogOnReply2, this);\r
-}\r
-\r
-void SendingDialogOnReply2(void* parg, CDataStream& vRecv)\r
-{\r
-    ((CSendingDialog*)parg)->OnReply2(vRecv);\r
-}\r
-\r
-void CSendingDialog::OnReply2(CDataStream& vRecv)\r
-{\r
-    if (!Status("Received public key..."))\r
-        return;\r
-\r
-    CScript scriptPubKey;\r
-    int nRet;\r
-    try\r
-    {\r
-        vRecv >> nRet;\r
-        if (nRet > 0)\r
-        {\r
-            string strMessage;\r
-            vRecv >> strMessage;\r
-            Error("Transfer was not accepted");\r
-            //// todo: enlarge the window and enable a hidden white box to put seller's message\r
-            return;\r
-        }\r
-        vRecv >> scriptPubKey;\r
-    }\r
-    catch (...)\r
-    {\r
-        //// what do we want to do about this?\r
-        Error("Invalid response received");\r
-        return;\r
-    }\r
-\r
-    // Pause to give the user a chance to cancel\r
-    while (wxDateTime::UNow() < start + wxTimeSpan(0, 0, 0, 2 * 1000))\r
-    {\r
-        Sleep(200);\r
-        if (!Status())\r
-            return;\r
-    }\r
-\r
-    CRITICAL_BLOCK(cs_main)\r
-    {\r
-        // Pay\r
-        if (!Status("Creating transaction..."))\r
-            return;\r
-        if (nPrice + nTransactionFee > GetBalance())\r
-        {\r
-            Error("You don't have enough money");\r
-            return;\r
-        }\r
-        CKey key;\r
-        int64 nFeeRequired;\r
-        if (!CreateTransaction(scriptPubKey, nPrice, wtx, key, nFeeRequired))\r
-        {\r
-            if (nPrice + nFeeRequired > GetBalance())\r
-                Error(strprintf("This is an oversized transaction that requires a transaction fee of %s", FormatMoney(nFeeRequired).c_str()));\r
-            else\r
-                Error("Transaction creation failed");\r
-            return;\r
-        }\r
-\r
-        // Make sure we're still connected\r
-        CNode* pnode = ConnectNode(addr, 2 * 60 * 60);\r
-        if (!pnode)\r
-        {\r
-            Error("Lost connection, transaction cancelled");\r
-            return;\r
-        }\r
-\r
-        // Last chance to cancel\r
-        Sleep(50);\r
-        if (!Status())\r
-            return;\r
-        fCanCancel = false;\r
-        if (fAbort)\r
-        {\r
-            fCanCancel = true;\r
-            if (!Status())\r
-                return;\r
-            fCanCancel = false;\r
-        }\r
-        if (!Status("Sending payment..."))\r
-            return;\r
-\r
-        // Commit\r
-        if (!CommitTransactionSpent(wtx, key))\r
-        {\r
-            Error("Error finalizing payment");\r
-            return;\r
-        }\r
-\r
-        // Send payment tx to seller, with response going to OnReply3 via event handler\r
-        pnode->PushRequest("submitorder", wtx, SendingDialogOnReply3, this);\r
-\r
-        // Accept and broadcast transaction\r
-        if (!wtx.AcceptTransaction())\r
-            printf("ERROR: CSendingDialog : wtxNew.AcceptTransaction() %s failed\n", wtx.GetHash().ToString().c_str());\r
-        wtx.RelayWalletTransaction();\r
-\r
-        Status("Waiting for confirmation...");\r
-        MainFrameRepaint();\r
-    }\r
-}\r
-\r
-void SendingDialogOnReply3(void* parg, CDataStream& vRecv)\r
-{\r
-    ((CSendingDialog*)parg)->OnReply3(vRecv);\r
-}\r
-\r
-void CSendingDialog::OnReply3(CDataStream& vRecv)\r
-{\r
-    int nRet;\r
-    try\r
-    {\r
-        vRecv >> nRet;\r
-        if (nRet > 0)\r
-        {\r
-            Error("The payment was sent, but the recipient was unable to verify it.\n"\r
-                  "The transaction is recorded and will credit to the recipient,\n"\r
-                  "but the comment information will be blank.");\r
-            return;\r
-        }\r
-    }\r
-    catch (...)\r
-    {\r
-        //// what do we want to do about this?\r
-        Error("Payment was sent, but an invalid response was received");\r
-        return;\r
-    }\r
-\r
-    fSuccess = true;\r
-    fWorkDone = true;\r
-    Status("Payment completed");\r
-}\r
-\r
-\r
-\r
-\r
-\r
-\r
-//////////////////////////////////////////////////////////////////////////////\r
-//\r
-// CYourAddressDialog\r
-//\r
-\r
-CYourAddressDialog::CYourAddressDialog(wxWindow* parent, const string& strInitSelected) : CYourAddressDialogBase(parent)\r
-{\r
-    // Init column headers\r
-    m_listCtrl->InsertColumn(0, "Label", wxLIST_FORMAT_LEFT, 200);\r
-    m_listCtrl->InsertColumn(1, "Bitcoin Address", wxLIST_FORMAT_LEFT, 350);\r
-    m_listCtrl->SetFocus();\r
-\r
-    // Fill listctrl with address book data\r
-    CRITICAL_BLOCK(cs_mapKeys)\r
-    {\r
-        foreach(const PAIRTYPE(string, string)& item, mapAddressBook)\r
-        {\r
-            string strAddress = item.first;\r
-            string strName = item.second;\r
-            uint160 hash160;\r
-            bool fMine = (AddressToHash160(strAddress, hash160) && mapPubKeys.count(hash160));\r
-            if (fMine)\r
-            {\r
-                int nIndex = InsertLine(m_listCtrl, strName, strAddress);\r
-                if (strAddress == strInitSelected)\r
-                    m_listCtrl->SetItemState(nIndex, wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED, wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED);\r
-            }\r
-        }\r
-    }\r
-}\r
-\r
-wxString CYourAddressDialog::GetAddress()\r
-{\r
-    int nIndex = GetSelection(m_listCtrl);\r
-    if (nIndex == -1)\r
-        return "";\r
-    return GetItemText(m_listCtrl, nIndex, 1);\r
-}\r
-\r
-void CYourAddressDialog::OnListEndLabelEdit(wxListEvent& event)\r
-{\r
-    // Update address book with edited name\r
-    if (event.IsEditCancelled())\r
-        return;\r
-    string strAddress = (string)GetItemText(m_listCtrl, event.GetIndex(), 1);\r
-    SetAddressBookName(strAddress, string(event.GetText()));\r
-    pframeMain->RefreshListCtrl();\r
-}\r
-\r
-void CYourAddressDialog::OnListItemSelected(wxListEvent& event)\r
-{\r
-}\r
-\r
-void CYourAddressDialog::OnListItemActivated(wxListEvent& event)\r
-{\r
-    // Doubleclick edits item\r
-    wxCommandEvent event2;\r
-    OnButtonRename(event2);\r
-}\r
-\r
-void CYourAddressDialog::OnButtonRename(wxCommandEvent& event)\r
-{\r
-    // Ask new name\r
-    int nIndex = GetSelection(m_listCtrl);\r
-    if (nIndex == -1)\r
-        return;\r
-    string strName = (string)m_listCtrl->GetItemText(nIndex);\r
-    string strAddress = (string)GetItemText(m_listCtrl, nIndex, 1);\r
-    CGetTextFromUserDialog dialog(this, "Edit Address Label", "New Label", strName);\r
-    if (!dialog.ShowModal())\r
-        return;\r
-    strName = dialog.GetValue();\r
-\r
-    // Change name\r
-    SetAddressBookName(strAddress, strName);\r
-    m_listCtrl->SetItemText(nIndex, strName);\r
-    pframeMain->RefreshListCtrl();\r
-}\r
-\r
-void CYourAddressDialog::OnButtonNew(wxCommandEvent& event)\r
-{\r
-    // Ask name\r
-    CGetTextFromUserDialog dialog(this, "New Bitcoin Address", "Label", "");\r
-    if (!dialog.ShowModal())\r
-        return;\r
-    string strName = dialog.GetValue();\r
-\r
-    // Generate new key\r
-    string strAddress = PubKeyToAddress(GenerateNewKey());\r
-    SetAddressBookName(strAddress, strName);\r
-\r
-    // Add to list and select it\r
-    int nIndex = InsertLine(m_listCtrl, strName, strAddress);\r
-    SetSelection(m_listCtrl, nIndex);\r
-    m_listCtrl->SetFocus();\r
-}\r
-\r
-void CYourAddressDialog::OnButtonCopy(wxCommandEvent& event)\r
-{\r
-    // Copy address box to clipboard\r
-    if (wxTheClipboard->Open())\r
-    {\r
-        wxTheClipboard->SetData(new wxTextDataObject(GetAddress()));\r
-        wxTheClipboard->Close();\r
-    }\r
-}\r
-\r
-void CYourAddressDialog::OnButtonOK(wxCommandEvent& event)\r
-{\r
-    // OK\r
-    EndModal(true);\r
-}\r
-\r
-void CYourAddressDialog::OnButtonCancel(wxCommandEvent& event)\r
-{\r
-    // Cancel\r
-    EndModal(false);\r
-}\r
-\r
-void CYourAddressDialog::OnClose(wxCloseEvent& event)\r
-{\r
-    // Close\r
-    EndModal(false);\r
-}\r
-\r
-\r
-\r
-\r
-\r
-\r
-//////////////////////////////////////////////////////////////////////////////\r
-//\r
-// CAddressBookDialog\r
-//\r
-\r
-CAddressBookDialog::CAddressBookDialog(wxWindow* parent, const wxString& strInitSelected, bool fSendingIn) : CAddressBookDialogBase(parent)\r
-{\r
-    fSending = fSendingIn;\r
-    if (!fSending)\r
-        m_buttonCancel->Show(false);\r
-\r
-    // Init column headers\r
-    m_listCtrl->InsertColumn(0, "Name", wxLIST_FORMAT_LEFT, 200);\r
-    m_listCtrl->InsertColumn(1, "Address", wxLIST_FORMAT_LEFT, 350);\r
-    m_listCtrl->SetFocus();\r
-\r
-    // Set Icon\r
-    wxIcon iconAddressBook;\r
-    iconAddressBook.CopyFromBitmap(wxBitmap(addressbook16_xpm));\r
-    SetIcon(iconAddressBook);\r
-\r
-    // Fill listctrl with address book data\r
-    CRITICAL_BLOCK(cs_mapKeys)\r
-    {\r
-        foreach(const PAIRTYPE(string, string)& item, mapAddressBook)\r
-        {\r
-            string strAddress = item.first;\r
-            string strName = item.second;\r
-            uint160 hash160;\r
-            bool fMine = (AddressToHash160(strAddress, hash160) && mapPubKeys.count(hash160));\r
-            if (!fMine)\r
-            {\r
-                int nIndex = InsertLine(m_listCtrl, strName, strAddress);\r
-                if (strAddress == strInitSelected)\r
-                    m_listCtrl->SetItemState(nIndex, wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED, wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED);\r
-            }\r
-        }\r
-    }\r
-}\r
-\r
-wxString CAddressBookDialog::GetAddress()\r
-{\r
-    int nIndex = GetSelection(m_listCtrl);\r
-    if (nIndex == -1)\r
-        return "";\r
-    return GetItemText(m_listCtrl, nIndex, 1);\r
-}\r
-\r
-void CAddressBookDialog::OnListEndLabelEdit(wxListEvent& event)\r
-{\r
-    // Update address book with edited name\r
-    if (event.IsEditCancelled())\r
-        return;\r
-    string strAddress = (string)GetItemText(m_listCtrl, event.GetIndex(), 1);\r
-    SetAddressBookName(strAddress, string(event.GetText()));\r
-    pframeMain->RefreshListCtrl();\r
-}\r
-\r
-void CAddressBookDialog::OnListItemSelected(wxListEvent& event)\r
-{\r
-}\r
-\r
-void CAddressBookDialog::OnListItemActivated(wxListEvent& event)\r
-{\r
-    if (fSending)\r
-    {\r
-        // Doubleclick returns selection\r
-        EndModal(GetAddress() != "" ? 2 : 0);\r
-    }\r
-    else\r
-    {\r
-        // Doubleclick edits item\r
-        wxCommandEvent event2;\r
-        OnButtonEdit(event2);\r
-    }\r
-}\r
-\r
-bool CAddressBookDialog::CheckIfMine(const string& strAddress, const string& strTitle)\r
-{\r
-    uint160 hash160;\r
-    bool fMine = (AddressToHash160(strAddress, hash160) && mapPubKeys.count(hash160));\r
-    if (fMine)\r
-        wxMessageBox("This is one of your own addresses for receiving payments and cannot be entered in the address book.  ", strTitle);\r
-    return fMine;\r
-}\r
-\r
-void CAddressBookDialog::OnButtonEdit(wxCommandEvent& event)\r
-{\r
-    // Ask new name\r
-    int nIndex = GetSelection(m_listCtrl);\r
-    if (nIndex == -1)\r
-        return;\r
-    string strName = (string)m_listCtrl->GetItemText(nIndex);\r
-    string strAddress = (string)GetItemText(m_listCtrl, nIndex, 1);\r
-    string strAddressOrg = strAddress;\r
-    do\r
-    {\r
-        CGetTextFromUserDialog dialog(this, "Edit Address", "Name", strName, "Address", strAddress);\r
-        if (!dialog.ShowModal())\r
-            return;\r
-        strName = dialog.GetValue1();\r
-        strAddress = dialog.GetValue2();\r
-    }\r
-    while (CheckIfMine(strAddress, "Edit Address"));\r
-\r
-    // Change name\r
-    if (strAddress != strAddressOrg)\r
-        CWalletDB().EraseName(strAddressOrg);\r
-    SetAddressBookName(strAddress, strName);\r
-    m_listCtrl->SetItem(nIndex, 1, strAddress);\r
-    m_listCtrl->SetItemText(nIndex, strName);\r
-    pframeMain->RefreshListCtrl();\r
-}\r
-\r
-void CAddressBookDialog::OnButtonNew(wxCommandEvent& event)\r
-{\r
-    // Ask name\r
-    string strName;\r
-    string strAddress;\r
-    do\r
-    {\r
-        CGetTextFromUserDialog dialog(this, "New Address", "Name", strName, "Address", strAddress);\r
-        if (!dialog.ShowModal())\r
-            return;\r
-        strName = dialog.GetValue1();\r
-        strAddress = dialog.GetValue2();\r
-    }\r
-    while (CheckIfMine(strAddress, "New Address"));\r
-\r
-    // Add to list and select it\r
-    SetAddressBookName(strAddress, strName);\r
-    int nIndex = InsertLine(m_listCtrl, strName, strAddress);\r
-    SetSelection(m_listCtrl, nIndex);\r
-    m_listCtrl->SetFocus();\r
-    pframeMain->RefreshListCtrl();\r
-}\r
-\r
-void CAddressBookDialog::OnButtonDelete(wxCommandEvent& event)\r
-{\r
-    for (int nIndex = m_listCtrl->GetItemCount()-1; nIndex >= 0; nIndex--)\r
-    {\r
-        if (m_listCtrl->GetItemState(nIndex, wxLIST_STATE_SELECTED))\r
-        {\r
-            string strAddress = (string)GetItemText(m_listCtrl, nIndex, 1);\r
-            CWalletDB().EraseName(strAddress);\r
-            m_listCtrl->DeleteItem(nIndex);\r
-        }\r
-    }\r
-    pframeMain->RefreshListCtrl();\r
-}\r
-\r
-void CAddressBookDialog::OnButtonCopy(wxCommandEvent& event)\r
-{\r
-    // Copy address box to clipboard\r
-    if (wxTheClipboard->Open())\r
-    {\r
-        wxTheClipboard->SetData(new wxTextDataObject(GetAddress()));\r
-        wxTheClipboard->Close();\r
-    }\r
-}\r
-\r
-void CAddressBookDialog::OnButtonOK(wxCommandEvent& event)\r
-{\r
-    // OK\r
-    EndModal(GetAddress() != "" ? 1 : 0);\r
-}\r
-\r
-void CAddressBookDialog::OnButtonCancel(wxCommandEvent& event)\r
-{\r
-    // Cancel\r
-    EndModal(0);\r
-}\r
-\r
-void CAddressBookDialog::OnClose(wxCloseEvent& event)\r
-{\r
-    // Close\r
-    EndModal(0);\r
-}\r
-\r
-\r
-\r
-\r
-\r
-\r
-//////////////////////////////////////////////////////////////////////////////\r
-//\r
-// CProductsDialog\r
-//\r
-\r
-bool CompareIntStringPairBestFirst(const pair<int, string>& item1, const pair<int, string>& item2)\r
-{\r
-    return (item1.first > item2.first);\r
-}\r
-\r
-CProductsDialog::CProductsDialog(wxWindow* parent) : CProductsDialogBase(parent)\r
-{\r
-    // Init column headers\r
-    m_listCtrl->InsertColumn(0, "Title",  wxLIST_FORMAT_LEFT, 200);\r
-    m_listCtrl->InsertColumn(1, "Price",  wxLIST_FORMAT_LEFT, 80);\r
-    m_listCtrl->InsertColumn(2, "Seller", wxLIST_FORMAT_LEFT, 80);\r
-    m_listCtrl->InsertColumn(3, "Stars",  wxLIST_FORMAT_LEFT, 50);\r
-    m_listCtrl->InsertColumn(4, "Power",  wxLIST_FORMAT_LEFT, 50);\r
-\r
-    // Tally top categories\r
-    map<string, int> mapTopCategories;\r
-    CRITICAL_BLOCK(cs_mapProducts)\r
-        for (map<uint256, CProduct>::iterator mi = mapProducts.begin(); mi != mapProducts.end(); ++mi)\r
-            mapTopCategories[(*mi).second.mapValue["category"]]++;\r
-\r
-    // Sort top categories\r
-    vector<pair<int, string> > vTopCategories;\r
-    for (map<string, int>::iterator mi = mapTopCategories.begin(); mi != mapTopCategories.end(); ++mi)\r
-        vTopCategories.push_back(make_pair((*mi).second, (*mi).first));\r
-    sort(vTopCategories.begin(), vTopCategories.end(), CompareIntStringPairBestFirst);\r
-\r
-    // Fill categories combo box\r
-    int nLimit = 250;\r
-    for (vector<pair<int, string> >::iterator it = vTopCategories.begin(); it != vTopCategories.end() && nLimit-- > 0; ++it)\r
-        m_comboBoxCategory->Append((*it).second);\r
-\r
-    // Fill window with initial search\r
-    //wxCommandEvent event;\r
-    //OnButtonSearch(event);\r
-}\r
-\r
-void CProductsDialog::OnCombobox(wxCommandEvent& event)\r
-{\r
-    OnButtonSearch(event);\r
-}\r
-\r
-bool CompareProductsBestFirst(const CProduct* p1, const CProduct* p2)\r
-{\r
-    return (p1->nAtoms > p2->nAtoms);\r
-}\r
-\r
-void CProductsDialog::OnButtonSearch(wxCommandEvent& event)\r
-{\r
-    string strCategory = (string)m_comboBoxCategory->GetValue();\r
-    string strSearch = (string)m_textCtrlSearch->GetValue();\r
-\r
-    // Search products\r
-    vector<CProduct*> vProductsFound;\r
-    CRITICAL_BLOCK(cs_mapProducts)\r
-    {\r
-        for (map<uint256, CProduct>::iterator mi = mapProducts.begin(); mi != mapProducts.end(); ++mi)\r
-        {\r
-            CProduct& product = (*mi).second;\r
-            if (product.mapValue["category"].find(strCategory) != -1)\r
-            {\r
-                if (product.mapValue["title"].find(strSearch) != -1 ||\r
-                    product.mapValue["description"].find(strSearch) != -1 ||\r
-                    product.mapValue["seller"].find(strSearch) != -1)\r
-                {\r
-                    vProductsFound.push_back(&product);\r
-                }\r
-            }\r
-        }\r
-    }\r
-\r
-    // Sort\r
-    sort(vProductsFound.begin(), vProductsFound.end(), CompareProductsBestFirst);\r
-\r
-    // Display\r
-    foreach(CProduct* pproduct, vProductsFound)\r
-    {\r
-        InsertLine(m_listCtrl,\r
-                   pproduct->mapValue["title"],\r
-                   pproduct->mapValue["price"],\r
-                   pproduct->mapValue["seller"],\r
-                   pproduct->mapValue["stars"],\r
-                   itostr(pproduct->nAtoms));\r
-    }\r
-}\r
-\r
-void CProductsDialog::OnListItemActivated(wxListEvent& event)\r
-{\r
-    // Doubleclick opens product\r
-    CViewProductDialog* pdialog = new CViewProductDialog(this, m_vProduct[event.GetIndex()]);\r
-    pdialog->Show();\r
-}\r
-\r
-\r
-\r
-\r
-\r
-\r
-\r
-//////////////////////////////////////////////////////////////////////////////\r
-//\r
-// CEditProductDialog\r
-//\r
-\r
-CEditProductDialog::CEditProductDialog(wxWindow* parent) : CEditProductDialogBase(parent)\r
-{\r
-    m_textCtrlLabel[0 ] = m_textCtrlLabel0;\r
-    m_textCtrlLabel[1 ] = m_textCtrlLabel1;\r
-    m_textCtrlLabel[2 ] = m_textCtrlLabel2;\r
-    m_textCtrlLabel[3 ] = m_textCtrlLabel3;\r
-    m_textCtrlLabel[4 ] = m_textCtrlLabel4;\r
-    m_textCtrlLabel[5 ] = m_textCtrlLabel5;\r
-    m_textCtrlLabel[6 ] = m_textCtrlLabel6;\r
-    m_textCtrlLabel[7 ] = m_textCtrlLabel7;\r
-    m_textCtrlLabel[8 ] = m_textCtrlLabel8;\r
-    m_textCtrlLabel[9 ] = m_textCtrlLabel9;\r
-    m_textCtrlLabel[10] = m_textCtrlLabel10;\r
-    m_textCtrlLabel[11] = m_textCtrlLabel11;\r
-    m_textCtrlLabel[12] = m_textCtrlLabel12;\r
-    m_textCtrlLabel[13] = m_textCtrlLabel13;\r
-    m_textCtrlLabel[14] = m_textCtrlLabel14;\r
-    m_textCtrlLabel[15] = m_textCtrlLabel15;\r
-    m_textCtrlLabel[16] = m_textCtrlLabel16;\r
-    m_textCtrlLabel[17] = m_textCtrlLabel17;\r
-    m_textCtrlLabel[18] = m_textCtrlLabel18;\r
-    m_textCtrlLabel[19] = m_textCtrlLabel19;\r
-\r
-    m_textCtrlField[0 ] = m_textCtrlField0;\r
-    m_textCtrlField[1 ] = m_textCtrlField1;\r
-    m_textCtrlField[2 ] = m_textCtrlField2;\r
-    m_textCtrlField[3 ] = m_textCtrlField3;\r
-    m_textCtrlField[4 ] = m_textCtrlField4;\r
-    m_textCtrlField[5 ] = m_textCtrlField5;\r
-    m_textCtrlField[6 ] = m_textCtrlField6;\r
-    m_textCtrlField[7 ] = m_textCtrlField7;\r
-    m_textCtrlField[8 ] = m_textCtrlField8;\r
-    m_textCtrlField[9 ] = m_textCtrlField9;\r
-    m_textCtrlField[10] = m_textCtrlField10;\r
-    m_textCtrlField[11] = m_textCtrlField11;\r
-    m_textCtrlField[12] = m_textCtrlField12;\r
-    m_textCtrlField[13] = m_textCtrlField13;\r
-    m_textCtrlField[14] = m_textCtrlField14;\r
-    m_textCtrlField[15] = m_textCtrlField15;\r
-    m_textCtrlField[16] = m_textCtrlField16;\r
-    m_textCtrlField[17] = m_textCtrlField17;\r
-    m_textCtrlField[18] = m_textCtrlField18;\r
-    m_textCtrlField[19] = m_textCtrlField19;\r
-\r
-    m_buttonDel[0 ] = m_buttonDel0;\r
-    m_buttonDel[1 ] = m_buttonDel1;\r
-    m_buttonDel[2 ] = m_buttonDel2;\r
-    m_buttonDel[3 ] = m_buttonDel3;\r
-    m_buttonDel[4 ] = m_buttonDel4;\r
-    m_buttonDel[5 ] = m_buttonDel5;\r
-    m_buttonDel[6 ] = m_buttonDel6;\r
-    m_buttonDel[7 ] = m_buttonDel7;\r
-    m_buttonDel[8 ] = m_buttonDel8;\r
-    m_buttonDel[9 ] = m_buttonDel9;\r
-    m_buttonDel[10] = m_buttonDel10;\r
-    m_buttonDel[11] = m_buttonDel11;\r
-    m_buttonDel[12] = m_buttonDel12;\r
-    m_buttonDel[13] = m_buttonDel13;\r
-    m_buttonDel[14] = m_buttonDel14;\r
-    m_buttonDel[15] = m_buttonDel15;\r
-    m_buttonDel[16] = m_buttonDel16;\r
-    m_buttonDel[17] = m_buttonDel17;\r
-    m_buttonDel[18] = m_buttonDel18;\r
-    m_buttonDel[19] = m_buttonDel19;\r
-\r
-    for (int i = 1; i < FIELDS_MAX; i++)\r
-        ShowLine(i, false);\r
-\r
-    LayoutAll();\r
-}\r
-\r
-void CEditProductDialog::LayoutAll()\r
-{\r
-    m_scrolledWindow->Layout();\r
-    m_scrolledWindow->GetSizer()->Fit(m_scrolledWindow);\r
-    this->Layout();\r
-}\r
-\r
-void CEditProductDialog::ShowLine(int i, bool fShow)\r
-{\r
-    m_textCtrlLabel[i]->Show(fShow);\r
-    m_textCtrlField[i]->Show(fShow);\r
-    m_buttonDel[i]->Show(fShow);\r
-}\r
-\r
-void CEditProductDialog::OnButtonDel0(wxCommandEvent& event)  { OnButtonDel(event, 0); }\r
-void CEditProductDialog::OnButtonDel1(wxCommandEvent& event)  { OnButtonDel(event, 1); }\r
-void CEditProductDialog::OnButtonDel2(wxCommandEvent& event)  { OnButtonDel(event, 2); }\r
-void CEditProductDialog::OnButtonDel3(wxCommandEvent& event)  { OnButtonDel(event, 3); }\r
-void CEditProductDialog::OnButtonDel4(wxCommandEvent& event)  { OnButtonDel(event, 4); }\r
-void CEditProductDialog::OnButtonDel5(wxCommandEvent& event)  { OnButtonDel(event, 5); }\r
-void CEditProductDialog::OnButtonDel6(wxCommandEvent& event)  { OnButtonDel(event, 6); }\r
-void CEditProductDialog::OnButtonDel7(wxCommandEvent& event)  { OnButtonDel(event, 7); }\r
-void CEditProductDialog::OnButtonDel8(wxCommandEvent& event)  { OnButtonDel(event, 8); }\r
-void CEditProductDialog::OnButtonDel9(wxCommandEvent& event)  { OnButtonDel(event, 9); }\r
-void CEditProductDialog::OnButtonDel10(wxCommandEvent& event) { OnButtonDel(event, 10); }\r
-void CEditProductDialog::OnButtonDel11(wxCommandEvent& event) { OnButtonDel(event, 11); }\r
-void CEditProductDialog::OnButtonDel12(wxCommandEvent& event) { OnButtonDel(event, 12); }\r
-void CEditProductDialog::OnButtonDel13(wxCommandEvent& event) { OnButtonDel(event, 13); }\r
-void CEditProductDialog::OnButtonDel14(wxCommandEvent& event) { OnButtonDel(event, 14); }\r
-void CEditProductDialog::OnButtonDel15(wxCommandEvent& event) { OnButtonDel(event, 15); }\r
-void CEditProductDialog::OnButtonDel16(wxCommandEvent& event) { OnButtonDel(event, 16); }\r
-void CEditProductDialog::OnButtonDel17(wxCommandEvent& event) { OnButtonDel(event, 17); }\r
-void CEditProductDialog::OnButtonDel18(wxCommandEvent& event) { OnButtonDel(event, 18); }\r
-void CEditProductDialog::OnButtonDel19(wxCommandEvent& event) { OnButtonDel(event, 19); }\r
-\r
-void CEditProductDialog::OnButtonDel(wxCommandEvent& event, int n)\r
-{\r
-    Freeze();\r
-    int x, y;\r
-    m_scrolledWindow->GetViewStart(&x, &y);\r
-    int i;\r
-    for (i = n; i < FIELDS_MAX-1; i++)\r
-    {\r
-        m_textCtrlLabel[i]->SetValue(m_textCtrlLabel[i+1]->GetValue());\r
-        m_textCtrlField[i]->SetValue(m_textCtrlField[i+1]->GetValue());\r
-        if (!m_buttonDel[i+1]->IsShown())\r
-            break;\r
-    }\r
-    m_textCtrlLabel[i]->SetValue("");\r
-    m_textCtrlField[i]->SetValue("");\r
-    ShowLine(i, false);\r
-    m_buttonAddField->Enable(true);\r
-    LayoutAll();\r
-    m_scrolledWindow->Scroll(0, y);\r
-    Thaw();\r
-}\r
-\r
-void CEditProductDialog::OnButtonAddField(wxCommandEvent& event)\r
-{\r
-    for (int i = 0; i < FIELDS_MAX; i++)\r
-    {\r
-        if (!m_buttonDel[i]->IsShown())\r
-        {\r
-            Freeze();\r
-            ShowLine(i, true);\r
-            if (i == FIELDS_MAX-1)\r
-                m_buttonAddField->Enable(false);\r
-            LayoutAll();\r
-            m_scrolledWindow->Scroll(0, 99999);\r
-            Thaw();\r
-            break;\r
-        }\r
-    }\r
-}\r
-\r
-void CEditProductDialog::OnButtonSend(wxCommandEvent& event)\r
-{\r
-    CProduct product;\r
-    GetProduct(product);\r
-\r
-    // Sign the detailed product\r
-    product.vchPubKeyFrom = keyUser.GetPubKey();\r
-    if (!keyUser.Sign(product.GetSigHash(), product.vchSig))\r
-    {\r
-        wxMessageBox("Error digitally signing the product  ");\r
-        return;\r
-    }\r
-\r
-    // Save detailed product\r
-    AddToMyProducts(product);\r
-\r
-    // Strip down to summary product\r
-    product.mapDetails.clear();\r
-    product.vOrderForm.clear();\r
-\r
-    // Sign the summary product\r
-    if (!keyUser.Sign(product.GetSigHash(), product.vchSig))\r
-    {\r
-        wxMessageBox("Error digitally signing the product  ");\r
-        return;\r
-    }\r
-\r
-    // Verify\r
-    if (!product.CheckProduct())\r
-    {\r
-        wxMessageBox("Errors found in product  ");\r
-        return;\r
-    }\r
-\r
-    // Broadcast\r
-    AdvertStartPublish(pnodeLocalHost, MSG_PRODUCT, 0, product);\r
-\r
-    Destroy();\r
-}\r
-\r
-void CEditProductDialog::OnButtonPreview(wxCommandEvent& event)\r
-{\r
-    CProduct product;\r
-    GetProduct(product);\r
-    CViewProductDialog* pdialog = new CViewProductDialog(this, product);\r
-    pdialog->Show();\r
-}\r
-\r
-void CEditProductDialog::OnButtonCancel(wxCommandEvent& event)\r
-{\r
-    Destroy();\r
-}\r
-\r
-void CEditProductDialog::SetProduct(const CProduct& productIn)\r
-{\r
-    CProduct product = productIn;\r
-\r
-    m_comboBoxCategory->SetValue(product.mapValue["category"]);\r
-    m_textCtrlTitle->SetValue(product.mapValue["title"]);\r
-    m_textCtrlPrice->SetValue(product.mapValue["price"]);\r
-    m_textCtrlDescription->SetValue(product.mapValue["description"]);\r
-    m_textCtrlInstructions->SetValue(product.mapValue["instructions"]);\r
-\r
-    for (int i = 0; i < FIELDS_MAX; i++)\r
-    {\r
-        bool fUsed = i < product.vOrderForm.size();\r
-        m_buttonDel[i]->Show(fUsed);\r
-        m_textCtrlLabel[i]->Show(fUsed);\r
-        m_textCtrlField[i]->Show(fUsed);\r
-        if (!fUsed)\r
-            continue;\r
-\r
-        m_textCtrlLabel[i]->SetValue(product.vOrderForm[i].first);\r
-        string strControl = product.vOrderForm[i].second;\r
-        if (strControl.substr(0, 5) == "text=")\r
-            m_textCtrlField[i]->SetValue("");\r
-        else if (strControl.substr(0, 7) == "choice=")\r
-            m_textCtrlField[i]->SetValue(strControl.substr(7));\r
-        else\r
-            m_textCtrlField[i]->SetValue(strControl);\r
-    }\r
-}\r
-\r
-void CEditProductDialog::GetProduct(CProduct& product)\r
-{\r
-    // map<string, string> mapValue;\r
-    // vector<pair<string, string> > vOrderForm;\r
-\r
-    product.mapValue["category"]     = m_comboBoxCategory->GetValue().Trim();\r
-    product.mapValue["title"]        = m_textCtrlTitle->GetValue().Trim();\r
-    product.mapValue["price"]        = m_textCtrlPrice->GetValue().Trim();\r
-    product.mapValue["description"]  = m_textCtrlDescription->GetValue().Trim();\r
-    product.mapValue["instructions"] = m_textCtrlInstructions->GetValue().Trim();\r
-\r
-    for (int i = 0; i < FIELDS_MAX; i++)\r
-    {\r
-        if (m_buttonDel[i]->IsShown())\r
-        {\r
-            string strLabel = (string)m_textCtrlLabel[i]->GetValue().Trim();\r
-            string strControl = (string)m_textCtrlField[i]->GetValue();\r
-            if (strControl.empty())\r
-                strControl = "text=";\r
-            else\r
-                strControl = "choice=" + strControl;\r
-            product.vOrderForm.push_back(make_pair(strLabel, strControl));\r
-        }\r
-    }\r
-}\r
-\r
-\r
-\r
-\r
-\r
-\r
-\r
-//////////////////////////////////////////////////////////////////////////////\r
-//\r
-// CViewProductDialog\r
-//\r
-\r
-CViewProductDialog::CViewProductDialog(wxWindow* parent, const CProduct& productIn) : CViewProductDialogBase(parent)\r
-{\r
-    Connect(wxEVT_REPLY1, wxCommandEventHandler(CViewProductDialog::OnReply1), NULL, this);\r
-    AddCallbackAvailable(GetEventHandler());\r
-\r
-    // Fill display with product summary while waiting for details\r
-    product = productIn;\r
-    UpdateProductDisplay(false);\r
-\r
-    m_buttonBack->Enable(false);\r
-    m_buttonNext->Enable(!product.vOrderForm.empty());\r
-    m_htmlWinReviews->Show(true);\r
-    m_scrolledWindow->Show(false);\r
-    this->Layout();\r
-\r
-    // Request details from seller\r
-    CreateThread(ThreadRequestProductDetails, new pair<CProduct, wxEvtHandler*>(product, GetEventHandler()));\r
-}\r
-\r
-CViewProductDialog::~CViewProductDialog()\r
-{\r
-    RemoveCallbackAvailable(GetEventHandler());\r
-}\r
-\r
-void ThreadRequestProductDetails(void* parg)\r
-{\r
-    // Extract parameters\r
-    pair<CProduct, wxEvtHandler*>* pitem = (pair<CProduct, wxEvtHandler*>*)parg;\r
-    CProduct product = pitem->first;\r
-    wxEvtHandler* pevthandler = pitem->second;\r
-    delete pitem;\r
-\r
-    // Connect to seller\r
-    CNode* pnode = ConnectNode(product.addr, 5 * 60);\r
-    if (!pnode)\r
-    {\r
-        CDataStream ssEmpty;\r
-        AddPendingReplyEvent1(pevthandler, ssEmpty);\r
-        return;\r
-    }\r
-\r
-    // Request detailed product, with response going to OnReply1 via dialog's event handler\r
-    pnode->PushRequest("getdetails", product.GetHash(), AddPendingReplyEvent1, (void*)pevthandler);\r
-}\r
-\r
-void CViewProductDialog::OnReply1(wxCommandEvent& event)\r
-{\r
-    CDataStream ss = GetStreamFromEvent(event);\r
-    if (ss.empty())\r
-    {\r
-        product.mapValue["description"] = "-- CAN'T CONNECT TO SELLER --\n";\r
-        UpdateProductDisplay(true);\r
-        return;\r
-    }\r
-\r
-    int nRet;\r
-    CProduct product2;\r
-    try\r
-    {\r
-        ss >> nRet;\r
-        if (nRet > 0)\r
-            throw false;\r
-        ss >> product2;\r
-        if (product2.GetHash() != product.GetHash())\r
-            throw false;\r
-        if (!product2.CheckSignature())\r
-            throw false;\r
-    }\r
-    catch (...)\r
-    {\r
-        product.mapValue["description"] = "-- INVALID RESPONSE --\n";\r
-        UpdateProductDisplay(true);\r
-        return;\r
-    }\r
-\r
-    product = product2;\r
-    UpdateProductDisplay(true);\r
-}\r
-\r
-bool CompareReviewsBestFirst(const CReview* p1, const CReview* p2)\r
-{\r
-    return (p1->nAtoms > p2->nAtoms);\r
-}\r
-\r
-void CViewProductDialog::UpdateProductDisplay(bool fDetails)\r
-{\r
-    // Product and reviews\r
-    string strHTML;\r
-    strHTML.reserve(4000);\r
-    strHTML += "<html>\n"\r
-               "<head>\n"\r
-               "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n"\r
-               "</head>\n"\r
-               "<body>\n";\r
-    strHTML += "<b>Category:</b> " + HtmlEscape(product.mapValue["category"]) + "<br>\n";\r
-    strHTML += "<b>Title:</b> "    + HtmlEscape(product.mapValue["title"])    + "<br>\n";\r
-    strHTML += "<b>Price:</b> "    + HtmlEscape(product.mapValue["price"])    + "<br>\n";\r
-\r
-    if (!fDetails)\r
-        strHTML += "<b>Loading details...</b><br>\n<br>\n";\r
-    else\r
-        strHTML += HtmlEscape(product.mapValue["description"], true) + "<br>\n<br>\n";\r
-\r
-    strHTML += "<b>Reviews:</b><br>\n<br>\n";\r
-\r
-    if (!product.vchPubKeyFrom.empty())\r
-    {\r
-        CReviewDB reviewdb("r");\r
-\r
-        // Get reviews\r
-        vector<CReview> vReviews;\r
-        reviewdb.ReadReviews(product.GetUserHash(), vReviews);\r
-\r
-        // Get reviewer's number of atoms\r
-        vector<CReview*> vSortedReviews;\r
-        vSortedReviews.reserve(vReviews.size());\r
-        for (vector<CReview>::reverse_iterator it = vReviews.rbegin(); it != vReviews.rend(); ++it)\r
-        {\r
-            CReview& review = *it;\r
-            CUser user;\r
-            reviewdb.ReadUser(review.GetUserHash(), user);\r
-            review.nAtoms = user.GetAtomCount();\r
-            vSortedReviews.push_back(&review);\r
-        }\r
-\r
-        reviewdb.Close();\r
-\r
-        // Sort\r
-        stable_sort(vSortedReviews.begin(), vSortedReviews.end(), CompareReviewsBestFirst);\r
-\r
-        // Format reviews\r
-        foreach(CReview* preview, vSortedReviews)\r
-        {\r
-            CReview& review = *preview;\r
-            int nStars = atoi(review.mapValue["stars"].c_str());\r
-            if (nStars < 1 || nStars > 5)\r
-                continue;\r
-\r
-            strHTML += "<b>" + itostr(nStars) + (nStars == 1 ? " star" : " stars") + "</b>";\r
-            strHTML += " &nbsp;&nbsp;&nbsp; ";\r
-            strHTML += DateStr(atoi64(review.mapValue["date"])) + "<br>\n";\r
-            strHTML += HtmlEscape(review.mapValue["review"], true);\r
-            strHTML += "<br>\n<br>\n";\r
-        }\r
-    }\r
-\r
-    strHTML += "</body>\n</html>\n";\r
-\r
-    // Shrink capacity to fit\r
-    string(strHTML.begin(), strHTML.end()).swap(strHTML);\r
-\r
-    m_htmlWinReviews->SetPage(strHTML);\r
-\r
-    ///// need to find some other indicator to use so can allow empty order form\r
-    if (product.vOrderForm.empty())\r
-        return;\r
-\r
-    // Order form\r
-    m_staticTextInstructions->SetLabel(product.mapValue["instructions"]);\r
-    for (int i = 0; i < FIELDS_MAX; i++)\r
-    {\r
-        m_staticTextLabel[i] = NULL;\r
-        m_textCtrlField[i] = NULL;\r
-        m_choiceField[i] = NULL;\r
-    }\r
-\r
-    // Construct flexgridsizer\r
-    wxBoxSizer* bSizer21 = (wxBoxSizer*)m_scrolledWindow->GetSizer();\r
-    wxFlexGridSizer* fgSizer;\r
-    fgSizer = new wxFlexGridSizer(0, 2, 0, 0);\r
-    fgSizer->AddGrowableCol(1);\r
-    fgSizer->SetFlexibleDirection(wxBOTH);\r
-    fgSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);\r
-\r
-    // Construct order form fields\r
-    wxWindow* windowLast = NULL;\r
-    for (int i = 0; i < product.vOrderForm.size(); i++)\r
-    {\r
-        string strLabel = product.vOrderForm[i].first;\r
-        string strControl = product.vOrderForm[i].second;\r
-\r
-        if (strLabel.size() < 20)\r
-            strLabel.insert(strLabel.begin(), 20 - strLabel.size(), ' ');\r
-\r
-        m_staticTextLabel[i] = new wxStaticText(m_scrolledWindow, wxID_ANY, strLabel, wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT);\r
-        m_staticTextLabel[i]->Wrap(-1);\r
-        fgSizer->Add(m_staticTextLabel[i], 0, wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxALL, 5);\r
-\r
-        if (strControl.substr(0, 5) == "text=")\r
-        {\r
-            m_textCtrlField[i] = new wxTextCtrl(m_scrolledWindow, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0);\r
-            fgSizer->Add(m_textCtrlField[i], 1, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5);\r
-            windowLast = m_textCtrlField[i];\r
-        }\r
-        else if (strControl.substr(0, 7) == "choice=")\r
-        {\r
-            vector<string> vChoices;\r
-            ParseString(strControl.substr(7), ',', vChoices);\r
-\r
-            wxArrayString arraystring;\r
-            foreach(const string& str, vChoices)\r
-                arraystring.Add(str);\r
-\r
-            m_choiceField[i] = new wxChoice(m_scrolledWindow, wxID_ANY, wxDefaultPosition, wxDefaultSize, arraystring, 0);\r
-            fgSizer->Add(m_choiceField[i], 0, wxALL|wxALIGN_CENTER_VERTICAL, 5);\r
-            windowLast = m_choiceField[i];\r
-        }\r
-        else\r
-        {\r
-            m_textCtrlField[i] = new wxTextCtrl(m_scrolledWindow, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0);\r
-            fgSizer->Add(m_textCtrlField[i], 1, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5);\r
-            m_staticTextLabel[i]->Show(false);\r
-            m_textCtrlField[i]->Show(false);\r
-        }\r
-    }\r
-\r
-    // Insert after instructions and before submit/cancel buttons\r
-    bSizer21->Insert(2, fgSizer, 0, wxEXPAND|wxRIGHT|wxLEFT, 5);\r
-    m_scrolledWindow->Layout();\r
-    bSizer21->Fit(m_scrolledWindow);\r
-    this->Layout();\r
-\r
-    // Fixup the tab order\r
-    m_buttonSubmitForm->MoveAfterInTabOrder(windowLast);\r
-    m_buttonCancelForm->MoveAfterInTabOrder(m_buttonSubmitForm);\r
-    //m_buttonBack->MoveAfterInTabOrder(m_buttonCancelForm);\r
-    //m_buttonNext->MoveAfterInTabOrder(m_buttonBack);\r
-    //m_buttonCancel->MoveAfterInTabOrder(m_buttonNext);\r
-    this->Layout();\r
-}\r
-\r
-void CViewProductDialog::GetOrder(CWalletTx& wtx)\r
-{\r
-    wtx.SetNull();\r
-    for (int i = 0; i < product.vOrderForm.size(); i++)\r
-    {\r
-        string strValue;\r
-        if (m_textCtrlField[i])\r
-            strValue = m_textCtrlField[i]->GetValue().Trim();\r
-        else\r
-            strValue = m_choiceField[i]->GetStringSelection();\r
-        wtx.vOrderForm.push_back(make_pair(m_staticTextLabel[i]->GetLabel(), strValue));\r
-    }\r
-}\r
-\r
-void CViewProductDialog::OnButtonSubmitForm(wxCommandEvent& event)\r
-{\r
-    m_buttonSubmitForm->Enable(false);\r
-    m_buttonCancelForm->Enable(false);\r
-\r
-    CWalletTx wtx;\r
-    GetOrder(wtx);\r
-\r
-    CSendingDialog* pdialog = new CSendingDialog(this, product.addr, atoi64(product.mapValue["price"]), wtx);\r
-    if (!pdialog->ShowModal())\r
-    {\r
-        m_buttonSubmitForm->Enable(true);\r
-        m_buttonCancelForm->Enable(true);\r
-        return;\r
-    }\r
-}\r
-\r
-void CViewProductDialog::OnButtonCancelForm(wxCommandEvent& event)\r
-{\r
-    Destroy();\r
-}\r
-\r
-void CViewProductDialog::OnButtonBack(wxCommandEvent& event)\r
-{\r
-    Freeze();\r
-    m_htmlWinReviews->Show(true);\r
-    m_scrolledWindow->Show(false);\r
-    m_buttonBack->Enable(false);\r
-    m_buttonNext->Enable(!product.vOrderForm.empty());\r
-    this->Layout();\r
-    Thaw();\r
-}\r
-\r
-void CViewProductDialog::OnButtonNext(wxCommandEvent& event)\r
-{\r
-    if (!product.vOrderForm.empty())\r
-    {\r
-        Freeze();\r
-        m_htmlWinReviews->Show(false);\r
-        m_scrolledWindow->Show(true);\r
-        m_buttonBack->Enable(true);\r
-        m_buttonNext->Enable(false);\r
-        this->Layout();\r
-        Thaw();\r
-    }\r
-}\r
-\r
-void CViewProductDialog::OnButtonCancel(wxCommandEvent& event)\r
-{\r
-    Destroy();\r
-}\r
-\r
-\r
-\r
-\r
-\r
-\r
-\r
-//////////////////////////////////////////////////////////////////////////////\r
-//\r
-// CViewOrderDialog\r
-//\r
-\r
-CViewOrderDialog::CViewOrderDialog(wxWindow* parent, CWalletTx order, bool fReceived) : CViewOrderDialogBase(parent)\r
-{\r
-    int64 nPrice = (fReceived ? order.GetCredit() : order.GetDebit());\r
-\r
-    string strHTML;\r
-    strHTML.reserve(4000);\r
-    strHTML += "<html>\n"\r
-               "<head>\n"\r
-               "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n"\r
-               "</head>\n"\r
-               "<body>\n";\r
-    strHTML += "<b>Time:</b> "   + HtmlEscape(DateTimeStr(order.nTimeReceived)) + "<br>\n";\r
-    strHTML += "<b>Price:</b> "  + HtmlEscape(FormatMoney(nPrice)) + "<br>\n";\r
-    strHTML += "<b>Status:</b> " + HtmlEscape(FormatTxStatus(order)) + "<br>\n";\r
-\r
-    strHTML += "<table>\n";\r
-    for (int i = 0; i < order.vOrderForm.size(); i++)\r
-    {\r
-        strHTML += " <tr><td><b>" + HtmlEscape(order.vOrderForm[i].first) + ":</b></td>";\r
-        strHTML += "<td>" + HtmlEscape(order.vOrderForm[i].second) + "</td></tr>\n";\r
-    }\r
-    strHTML += "</table>\n";\r
-\r
-    strHTML += "</body>\n</html>\n";\r
-\r
-    // Shrink capacity to fit\r
-    // (strings are ref counted, so it may live on in SetPage)\r
-    string(strHTML.begin(), strHTML.end()).swap(strHTML);\r
-\r
-    m_htmlWin->SetPage(strHTML);\r
-}\r
-\r
-void CViewOrderDialog::OnButtonOK(wxCommandEvent& event)\r
-{\r
-    Destroy();\r
-}\r
-\r
-\r
-\r
-\r
-\r
-\r
-\r
-//////////////////////////////////////////////////////////////////////////////\r
-//\r
-// CEditReviewDialog\r
-//\r
-\r
-CEditReviewDialog::CEditReviewDialog(wxWindow* parent) : CEditReviewDialogBase(parent)\r
-{\r
-}\r
-\r
-void CEditReviewDialog::OnButtonSubmit(wxCommandEvent& event)\r
-{\r
-    if (m_choiceStars->GetSelection() == -1)\r
-    {\r
-        wxMessageBox("Please select a rating  ");\r
-        return;\r
-    }\r
-\r
-    CReview review;\r
-    GetReview(review);\r
-\r
-    // Sign the review\r
-    review.vchPubKeyFrom = keyUser.GetPubKey();\r
-    if (!keyUser.Sign(review.GetSigHash(), review.vchSig))\r
-    {\r
-        wxMessageBox("Unable to digitally sign the review  ");\r
-        return;\r
-    }\r
-\r
-    // Broadcast\r
-    if (!review.AcceptReview())\r
-    {\r
-        wxMessageBox("Save failed  ");\r
-        return;\r
-    }\r
-    RelayMessage(CInv(MSG_REVIEW, review.GetHash()), review);\r
-\r
-    Destroy();\r
-}\r
-\r
-void CEditReviewDialog::OnButtonCancel(wxCommandEvent& event)\r
-{\r
-    Destroy();\r
-}\r
-\r
-void CEditReviewDialog::GetReview(CReview& review)\r
-{\r
-    review.mapValue["time"]   = i64tostr(GetAdjustedTime());\r
-    review.mapValue["stars"]  = itostr(m_choiceStars->GetSelection()+1);\r
-    review.mapValue["review"] = m_textCtrlReview->GetValue();\r
-}\r
-\r
-\r
-\r
-\r
-\r
-\r
-\r
-//////////////////////////////////////////////////////////////////////////////\r
-//\r
-// CMyTaskBarIcon\r
-//\r
-\r
-enum\r
-{\r
-    ID_TASKBAR_RESTORE = 10001,\r
-    ID_TASKBAR_OPTIONS,\r
-    ID_TASKBAR_GENERATE,\r
-    ID_TASKBAR_EXIT,\r
-};\r
-\r
-BEGIN_EVENT_TABLE(CMyTaskBarIcon, wxTaskBarIcon)\r
-    EVT_TASKBAR_LEFT_DCLICK(CMyTaskBarIcon::OnLeftButtonDClick)\r
-    EVT_MENU(ID_TASKBAR_RESTORE, CMyTaskBarIcon::OnMenuRestore)\r
-    EVT_MENU(ID_TASKBAR_OPTIONS, CMyTaskBarIcon::OnMenuOptions)\r
-    EVT_MENU(ID_TASKBAR_GENERATE, CMyTaskBarIcon::OnMenuGenerate)\r
-    EVT_UPDATE_UI(ID_TASKBAR_GENERATE, CMyTaskBarIcon::OnUpdateUIGenerate)\r
-    EVT_MENU(ID_TASKBAR_EXIT, CMyTaskBarIcon::OnMenuExit)\r
-END_EVENT_TABLE()\r
-\r
-void CMyTaskBarIcon::Show(bool fShow)\r
-{\r
-    static char pszPrevTip[200];\r
-    if (fShow)\r
-    {\r
-        string strTooltip = "Bitcoin";\r
-        if (fGenerateBitcoins)\r
-            strTooltip = "Bitcoin - Generating";\r
-        if (fGenerateBitcoins && vNodes.empty())\r
-            strTooltip = "Bitcoin - (not connected)";\r
-\r
-        // Optimization, only update when changed, using char array to be reentrant\r
-        if (strncmp(pszPrevTip, strTooltip.c_str(), sizeof(pszPrevTip)-1) != 0)\r
-        {\r
-            strlcpy(pszPrevTip, strTooltip.c_str(), sizeof(pszPrevTip));\r
-#ifdef __WXMSW__\r
-            SetIcon(wxICON(bitcoin), strTooltip);\r
-#else\r
-            SetIcon(bitcoin20_xpm, strTooltip);\r
-#endif\r
-        }\r
-    }\r
-    else\r
-    {\r
-        strlcpy(pszPrevTip, "", sizeof(pszPrevTip));\r
-        RemoveIcon();\r
-    }\r
-}\r
-\r
-void CMyTaskBarIcon::Hide()\r
-{\r
-    Show(false);\r
-}\r
-\r
-void CMyTaskBarIcon::OnLeftButtonDClick(wxTaskBarIconEvent& event)\r
-{\r
-    Restore();\r
-}\r
-\r
-void CMyTaskBarIcon::OnMenuRestore(wxCommandEvent& event)\r
-{\r
-    Restore();\r
-}\r
-\r
-void CMyTaskBarIcon::OnMenuOptions(wxCommandEvent& event)\r
-{\r
-    // Since it's modal, get the main window to do it\r
-    wxCommandEvent event2(wxEVT_COMMAND_MENU_SELECTED, wxID_MENUOPTIONSOPTIONS);\r
-    pframeMain->GetEventHandler()->AddPendingEvent(event2);\r
-}\r
-\r
-void CMyTaskBarIcon::Restore()\r
-{\r
-    pframeMain->Show();\r
-    wxIconizeEvent event(0, false);\r
-    pframeMain->GetEventHandler()->AddPendingEvent(event);\r
-    pframeMain->Iconize(false);\r
-    pframeMain->Raise();\r
-}\r
-\r
-void CMyTaskBarIcon::OnMenuGenerate(wxCommandEvent& event)\r
-{\r
-    GenerateBitcoins(event.IsChecked());\r
-}\r
-\r
-void CMyTaskBarIcon::OnUpdateUIGenerate(wxUpdateUIEvent& event)\r
-{\r
-    event.Check(fGenerateBitcoins);\r
-}\r
-\r
-void CMyTaskBarIcon::OnMenuExit(wxCommandEvent& event)\r
-{\r
-    pframeMain->Close(true);\r
-}\r
-\r
-void CMyTaskBarIcon::UpdateTooltip()\r
-{\r
-    if (IsIconInstalled())\r
-        Show(true);\r
-}\r
-\r
-wxMenu* CMyTaskBarIcon::CreatePopupMenu()\r
-{\r
-    wxMenu* pmenu = new wxMenu;\r
-    pmenu->Append(ID_TASKBAR_RESTORE, "&Open Bitcoin");\r
-    pmenu->Append(ID_TASKBAR_OPTIONS, "O&ptions...");\r
-    pmenu->AppendCheckItem(ID_TASKBAR_GENERATE, "&Generate Coins")->Check(fGenerateBitcoins);\r
-#ifndef __WXMAC_OSX__ // Mac has built-in quit menu\r
-    pmenu->AppendSeparator();\r
-    pmenu->Append(ID_TASKBAR_EXIT, "E&xit");\r
-#endif\r
-    return pmenu;\r
-}\r
-\r
-\r
-\r
-\r
-\r
-\r
-\r
-\r
-\r
-\r
-//////////////////////////////////////////////////////////////////////////////\r
-//\r
-// CMyApp\r
-//\r
-\r
-// Define a new application\r
-class CMyApp: public wxApp\r
-{\r
-  public:\r
-    CMyApp(){};\r
-    ~CMyApp(){};\r
-    bool OnInit();\r
-    bool OnInit2();\r
-    int OnExit();\r
-\r
-    // 2nd-level exception handling: we get all the exceptions occurring in any\r
-    // event handler here\r
-    virtual bool OnExceptionInMainLoop();\r
-\r
-    // 3rd, and final, level exception handling: whenever an unhandled\r
-    // exception is caught, this function is called\r
-    virtual void OnUnhandledException();\r
-\r
-    // and now for something different: this function is called in case of a\r
-    // crash (e.g. dereferencing null pointer, division by 0, ...)\r
-    virtual void OnFatalException();\r
-};\r
-\r
-IMPLEMENT_APP(CMyApp)\r
-\r
-bool CMyApp::OnInit()\r
-{\r
-    bool fRet = false;\r
-    try\r
-    {\r
-        fRet = OnInit2();\r
-    }\r
-    catch (std::exception& e) {\r
-        PrintException(&e, "OnInit()");\r
-    } catch (...) {\r
-        PrintException(NULL, "OnInit()");\r
-    }\r
-    if (!fRet)\r
-        Shutdown(NULL);\r
-    return fRet;\r
-}\r
-\r
-bool CMyApp::OnInit2()\r
-{\r
-#ifdef _MSC_VER\r
-    // Turn off microsoft heap dump noise for now\r
-    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);\r
-    _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));\r
-#endif\r
-#if defined(__WXMSW__) && defined(__WXDEBUG__)\r
-    // Disable malfunctioning wxWidgets debug assertion\r
-    g_isPainting = 10000;\r
-#endif\r
-    wxImage::AddHandler(new wxPNGHandler);\r
-#ifdef __WXMSW__\r
-    SetAppName("Bitcoin");\r
-#else\r
-    SetAppName("bitcoin");\r
-    umask(077);\r
-#endif\r
-\r
-    //\r
-    // Parameters\r
-    //\r
-    ParseParameters(argc, argv);\r
-    if (mapArgs.count("-?") || mapArgs.count("--help"))\r
-    {\r
-#ifdef __WXMSW__\r
-        string strUsage =\r
-            "Usage: bitcoin [options]\t\t\t\t\t\t\n"\r
-            "Options:\n"\r
-            "  -gen\t\t  Generate coins\n"\r
-            "  -gen=0\t\t  Don't generate coins\n"\r
-            "  -min\t\t  Start minimized\n"\r
-            "  -datadir=<dir>\t  Specify data directory\n"\r
-            "  -proxy=<ip:port>\t  Connect through socks4 proxy\n"\r
-            "  -addnode=<ip>\t  Add a node to connect to\n"\r
-            "  -connect=<ip>\t  Connect only to the specified node\n"\r
-            "  -?\t\t  This help message\n";\r
-        wxMessageBox(strUsage, "Bitcoin", wxOK);\r
-#else\r
-        string strUsage =\r
-            "Usage: bitcoin [options]\n"\r
-            "Options:\n"\r
-            "  -gen              Generate coins\n"\r
-            "  -gen=0            Don't generate coins\n"\r
-            "  -min              Start minimized\n"\r
-            "  -datadir=<dir>    Specify data directory\n"\r
-            "  -proxy=<ip:port>  Connect through socks4 proxy\n"\r
-            "  -addnode=<ip>     Add a node to connect to\n"\r
-            "  -connect=<ip>     Connect only to the specified node\n"\r
-            "  -?                This help message\n";\r
-        fprintf(stderr, "%s", strUsage.c_str());\r
-#endif\r
-        return false;\r
-    }\r
-\r
-    if (mapArgs.count("-datadir"))\r
-        strlcpy(pszSetDataDir, mapArgs["-datadir"].c_str(), sizeof(pszSetDataDir));\r
-\r
-    if (mapArgs.count("-debug"))\r
-        fDebug = true;\r
-\r
-    if (mapArgs.count("-printtodebugger"))\r
-        fPrintToDebugger = true;\r
-\r
-    if (!fDebug && !pszSetDataDir[0])\r
-        ShrinkDebugFile();\r
-    printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");\r
-    printf("Bitcoin version %d%s, OS version %s\n", VERSION, pszSubVer, ((string)wxGetOsDescription()).c_str());\r
-\r
-    if (mapArgs.count("-loadblockindextest"))\r
-    {\r
-        CTxDB txdb("r");\r
-        txdb.LoadBlockIndex();\r
-        PrintBlockTree();\r
-        return false;\r
-    }\r
-\r
-    //\r
-    // Limit to single instance per user\r
-    // Required to protect the database files if we're going to keep deleting log.*\r
-    //\r
-#ifdef __WXMSW__\r
-    // todo: wxSingleInstanceChecker wasn't working on Linux, never deleted its lock file\r
-    //  maybe should go by whether successfully bind port 8333 instead\r
-    wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");\r
-    for (int i = 0; i < strMutexName.size(); i++)\r
-        if (!isalnum(strMutexName[i]))\r
-            strMutexName[i] = '.';\r
-    wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);\r
-    if (psingleinstancechecker->IsAnotherRunning())\r
-    {\r
-        printf("Existing instance found\n");\r
-        unsigned int nStart = GetTime();\r
-        loop\r
-        {\r
-            // TODO: find out how to do this in Linux, or replace with wxWidgets commands\r
-            // Show the previous instance and exit\r
-            HWND hwndPrev = FindWindow("wxWindowClassNR", "Bitcoin");\r
-            if (hwndPrev)\r
-            {\r
-                if (IsIconic(hwndPrev))\r
-                    ShowWindow(hwndPrev, SW_RESTORE);\r
-                SetForegroundWindow(hwndPrev);\r
-                return false;\r
-            }\r
-\r
-            if (GetTime() > nStart + 60)\r
-                return false;\r
-\r
-            // Resume this instance if the other exits\r
-            delete psingleinstancechecker;\r
-            Sleep(1000);\r
-            psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);\r
-            if (!psingleinstancechecker->IsAnotherRunning())\r
-                break;\r
-        }\r
-    }\r
-#endif\r
-\r
-    // Bind to the port early so we can tell if another instance is already running.\r
-    // This is a backup to wxSingleInstanceChecker, which doesn't work on Linux.\r
-    string strErrors;\r
-    if (!BindListenPort(strErrors))\r
-    {\r
-        wxMessageBox(strErrors, "Bitcoin");\r
-        return false;\r
-    }\r
-\r
-    //\r
-    // Load data files\r
-    //\r
-    bool fFirstRun;\r
-    strErrors = "";\r
-    int64 nStart;\r
-\r
-    printf("Loading addresses...\n");\r
-    nStart = GetTimeMillis();\r
-    if (!LoadAddresses())\r
-        strErrors += "Error loading addr.dat      \n";\r
-    printf(" addresses   %15"PRI64d"ms\n", GetTimeMillis() - nStart);\r
-\r
-    printf("Loading block index...\n");\r
-    nStart = GetTimeMillis();\r
-    if (!LoadBlockIndex())\r
-        strErrors += "Error loading blkindex.dat      \n";\r
-    printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);\r
-\r
-    printf("Loading wallet...\n");\r
-    nStart = GetTimeMillis();\r
-    if (!LoadWallet(fFirstRun))\r
-        strErrors += "Error loading wallet.dat      \n";\r
-    printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);\r
-\r
-    printf("Done loading\n");\r
-\r
-        //// debug print\r
-        printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());\r
-        printf("nBestHeight = %d\n",            nBestHeight);\r
-        printf("mapKeys.size() = %d\n",         mapKeys.size());\r
-        printf("mapPubKeys.size() = %d\n",      mapPubKeys.size());\r
-        printf("mapWallet.size() = %d\n",       mapWallet.size());\r
-        printf("mapAddressBook.size() = %d\n",  mapAddressBook.size());\r
-\r
-    if (!strErrors.empty())\r
-    {\r
-        wxMessageBox(strErrors, "Bitcoin");\r
-        return false;\r
-    }\r
-\r
-    // Add wallet transactions that aren't already in a block to mapTransactions\r
-    ReacceptWalletTransactions();\r
-\r
-    //\r
-    // Parameters\r
-    //\r
-    if (mapArgs.count("-printblockindex") || mapArgs.count("-printblocktree"))\r
-    {\r
-        PrintBlockTree();\r
-        return false;\r
-    }\r
-\r
-    if (mapArgs.count("-printblock"))\r
-    {\r
-        string strMatch = mapArgs["-printblock"];\r
-        int nFound = 0;\r
-        for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)\r
-        {\r
-            uint256 hash = (*mi).first;\r
-            if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)\r
-            {\r
-                CBlockIndex* pindex = (*mi).second;\r
-                CBlock block;\r
-                block.ReadFromDisk(pindex);\r
-                block.BuildMerkleTree();\r
-                block.print();\r
-                printf("\n");\r
-                nFound++;\r
-            }\r
-        }\r
-        if (nFound == 0)\r
-            printf("No blocks matching %s were found\n", strMatch.c_str());\r
-        return false;\r
-    }\r
-\r
-    if (mapArgs.count("-gen"))\r
-    {\r
-        if (mapArgs["-gen"].empty())\r
-            fGenerateBitcoins = true;\r
-        else\r
-            fGenerateBitcoins = (atoi(mapArgs["-gen"].c_str()) != 0);\r
-    }\r
-\r
-    if (mapArgs.count("-proxy"))\r
-    {\r
-        fUseProxy = true;\r
-        addrProxy = CAddress(mapArgs["-proxy"]);\r
-        if (!addrProxy.IsValid())\r
-        {\r
-            wxMessageBox("Invalid -proxy address", "Bitcoin");\r
-            return false;\r
-        }\r
-    }\r
-\r
-    if (mapArgs.count("-addnode"))\r
-    {\r
-        foreach(string strAddr, mapMultiArgs["-addnode"])\r
-        {\r
-            CAddress addr(strAddr, NODE_NETWORK);\r
-            addr.nTime = 0; // so it won't relay unless successfully connected\r
-            if (addr.IsValid())\r
-                AddAddress(addr);\r
-        }\r
-    }\r
-\r
-    //\r
-    // Create the main frame window\r
-    //\r
-    if (!mapArgs.count("-noui"))\r
-    {\r
-        pframeMain = new CMainFrame(NULL);\r
-        if (mapArgs.count("-min"))\r
-            pframeMain->Iconize(true);\r
-        pframeMain->Show(true);  // have to show first to get taskbar button to hide\r
-        if (fMinimizeToTray && pframeMain->IsIconized())\r
-            fClosedToTray = true;\r
-        pframeMain->Show(!fClosedToTray);\r
-        ptaskbaricon->Show(fMinimizeToTray || fClosedToTray);\r
-\r
-        CreateThread(ThreadDelayedRepaint, NULL);\r
-    }\r
-\r
-    if (!CheckDiskSpace())\r
-        return false;\r
-\r
-    RandAddSeedPerfmon();\r
-\r
-    if (!CreateThread(StartNode, NULL))\r
-        wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");\r
-\r
-    if (fFirstRun)\r
-        SetStartOnSystemStartup(true);\r
-\r
-\r
-    //\r
-    // Tests\r
-    //\r
-#ifdef __WXMSW__\r
-    if (argc >= 2 && stricmp(argv[1], "-send") == 0)\r
-#else\r
-    if (argc >= 2 && strcmp(argv[1], "-send") == 0)\r
-#endif\r
-    {\r
-        int64 nValue = 1;\r
-        if (argc >= 3)\r
-            ParseMoney(argv[2], nValue);\r
-\r
-        string strAddress;\r
-        if (argc >= 4)\r
-            strAddress = argv[3];\r
-        CAddress addr(strAddress);\r
-\r
-        CWalletTx wtx;\r
-        wtx.mapValue["to"] = strAddress;\r
-        wtx.mapValue["from"] = addrLocalHost.ToString();\r
-        wtx.mapValue["message"] = "command line send";\r
-\r
-        // Send to IP address\r
-        CSendingDialog* pdialog = new CSendingDialog(pframeMain, addr, nValue, wtx);\r
-        if (!pdialog->ShowModal())\r
-            return false;\r
-    }\r
-\r
-    return true;\r
-}\r
-\r
-int CMyApp::OnExit()\r
-{\r
-    Shutdown(NULL);\r
-    return wxApp::OnExit();\r
-}\r
-\r
-bool CMyApp::OnExceptionInMainLoop()\r
-{\r
-    try\r
-    {\r
-        throw;\r
-    }\r
-    catch (std::exception& e)\r
-    {\r
-        PrintException(&e, "CMyApp::OnExceptionInMainLoop()");\r
-        wxLogWarning("Exception %s %s", typeid(e).name(), e.what());\r
-        Sleep(1000);\r
-        throw;\r
-    }\r
-    catch (...)\r
-    {\r
-        PrintException(NULL, "CMyApp::OnExceptionInMainLoop()");\r
-        wxLogWarning("Unknown exception");\r
-        Sleep(1000);\r
-        throw;\r
-    }\r
-\r
-    return true;\r
-}\r
-\r
-void CMyApp::OnUnhandledException()\r
-{\r
-    // this shows how we may let some exception propagate uncaught\r
-    try\r
-    {\r
-        throw;\r
-    }\r
-    catch (std::exception& e)\r
-    {\r
-        PrintException(&e, "CMyApp::OnUnhandledException()");\r
-        wxLogWarning("Exception %s %s", typeid(e).name(), e.what());\r
-        Sleep(1000);\r
-        throw;\r
-    }\r
-    catch (...)\r
-    {\r
-        PrintException(NULL, "CMyApp::OnUnhandledException()");\r
-        wxLogWarning("Unknown exception");\r
-        Sleep(1000);\r
-        throw;\r
-    }\r
-}\r
-\r
-void CMyApp::OnFatalException()\r
-{\r
-    wxMessageBox("Program has crashed and will terminate.  ", "Bitcoin", wxOK | wxICON_ERROR);\r
-}\r
-\r
-\r
-\r
-\r
-\r
-#ifdef __WXMSW__\r
-typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);\r
-\r
-string MyGetSpecialFolderPath(int nFolder, bool fCreate)\r
-{\r
-    char pszPath[MAX_PATH+100] = "";\r
-\r
-    // SHGetSpecialFolderPath is not usually available on NT 4.0\r
-    HMODULE hShell32 = LoadLibrary("shell32.dll");\r
-    if (hShell32)\r
-    {\r
-        PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =\r
-            (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");\r
-        if (pSHGetSpecialFolderPath)\r
-            (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);\r
-        FreeModule(hShell32);\r
-    }\r
-\r
-    // Backup option\r
-    if (pszPath[0] == '\0')\r
-    {\r
-        if (nFolder == CSIDL_STARTUP)\r
-        {\r
-            strcpy(pszPath, getenv("USERPROFILE"));\r
-            strcat(pszPath, "\\Start Menu\\Programs\\Startup");\r
-        }\r
-        else if (nFolder == CSIDL_APPDATA)\r
-        {\r
-            strcpy(pszPath, getenv("APPDATA"));\r
-        }\r
-    }\r
-\r
-    return pszPath;\r
-}\r
-\r
-string StartupShortcutPath()\r
-{\r
-    return MyGetSpecialFolderPath(CSIDL_STARTUP, true) + "\\Bitcoin.lnk";\r
-}\r
-\r
-bool GetStartOnSystemStartup()\r
-{\r
-    return wxFileExists(StartupShortcutPath());\r
-}\r
-\r
-void SetStartOnSystemStartup(bool fAutoStart)\r
-{\r
-    // If the shortcut exists already, remove it for updating\r
-    remove(StartupShortcutPath().c_str());\r
-\r
-    if (fAutoStart)\r
-    {\r
-        CoInitialize(NULL);\r
-\r
-        // Get a pointer to the IShellLink interface.\r
-        IShellLink* psl = NULL;\r
-        HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,\r
-                                CLSCTX_INPROC_SERVER, IID_IShellLink,\r
-                                reinterpret_cast<void**>(&psl));\r
-\r
-        if (SUCCEEDED(hres))\r
-        {\r
-            // Get the current executable path\r
-            char pszExePath[MAX_PATH];\r
-            GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));\r
-\r
-            // Set the path to the shortcut target\r
-            psl->SetPath(pszExePath);\r
-            PathRemoveFileSpec(pszExePath);\r
-            psl->SetWorkingDirectory(pszExePath);\r
-            psl->SetShowCmd(SW_SHOWMINNOACTIVE);\r
-\r
-            // Query IShellLink for the IPersistFile interface for\r
-            // saving the shortcut in persistent storage.\r
-            IPersistFile* ppf = NULL;\r
-            hres = psl->QueryInterface(IID_IPersistFile,\r
-                                       reinterpret_cast<void**>(&ppf));\r
-            if (SUCCEEDED(hres))\r
-            {\r
-                WCHAR pwsz[MAX_PATH];\r
-                // Ensure that the string is ANSI.\r
-                MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().c_str(), -1, pwsz, MAX_PATH);\r
-                // Save the link by calling IPersistFile::Save.\r
-                hres = ppf->Save(pwsz, TRUE);\r
-                ppf->Release();\r
-            }\r
-            psl->Release();\r
-        }\r
-        CoUninitialize();\r
-    }\r
-}\r
-#else\r
-bool GetStartOnSystemStartup() { return false; }\r
-void SetStartOnSystemStartup(bool fAutoStart) { }\r
-#endif\r
-\r
-\r
-\r
-\r
-\r
-\r
-\r
-\r
-\r
-\r
+// Copyright (c) 2009-2010 Satoshi Nakamoto
+// Distributed under the MIT/X11 software license, see the accompanying
+// file license.txt or http://www.opensource.org/licenses/mit-license.php.
+
+#include "headers.h"
+#ifdef _MSC_VER
+#include <crtdbg.h>
+#endif
+
+
+
+DEFINE_EVENT_TYPE(wxEVT_UITHREADCALL)
+
+CMainFrame* pframeMain = NULL;
+CMyTaskBarIcon* ptaskbaricon = NULL;
+bool fClosedToTray = false;
+wxLocale g_locale;
+
+
+
+
+
+
+
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// Util
+//
+
+void HandleCtrlA(wxKeyEvent& event)
+{
+    // Ctrl-a select all
+    event.Skip();
+    wxTextCtrl* textCtrl = (wxTextCtrl*)event.GetEventObject();
+    if (event.GetModifiers() == wxMOD_CONTROL && event.GetKeyCode() == 'A')
+        textCtrl->SetSelection(-1, -1);
+}
+
+bool Is24HourTime()
+{
+    //char pszHourFormat[256];
+    //pszHourFormat[0] = '\0';
+    //GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_ITIME, pszHourFormat, 256);
+    //return (pszHourFormat[0] != '0');
+    return true;
+}
+
+string DateStr(int64 nTime)
+{
+    // Can only be used safely here in the UI
+    return (string)wxDateTime((time_t)nTime).FormatDate();
+}
+
+string DateTimeStr(int64 nTime)
+{
+    // Can only be used safely here in the UI
+    wxDateTime datetime((time_t)nTime);
+    if (Is24HourTime())
+        return (string)datetime.Format("%x %H:%M");
+    else
+        return (string)datetime.Format("%x ") + itostr((datetime.GetHour() + 11) % 12 + 1) + (string)datetime.Format(":%M %p");
+}
+
+wxString GetItemText(wxListCtrl* listCtrl, int nIndex, int nColumn)
+{
+    // Helper to simplify access to listctrl
+    wxListItem item;
+    item.m_itemId = nIndex;
+    item.m_col = nColumn;
+    item.m_mask = wxLIST_MASK_TEXT;
+    if (!listCtrl->GetItem(item))
+        return "";
+    return item.GetText();
+}
+
+int InsertLine(wxListCtrl* listCtrl, const wxString& str0, const wxString& str1)
+{
+    int nIndex = listCtrl->InsertItem(listCtrl->GetItemCount(), str0);
+    listCtrl->SetItem(nIndex, 1, str1);
+    return nIndex;
+}
+
+int InsertLine(wxListCtrl* listCtrl, const wxString& str0, const wxString& str1, const wxString& str2, const wxString& str3, const wxString& str4)
+{
+    int nIndex = listCtrl->InsertItem(listCtrl->GetItemCount(), str0);
+    listCtrl->SetItem(nIndex, 1, str1);
+    listCtrl->SetItem(nIndex, 2, str2);
+    listCtrl->SetItem(nIndex, 3, str3);
+    listCtrl->SetItem(nIndex, 4, str4);
+    return nIndex;
+}
+
+int InsertLine(wxListCtrl* listCtrl, void* pdata, const wxString& str0, const wxString& str1, const wxString& str2, const wxString& str3, const wxString& str4)
+{
+    int nIndex = listCtrl->InsertItem(listCtrl->GetItemCount(), str0);
+    listCtrl->SetItemPtrData(nIndex, (wxUIntPtr)pdata);
+    listCtrl->SetItem(nIndex, 1, str1);
+    listCtrl->SetItem(nIndex, 2, str2);
+    listCtrl->SetItem(nIndex, 3, str3);
+    listCtrl->SetItem(nIndex, 4, str4);
+    return nIndex;
+}
+
+void SetItemTextColour(wxListCtrl* listCtrl, int nIndex, const wxColour& colour)
+{
+    // Repaint on Windows is more flickery if the colour has ever been set,
+    // so don't want to set it unless it's different.  Default colour has
+    // alpha 0 transparent, so our colours don't match using operator==.
+    wxColour c1 = listCtrl->GetItemTextColour(nIndex);
+    if (!c1.IsOk())
+        c1 = wxColour(0,0,0);
+    if (colour.Red() != c1.Red() || colour.Green() != c1.Green() || colour.Blue() != c1.Blue())
+        listCtrl->SetItemTextColour(nIndex, colour);
+}
+
+void SetSelection(wxListCtrl* listCtrl, int nIndex)
+{
+    int nSize = listCtrl->GetItemCount();
+    long nState = (wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED);
+    for (int i = 0; i < nSize; i++)
+        listCtrl->SetItemState(i, (i == nIndex ? nState : 0), nState);
+}
+
+int GetSelection(wxListCtrl* listCtrl)
+{
+    int nSize = listCtrl->GetItemCount();
+    for (int i = 0; i < nSize; i++)
+        if (listCtrl->GetItemState(i, wxLIST_STATE_FOCUSED))
+            return i;
+    return -1;
+}
+
+string HtmlEscape(const char* psz, bool fMultiLine=false)
+{
+    int len = 0;
+    for (const char* p = psz; *p; p++)
+    {
+             if (*p == '<') len += 4;
+        else if (*p == '>') len += 4;
+        else if (*p == '&') len += 5;
+        else if (*p == '"') len += 6;
+        else if (*p == ' ' && p > psz && p[-1] == ' ' && p[1] == ' ') len += 6;
+        else if (*p == '\n' && fMultiLine) len += 5;
+        else
+            len++;
+    }
+    string str;
+    str.reserve(len);
+    for (const char* p = psz; *p; p++)
+    {
+             if (*p == '<') str += "&lt;";
+        else if (*p == '>') str += "&gt;";
+        else if (*p == '&') str += "&amp;";
+        else if (*p == '"') str += "&quot;";
+        else if (*p == ' ' && p > psz && p[-1] == ' ' && p[1] == ' ') str += "&nbsp;";
+        else if (*p == '\n' && fMultiLine) str += "<br>\n";
+        else
+            str += *p;
+    }
+    return str;
+}
+
+string HtmlEscape(const string& str, bool fMultiLine=false)
+{
+    return HtmlEscape(str.c_str(), fMultiLine);
+}
+
+void CalledMessageBox(const string& message, const string& caption, int style, wxWindow* parent, int x, int y, int* pnRet, bool* pfDone)
+{
+    *pnRet = wxMessageBox(message, caption, style, parent, x, y);
+    *pfDone = true;
+}
+
+int ThreadSafeMessageBox(const string& message, const string& caption, int style, wxWindow* parent, int x, int y)
+{
+#ifdef __WXMSW__
+    return wxMessageBox(message, caption, style, parent, x, y);
+#else
+    if (wxThread::IsMain() || fDaemon)
+    {
+        return wxMessageBox(message, caption, style, parent, x, y);
+    }
+    else
+    {
+        int nRet = 0;
+        bool fDone = false;
+        UIThreadCall(bind(CalledMessageBox, message, caption, style, parent, x, y, &nRet, &fDone));
+        while (!fDone)
+            Sleep(100);
+        return nRet;
+    }
+#endif
+}
+
+bool ThreadSafeAskFee(int64 nFeeRequired, const string& strCaption, wxWindow* parent)
+{
+    if (nFeeRequired < CENT || nFeeRequired <= nTransactionFee || fDaemon)
+        return true;
+    string strMessage = strprintf(
+        _("This transaction is over the size limit.  You can still send it for a fee of %s, "
+          "which goes to the nodes that process your transaction and helps to support the network.  "
+          "Do you want to pay the fee?"),
+        FormatMoney(nFeeRequired).c_str());
+    return (ThreadSafeMessageBox(strMessage, strCaption, wxYES_NO, parent) == wxYES);
+}
+
+void CalledSetStatusBar(const string& strText, int nField)
+{
+    if (nField == 0 && GetWarnings("statusbar") != "")
+        return;
+    if (pframeMain && pframeMain->m_statusBar)
+        pframeMain->m_statusBar->SetStatusText(strText, nField);
+}
+
+void SetDefaultReceivingAddress(const string& strAddress)
+{
+    // Update main window address and database
+    if (pframeMain == NULL)
+        return;
+    if (strAddress != pframeMain->m_textCtrlAddress->GetValue())
+    {
+        uint160 hash160;
+        if (!AddressToHash160(strAddress, hash160))
+            return;
+        if (!mapPubKeys.count(hash160))
+            return;
+        CWalletDB().WriteDefaultKey(mapPubKeys[hash160]);
+        pframeMain->m_textCtrlAddress->SetValue(strAddress);
+    }
+}
+
+
+
+
+
+
+
+
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CMainFrame
+//
+
+CMainFrame::CMainFrame(wxWindow* parent) : CMainFrameBase(parent)
+{
+    Connect(wxEVT_UITHREADCALL, wxCommandEventHandler(CMainFrame::OnUIThreadCall), NULL, this);
+
+    // Set initially selected page
+    wxNotebookEvent event;
+    event.SetSelection(0);
+    OnNotebookPageChanged(event);
+    m_notebook->ChangeSelection(0);
+
+    // Init
+    fRefreshListCtrl = false;
+    fRefreshListCtrlRunning = false;
+    fOnSetFocusAddress = false;
+    fRefresh = false;
+    m_choiceFilter->SetSelection(0);
+    double dResize = 1.0;
+#ifdef __WXMSW__
+    SetIcon(wxICON(bitcoin));
+#else
+    SetIcon(bitcoin80_xpm);
+    SetBackgroundColour(m_toolBar->GetBackgroundColour());
+    wxFont fontTmp = m_staticText41->GetFont();
+    fontTmp.SetFamily(wxFONTFAMILY_TELETYPE);
+    m_staticTextBalance->SetFont(fontTmp);
+    m_staticTextBalance->SetSize(140, 17);
+    // resize to fit ubuntu's huge default font
+    dResize = 1.22;
+    SetSize(dResize * GetSize().GetWidth(), 1.15 * GetSize().GetHeight());
+#endif
+    m_staticTextBalance->SetLabel(FormatMoney(GetBalance()) + "  ");
+    m_listCtrl->SetFocus();
+    ptaskbaricon = new CMyTaskBarIcon();
+#ifdef __WXMAC_OSX__
+    // Mac automatically moves wxID_EXIT, wxID_PREFERENCES and wxID_ABOUT
+    // to their standard places, leaving these menus empty.
+    GetMenuBar()->Remove(2); // remove Help menu
+    GetMenuBar()->Remove(0); // remove File menu
+#endif
+
+    // Init column headers
+    int nDateWidth = DateTimeStr(1229413914).size() * 6 + 8;
+    if (!strstr(DateTimeStr(1229413914).c_str(), "2008"))
+        nDateWidth += 12;
+#ifdef __WXMAC_OSX__
+    nDateWidth += 5;
+    dResize -= 0.01;
+#endif
+    wxListCtrl* pplistCtrl[] = {m_listCtrlAll, m_listCtrlSentReceived, m_listCtrlSent, m_listCtrlReceived};
+    foreach(wxListCtrl* p, pplistCtrl)
+    {
+        p->InsertColumn(0, "",               wxLIST_FORMAT_LEFT,  dResize * 0);
+        p->InsertColumn(1, "",               wxLIST_FORMAT_LEFT,  dResize * 0);
+        p->InsertColumn(2, _("Status"),      wxLIST_FORMAT_LEFT,  dResize * 112);
+        p->InsertColumn(3, _("Date"),        wxLIST_FORMAT_LEFT,  dResize * nDateWidth);
+        p->InsertColumn(4, _("Description"), wxLIST_FORMAT_LEFT,  dResize * 409 - nDateWidth);
+        p->InsertColumn(5, _("Debit"),       wxLIST_FORMAT_RIGHT, dResize * 79);
+        p->InsertColumn(6, _("Credit"),      wxLIST_FORMAT_RIGHT, dResize * 79);
+    }
+
+    // Init status bar
+    int pnWidths[3] = { -100, 88, 300 };
+#ifndef __WXMSW__
+    pnWidths[1] = pnWidths[1] * 1.1 * dResize;
+    pnWidths[2] = pnWidths[2] * 1.1 * dResize;
+#endif
+    m_statusBar->SetFieldsCount(3, pnWidths);
+
+    // Fill your address text box
+    vector<unsigned char> vchPubKey;
+    if (CWalletDB("r").ReadDefaultKey(vchPubKey))
+        m_textCtrlAddress->SetValue(PubKeyToAddress(vchPubKey));
+
+    // Fill listctrl with wallet transactions
+    RefreshListCtrl();
+}
+
+CMainFrame::~CMainFrame()
+{
+    pframeMain = NULL;
+    delete ptaskbaricon;
+    ptaskbaricon = NULL;
+}
+
+void CMainFrame::OnNotebookPageChanged(wxNotebookEvent& event)
+{
+    event.Skip();
+    nPage = event.GetSelection();
+    if (nPage == ALL)
+    {
+        m_listCtrl = m_listCtrlAll;
+        fShowGenerated = true;
+        fShowSent = true;
+        fShowReceived = true;
+    }
+    else if (nPage == SENTRECEIVED)
+    {
+        m_listCtrl = m_listCtrlSentReceived;
+        fShowGenerated = false;
+        fShowSent = true;
+        fShowReceived = true;
+    }
+    else if (nPage == SENT)
+    {
+        m_listCtrl = m_listCtrlSent;
+        fShowGenerated = false;
+        fShowSent = true;
+        fShowReceived = false;
+    }
+    else if (nPage == RECEIVED)
+    {
+        m_listCtrl = m_listCtrlReceived;
+        fShowGenerated = false;
+        fShowSent = false;
+        fShowReceived = true;
+    }
+    RefreshListCtrl();
+    m_listCtrl->SetFocus();
+}
+
+void CMainFrame::OnClose(wxCloseEvent& event)
+{
+    if (fMinimizeOnClose && event.CanVeto() && !IsIconized())
+    {
+        // Divert close to minimize
+        event.Veto();
+        fClosedToTray = true;
+        Iconize(true);
+    }
+    else
+    {
+        Destroy();
+        CreateThread(Shutdown, NULL);
+    }
+}
+
+void CMainFrame::OnIconize(wxIconizeEvent& event)
+{
+    event.Skip();
+    // Hide the task bar button when minimized.
+    // Event is sent when the frame is minimized or restored.
+    // wxWidgets 2.8.9 doesn't have IsIconized() so there's no way
+    // to get rid of the deprecated warning.  Just ignore it.
+    if (!event.Iconized())
+        fClosedToTray = false;
+#if defined(__WXGTK__) || defined(__WXMAC_OSX__)
+    if (GetBoolArg("-minimizetotray")) {
+#endif
+    // The tray icon sometimes disappears on ubuntu karmic
+    // Hiding the taskbar button doesn't work cleanly on ubuntu lucid
+    // Reports of CPU peg on 64-bit linux
+    if (fMinimizeToTray && event.Iconized())
+        fClosedToTray = true;
+    Show(!fClosedToTray);
+    ptaskbaricon->Show(fMinimizeToTray || fClosedToTray);
+#if defined(__WXGTK__) || defined(__WXMAC_OSX__)
+    }
+#endif
+}
+
+void CMainFrame::OnMouseEvents(wxMouseEvent& event)
+{
+    event.Skip();
+    RandAddSeed();
+    RAND_add(&event.m_x, sizeof(event.m_x), 0.25);
+    RAND_add(&event.m_y, sizeof(event.m_y), 0.25);
+}
+
+void CMainFrame::OnListColBeginDrag(wxListEvent& event)
+{
+    // Hidden columns not resizeable
+    if (event.GetColumn() <= 1 && !fDebug)
+        event.Veto();
+    else
+        event.Skip();
+}
+
+int CMainFrame::GetSortIndex(const string& strSort)
+{
+#ifdef __WXMSW__
+    return 0;
+#else
+    // The wx generic listctrl implementation used on GTK doesn't sort,
+    // so we have to do it ourselves.  Remember, we sort in reverse order.
+    // In the wx generic implementation, they store the list of items
+    // in a vector, so indexed lookups are fast, but inserts are slower
+    // the closer they are to the top.
+    int low = 0;
+    int high = m_listCtrl->GetItemCount();
+    while (low < high)
+    {
+        int mid = low + ((high - low) / 2);
+        if (strSort.compare(m_listCtrl->GetItemText(mid).c_str()) >= 0)
+            high = mid;
+        else
+            low = mid + 1;
+    }
+    return low;
+#endif
+}
+
+void CMainFrame::InsertLine(bool fNew, int nIndex, uint256 hashKey, string strSort, const wxColour& colour, const wxString& str2, const wxString& str3, const wxString& str4, const wxString& str5, const wxString& str6)
+{
+    strSort = " " + strSort;       // leading space to workaround wx2.9.0 ubuntu 9.10 bug
+    long nData = *(long*)&hashKey; //  where first char of hidden column is displayed
+
+    // Find item
+    if (!fNew && nIndex == -1)
+    {
+        string strHash = " " + hashKey.ToString();
+        while ((nIndex = m_listCtrl->FindItem(nIndex, nData)) != -1)
+            if (GetItemText(m_listCtrl, nIndex, 1) == strHash)
+                break;
+    }
+
+    // fNew is for blind insert, only use if you're sure it's new
+    if (fNew || nIndex == -1)
+    {
+        nIndex = m_listCtrl->InsertItem(GetSortIndex(strSort), strSort);
+    }
+    else
+    {
+        // If sort key changed, must delete and reinsert to make it relocate
+        if (GetItemText(m_listCtrl, nIndex, 0) != strSort)
+        {
+            m_listCtrl->DeleteItem(nIndex);
+            nIndex = m_listCtrl->InsertItem(GetSortIndex(strSort), strSort);
+        }
+    }
+
+    m_listCtrl->SetItem(nIndex, 1, " " + hashKey.ToString());
+    m_listCtrl->SetItem(nIndex, 2, str2);
+    m_listCtrl->SetItem(nIndex, 3, str3);
+    m_listCtrl->SetItem(nIndex, 4, str4);
+    m_listCtrl->SetItem(nIndex, 5, str5);
+    m_listCtrl->SetItem(nIndex, 6, str6);
+    m_listCtrl->SetItemData(nIndex, nData);
+    SetItemTextColour(m_listCtrl, nIndex, colour);
+}
+
+bool CMainFrame::DeleteLine(uint256 hashKey)
+{
+    long nData = *(long*)&hashKey;
+
+    // Find item
+    int nIndex = -1;
+    string strHash = " " + hashKey.ToString();
+    while ((nIndex = m_listCtrl->FindItem(nIndex, nData)) != -1)
+        if (GetItemText(m_listCtrl, nIndex, 1) == strHash)
+            break;
+
+    if (nIndex != -1)
+        m_listCtrl->DeleteItem(nIndex);
+
+    return nIndex != -1;
+}
+
+string FormatTxStatus(const CWalletTx& wtx)
+{
+    // Status
+    if (!wtx.IsFinal())
+    {
+        if (wtx.nLockTime < 500000000)
+            return strprintf(_("Open for %d blocks"), nBestHeight - wtx.nLockTime);
+        else
+            return strprintf(_("Open until %s"), DateTimeStr(wtx.nLockTime).c_str());
+    }
+    else
+    {
+        int nDepth = wtx.GetDepthInMainChain();
+        if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
+            return strprintf(_("%d/offline?"), nDepth);
+        else if (nDepth < 6)
+            return strprintf(_("%d/unconfirmed"), nDepth);
+        else
+            return strprintf(_("%d confirmations"), nDepth);
+    }
+}
+
+string SingleLine(const string& strIn)
+{
+    string strOut;
+    bool fOneSpace = false;
+    foreach(unsigned char c, strIn)
+    {
+        if (isspace(c))
+        {
+            fOneSpace = true;
+        }
+        else if (c > ' ')
+        {
+            if (fOneSpace && !strOut.empty())
+                strOut += ' ';
+            strOut += c;
+            fOneSpace = false;
+        }
+    }
+    return strOut;
+}
+
+bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex)
+{
+    int64 nTime = wtx.nTimeDisplayed = wtx.GetTxTime();
+    int64 nCredit = wtx.GetCredit(true);
+    int64 nDebit = wtx.GetDebit();
+    int64 nNet = nCredit - nDebit;
+    uint256 hash = wtx.GetHash();
+    string strStatus = FormatTxStatus(wtx);
+    bool fConfirmed = wtx.fConfirmedDisplayed = wtx.IsConfirmed();
+    wxColour colour = (fConfirmed ? wxColour(0,0,0) : wxColour(128,128,128));
+    map<string, string> mapValue = wtx.mapValue;
+    wtx.nLinesDisplayed = 1;
+    nListViewUpdated++;
+
+    // Filter
+    if (wtx.IsCoinBase())
+    {
+        // Don't show generated coin until confirmed by at least one block after it
+        // so we don't get the user's hopes up until it looks like it's probably accepted.
+        //
+        // It is not an error when generated blocks are not accepted.  By design,
+        // some percentage of blocks, like 10% or more, will end up not accepted.
+        // This is the normal mechanism by which the network copes with latency.
+        //
+        // We display regular transactions right away before any confirmation
+        // because they can always get into some block eventually.  Generated coins
+        // are special because if their block is not accepted, they are not valid.
+        //
+        if (wtx.GetDepthInMainChain() < 2)
+        {
+            wtx.nLinesDisplayed = 0;
+            return false;
+        }
+
+        if (!fShowGenerated)
+            return false;
+    }
+
+    // Find the block the tx is in
+    CBlockIndex* pindex = NULL;
+    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(wtx.hashBlock);
+    if (mi != mapBlockIndex.end())
+        pindex = (*mi).second;
+
+    // Sort order, unrecorded transactions sort to the top
+    string strSort = strprintf("%010d-%01d-%010u",
+        (pindex ? pindex->nHeight : INT_MAX),
+        (wtx.IsCoinBase() ? 1 : 0),
+        wtx.nTimeReceived);
+
+    // Insert line
+    if (nNet > 0 || wtx.IsCoinBase())
+    {
+        //
+        // Credit
+        //
+        string strDescription;
+        if (wtx.IsCoinBase())
+        {
+            // Generated
+            strDescription = _("Generated");
+            if (nCredit == 0)
+            {
+                int64 nUnmatured = 0;
+                foreach(const CTxOut& txout, wtx.vout)
+                    nUnmatured += txout.GetCredit();
+                if (wtx.IsInMainChain())
+                {
+                    strDescription = strprintf(_("Generated (%s matures in %d more blocks)"), FormatMoney(nUnmatured).c_str(), wtx.GetBlocksToMaturity());
+
+                    // Check if the block was requested by anyone
+                    if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
+                        strDescription = _("Generated - Warning: This block was not received by any other nodes and will probably not be accepted!");
+                }
+                else
+                {
+                    strDescription = _("Generated (not accepted)");
+                }
+            }
+        }
+        else if (!mapValue["from"].empty() || !mapValue["message"].empty())
+        {
+            // Received by IP connection
+            if (!fShowReceived)
+                return false;
+            if (!mapValue["from"].empty())
+                strDescription += _("From: ") + mapValue["from"];
+            if (!mapValue["message"].empty())
+            {
+                if (!strDescription.empty())
+                    strDescription += " - ";
+                strDescription += mapValue["message"];
+            }
+        }
+        else
+        {
+            // Received by Bitcoin Address
+            if (!fShowReceived)
+                return false;
+            foreach(const CTxOut& txout, wtx.vout)
+            {
+                if (txout.IsMine())
+                {
+                    vector<unsigned char> vchPubKey;
+                    if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey))
+                    {
+                        CRITICAL_BLOCK(cs_mapAddressBook)
+                        {
+                            //strDescription += _("Received payment to ");
+                            //strDescription += _("Received with address ");
+                            strDescription += _("Received with: ");
+                            string strAddress = PubKeyToAddress(vchPubKey);
+                            map<string, string>::iterator mi = mapAddressBook.find(strAddress);
+                            if (mi != mapAddressBook.end() && !(*mi).second.empty())
+                            {
+                                string strLabel = (*mi).second;
+                                strDescription += strAddress.substr(0,12) + "... ";
+                                strDescription += "(" + strLabel + ")";
+                            }
+                            else
+                                strDescription += strAddress;
+                        }
+                    }
+                    break;
+                }
+            }
+        }
+
+        string strCredit = FormatMoney(nNet, true);
+        if (!fConfirmed)
+            strCredit = "[" + strCredit + "]";
+
+        InsertLine(fNew, nIndex, hash, strSort, colour,
+                   strStatus,
+                   nTime ? DateTimeStr(nTime) : "",
+                   SingleLine(strDescription),
+                   "",
+                   strCredit);
+    }
+    else
+    {
+        bool fAllFromMe = true;
+        foreach(const CTxIn& txin, wtx.vin)
+            fAllFromMe = fAllFromMe && txin.IsMine();
+
+        bool fAllToMe = true;
+        foreach(const CTxOut& txout, wtx.vout)
+            fAllToMe = fAllToMe && txout.IsMine();
+
+        if (fAllFromMe && fAllToMe)
+        {
+            // Payment to self
+            int64 nChange = wtx.GetChange();
+            InsertLine(fNew, nIndex, hash, strSort, colour,
+                       strStatus,
+                       nTime ? DateTimeStr(nTime) : "",
+                       _("Payment to yourself"),
+                       FormatMoney(-(nDebit - nChange), true),
+                       FormatMoney(nCredit - nChange, true));
+        }
+        else if (fAllFromMe)
+        {
+            //
+            // Debit
+            //
+            if (!fShowSent)
+                return false;
+
+            int64 nTxFee = nDebit - wtx.GetValueOut();
+            wtx.nLinesDisplayed = 0;
+            for (int nOut = 0; nOut < wtx.vout.size(); nOut++)
+            {
+                const CTxOut& txout = wtx.vout[nOut];
+                if (txout.IsMine())
+                    continue;
+
+                string strAddress;
+                if (!mapValue["to"].empty())
+                {
+                    // Sent to IP
+                    strAddress = mapValue["to"];
+                }
+                else
+                {
+                    // Sent to Bitcoin Address
+                    uint160 hash160;
+                    if (ExtractHash160(txout.scriptPubKey, hash160))
+                        strAddress = Hash160ToAddress(hash160);
+                }
+
+                string strDescription = _("To: ");
+                CRITICAL_BLOCK(cs_mapAddressBook)
+                    if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())
+                        strDescription += mapAddressBook[strAddress] + " ";
+                strDescription += strAddress;
+                if (!mapValue["message"].empty())
+                {
+                    if (!strDescription.empty())
+                        strDescription += " - ";
+                    strDescription += mapValue["message"];
+                }
+                else if (!mapValue["comment"].empty())
+                {
+                    if (!strDescription.empty())
+                        strDescription += " - ";
+                    strDescription += mapValue["comment"];
+                }
+
+                int64 nValue = txout.nValue;
+                if (nTxFee > 0)
+                {
+                    nValue += nTxFee;
+                    nTxFee = 0;
+                }
+
+                InsertLine(fNew, nIndex, hash, strprintf("%s-%d", strSort.c_str(), nOut), colour,
+                           strStatus,
+                           nTime ? DateTimeStr(nTime) : "",
+                           SingleLine(strDescription),
+                           FormatMoney(-nValue, true),
+                           "");
+                nIndex = -1;
+                wtx.nLinesDisplayed++;
+            }
+        }
+        else
+        {
+            //
+            // Mixed debit transaction, can't break down payees
+            //
+            bool fAllMine = true;
+            foreach(const CTxOut& txout, wtx.vout)
+                fAllMine = fAllMine && txout.IsMine();
+            foreach(const CTxIn& txin, wtx.vin)
+                fAllMine = fAllMine && txin.IsMine();
+
+            InsertLine(fNew, nIndex, hash, strSort, colour,
+                       strStatus,
+                       nTime ? DateTimeStr(nTime) : "",
+                       "",
+                       FormatMoney(nNet, true),
+                       "");
+        }
+    }
+
+    return true;
+}
+
+void CMainFrame::RefreshListCtrl()
+{
+    fRefreshListCtrl = true;
+    ::wxWakeUpIdle();
+}
+
+void CMainFrame::OnIdle(wxIdleEvent& event)
+{
+    if (fRefreshListCtrl)
+    {
+        // Collect list of wallet transactions and sort newest first
+        bool fEntered = false;
+        vector<pair<unsigned int, uint256> > vSorted;
+        TRY_CRITICAL_BLOCK(cs_mapWallet)
+        {
+            printf("RefreshListCtrl starting\n");
+            fEntered = true;
+            fRefreshListCtrl = false;
+            vWalletUpdated.clear();
+
+            // Do the newest transactions first
+            vSorted.reserve(mapWallet.size());
+            for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
+            {
+                const CWalletTx& wtx = (*it).second;
+                unsigned int nTime = UINT_MAX - wtx.GetTxTime();
+                vSorted.push_back(make_pair(nTime, (*it).first));
+            }
+            m_listCtrl->DeleteAllItems();
+        }
+        if (!fEntered)
+            return;
+
+        sort(vSorted.begin(), vSorted.end());
+
+        // Fill list control
+        for (int i = 0; i < vSorted.size();)
+        {
+            if (fShutdown)
+                return;
+            bool fEntered = false;
+            TRY_CRITICAL_BLOCK(cs_mapWallet)
+            {
+                fEntered = true;
+                uint256& hash = vSorted[i++].second;
+                map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
+                if (mi != mapWallet.end())
+                    InsertTransaction((*mi).second, true);
+            }
+            if (!fEntered || i == 100 || i % 500 == 0)
+                wxYield();
+        }
+
+        printf("RefreshListCtrl done\n");
+
+        // Update transaction total display
+        MainFrameRepaint();
+    }
+    else
+    {
+        // Check for time updates
+        static int64 nLastTime;
+        if (GetTime() > nLastTime + 30)
+        {
+            TRY_CRITICAL_BLOCK(cs_mapWallet)
+            {
+                nLastTime = GetTime();
+                for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
+                {
+                    CWalletTx& wtx = (*it).second;
+                    if (wtx.nTimeDisplayed && wtx.nTimeDisplayed != wtx.GetTxTime())
+                        InsertTransaction(wtx, false);
+                }
+            }
+        }
+    }
+}
+
+void CMainFrame::RefreshStatusColumn()
+{
+    static int nLastTop;
+    static CBlockIndex* pindexLastBest;
+    static unsigned int nLastRefreshed;
+
+    int nTop = max((int)m_listCtrl->GetTopItem(), 0);
+    if (nTop == nLastTop && pindexLastBest == pindexBest)
+        return;
+
+    TRY_CRITICAL_BLOCK(cs_mapWallet)
+    {
+        int nStart = nTop;
+        int nEnd = min(nStart + 100, m_listCtrl->GetItemCount());
+
+        if (pindexLastBest == pindexBest && nLastRefreshed == nListViewUpdated)
+        {
+            // If no updates, only need to do the part that moved onto the screen
+            if (nStart >= nLastTop && nStart < nLastTop + 100)
+                nStart = nLastTop + 100;
+            if (nEnd >= nLastTop && nEnd < nLastTop + 100)
+                nEnd = nLastTop;
+        }
+        nLastTop = nTop;
+        pindexLastBest = pindexBest;
+        nLastRefreshed = nListViewUpdated;
+
+        for (int nIndex = nStart; nIndex < min(nEnd, m_listCtrl->GetItemCount()); nIndex++)
+        {
+            uint256 hash((string)GetItemText(m_listCtrl, nIndex, 1));
+            map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
+            if (mi == mapWallet.end())
+            {
+                printf("CMainFrame::RefreshStatusColumn() : tx not found in mapWallet\n");
+                continue;
+            }
+            CWalletTx& wtx = (*mi).second;
+            if (wtx.IsCoinBase() ||
+                wtx.GetTxTime() != wtx.nTimeDisplayed ||
+                wtx.IsConfirmed() != wtx.fConfirmedDisplayed)
+            {
+                if (!InsertTransaction(wtx, false, nIndex))
+                    m_listCtrl->DeleteItem(nIndex--);
+            }
+            else
+            {
+                m_listCtrl->SetItem(nIndex, 2, FormatTxStatus(wtx));
+            }
+        }
+    }
+}
+
+void CMainFrame::OnPaint(wxPaintEvent& event)
+{
+    event.Skip();
+    if (fRefresh)
+    {
+        fRefresh = false;
+        Refresh();
+    }
+}
+
+
+unsigned int nNeedRepaint = 0;
+unsigned int nLastRepaint = 0;
+int64 nLastRepaintTime = 0;
+int64 nRepaintInterval = 500;
+
+void ThreadDelayedRepaint(void* parg)
+{
+    while (!fShutdown)
+    {
+        if (nLastRepaint != nNeedRepaint && GetTimeMillis() - nLastRepaintTime >= nRepaintInterval)
+        {
+            nLastRepaint = nNeedRepaint;
+            if (pframeMain)
+            {
+                printf("DelayedRepaint\n");
+                wxPaintEvent event;
+                pframeMain->fRefresh = true;
+                pframeMain->GetEventHandler()->AddPendingEvent(event);
+            }
+        }
+        Sleep(nRepaintInterval);
+    }
+}
+
+void MainFrameRepaint()
+{
+    // This is called by network code that shouldn't access pframeMain
+    // directly because it could still be running after the UI is closed.
+    if (pframeMain)
+    {
+        // Don't repaint too often
+        static int64 nLastRepaintRequest;
+        if (GetTimeMillis() - nLastRepaintRequest < 100)
+        {
+            nNeedRepaint++;
+            return;
+        }
+        nLastRepaintRequest = GetTimeMillis();
+
+        printf("MainFrameRepaint\n");
+        wxPaintEvent event;
+        pframeMain->fRefresh = true;
+        pframeMain->GetEventHandler()->AddPendingEvent(event);
+    }
+}
+
+void CMainFrame::OnPaintListCtrl(wxPaintEvent& event)
+{
+    // Skip lets the listctrl do the paint, we're just hooking the message
+    event.Skip();
+
+    if (ptaskbaricon)
+        ptaskbaricon->UpdateTooltip();
+
+    //
+    // Slower stuff
+    //
+    static int nTransactionCount;
+    bool fPaintedBalance = false;
+    if (GetTimeMillis() - nLastRepaintTime >= nRepaintInterval)
+    {
+        nLastRepaint = nNeedRepaint;
+        nLastRepaintTime = GetTimeMillis();
+
+        // Update listctrl contents
+        if (!vWalletUpdated.empty())
+        {
+            TRY_CRITICAL_BLOCK(cs_mapWallet)
+            {
+                string strTop;
+                if (m_listCtrl->GetItemCount())
+                    strTop = (string)m_listCtrl->GetItemText(0);
+                foreach(uint256 hash, vWalletUpdated)
+                {
+                    map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
+                    if (mi != mapWallet.end())
+                        InsertTransaction((*mi).second, false);
+                }
+                vWalletUpdated.clear();
+                if (m_listCtrl->GetItemCount() && strTop != (string)m_listCtrl->GetItemText(0))
+                    m_listCtrl->ScrollList(0, INT_MIN/2);
+            }
+        }
+
+        // Balance total
+        TRY_CRITICAL_BLOCK(cs_mapWallet)
+        {
+            fPaintedBalance = true;
+            m_staticTextBalance->SetLabel(FormatMoney(GetBalance()) + "  ");
+
+            // Count hidden and multi-line transactions
+            nTransactionCount = 0;
+            for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
+            {
+                CWalletTx& wtx = (*it).second;
+                nTransactionCount += wtx.nLinesDisplayed;
+            }
+        }
+    }
+    if (!vWalletUpdated.empty() || !fPaintedBalance)
+        nNeedRepaint++;
+
+    // Update status column of visible items only
+    RefreshStatusColumn();
+
+    // Update status bar
+    static string strPrevWarning;
+    string strWarning = GetWarnings("statusbar");
+    if (strWarning != "")
+        m_statusBar->SetStatusText(string("    ") + _(strWarning), 0);
+    else if (strPrevWarning != "")
+        m_statusBar->SetStatusText("", 0);
+    strPrevWarning = strWarning;
+
+    string strGen = "";
+    if (fGenerateBitcoins)
+        strGen = _("    Generating");
+    if (fGenerateBitcoins && vNodes.empty())
+        strGen = _("(not connected)");
+    m_statusBar->SetStatusText(strGen, 1);
+
+    string strStatus = strprintf(_("     %d connections     %d blocks     %d transactions"), vNodes.size(), nBestHeight, nTransactionCount);
+    m_statusBar->SetStatusText(strStatus, 2);
+
+    // Update receiving address
+    string strDefaultAddress = PubKeyToAddress(vchDefaultKey);
+    if (m_textCtrlAddress->GetValue() != strDefaultAddress)
+        m_textCtrlAddress->SetValue(strDefaultAddress);
+}
+
+
+void UIThreadCall(boost::function0<void> fn)
+{
+    // Call this with a function object created with bind.
+    // bind needs all parameters to match the function's expected types
+    // and all default parameters specified.  Some examples:
+    //  UIThreadCall(bind(wxBell));
+    //  UIThreadCall(bind(wxMessageBox, wxT("Message"), wxT("Title"), wxOK, (wxWindow*)NULL, -1, -1));
+    //  UIThreadCall(bind(&CMainFrame::OnMenuHelpAbout, pframeMain, event));
+    if (pframeMain)
+    {
+        wxCommandEvent event(wxEVT_UITHREADCALL);
+        event.SetClientData((void*)new boost::function0<void>(fn));
+        pframeMain->GetEventHandler()->AddPendingEvent(event);
+    }
+}
+
+void CMainFrame::OnUIThreadCall(wxCommandEvent& event)
+{
+    boost::function0<void>* pfn = (boost::function0<void>*)event.GetClientData();
+    (*pfn)();
+    delete pfn;
+}
+
+void CMainFrame::OnMenuFileExit(wxCommandEvent& event)
+{
+    // File->Exit
+    Close(true);
+}
+
+void CMainFrame::OnMenuOptionsGenerate(wxCommandEvent& event)
+{
+    // Options->Generate Coins
+    GenerateBitcoins(event.IsChecked());
+}
+
+void CMainFrame::OnUpdateUIOptionsGenerate(wxUpdateUIEvent& event)
+{
+    event.Check(fGenerateBitcoins);
+}
+
+void CMainFrame::OnMenuOptionsChangeYourAddress(wxCommandEvent& event)
+{
+    // Options->Your Receiving Addresses
+    CAddressBookDialog dialog(this, "", CAddressBookDialog::RECEIVING, false);
+    if (!dialog.ShowModal())
+        return;
+}
+
+void CMainFrame::OnMenuOptionsOptions(wxCommandEvent& event)
+{
+    // Options->Options
+    COptionsDialog dialog(this);
+    dialog.ShowModal();
+}
+
+void CMainFrame::OnMenuHelpAbout(wxCommandEvent& event)
+{
+    // Help->About
+    CAboutDialog dialog(this);
+    dialog.ShowModal();
+}
+
+void CMainFrame::OnButtonSend(wxCommandEvent& event)
+{
+    // Toolbar: Send
+    CSendDialog dialog(this);
+    dialog.ShowModal();
+}
+
+void CMainFrame::OnButtonAddressBook(wxCommandEvent& event)
+{
+    // Toolbar: Address Book
+    CAddressBookDialog dialogAddr(this, "", CAddressBookDialog::SENDING, false);
+    if (dialogAddr.ShowModal() == 2)
+    {
+        // Send
+        CSendDialog dialogSend(this, dialogAddr.GetSelectedAddress());
+        dialogSend.ShowModal();
+    }
+}
+
+void CMainFrame::OnSetFocusAddress(wxFocusEvent& event)
+{
+    // Automatically select-all when entering window
+    event.Skip();
+    m_textCtrlAddress->SetSelection(-1, -1);
+    fOnSetFocusAddress = true;
+}
+
+void CMainFrame::OnMouseEventsAddress(wxMouseEvent& event)
+{
+    event.Skip();
+    if (fOnSetFocusAddress)
+        m_textCtrlAddress->SetSelection(-1, -1);
+    fOnSetFocusAddress = false;
+}
+
+void CMainFrame::OnButtonNew(wxCommandEvent& event)
+{
+    // Ask name
+    CGetTextFromUserDialog dialog(this,
+        _("New Receiving Address"),
+        _("You should use a new address for each payment you receive.\n\nLabel"),
+        "");
+    if (!dialog.ShowModal())
+        return;
+    string strName = dialog.GetValue();
+
+    // Generate new key
+    string strAddress = PubKeyToAddress(GetKeyFromKeyPool());
+
+    // Save
+    SetAddressBookName(strAddress, strName);
+    SetDefaultReceivingAddress(strAddress);
+}
+
+void CMainFrame::OnButtonCopy(wxCommandEvent& event)
+{
+    // Copy address box to clipboard
+    if (wxTheClipboard->Open())
+    {
+        wxTheClipboard->SetData(new wxTextDataObject(m_textCtrlAddress->GetValue()));
+        wxTheClipboard->Close();
+    }
+}
+
+void CMainFrame::OnListItemActivated(wxListEvent& event)
+{
+    uint256 hash((string)GetItemText(m_listCtrl, event.GetIndex(), 1));
+    CWalletTx wtx;
+    CRITICAL_BLOCK(cs_mapWallet)
+    {
+        map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
+        if (mi == mapWallet.end())
+        {
+            printf("CMainFrame::OnListItemActivated() : tx not found in mapWallet\n");
+            return;
+        }
+        wtx = (*mi).second;
+    }
+    CTxDetailsDialog dialog(this, wtx);
+    dialog.ShowModal();
+    //CTxDetailsDialog* pdialog = new CTxDetailsDialog(this, wtx);
+    //pdialog->Show();
+}
+
+
+
+
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CTxDetailsDialog
+//
+
+CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetailsDialogBase(parent)
+{
+    CRITICAL_BLOCK(cs_mapAddressBook)
+    {
+        string strHTML;
+        strHTML.reserve(4000);
+        strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>";
+
+        int64 nTime = wtx.GetTxTime();
+        int64 nCredit = wtx.GetCredit();
+        int64 nDebit = wtx.GetDebit();
+        int64 nNet = nCredit - nDebit;
+
+
+
+        strHTML += _("<b>Status:</b> ") + FormatTxStatus(wtx);
+        int nRequests = wtx.GetRequestCount();
+        if (nRequests != -1)
+        {
+            if (nRequests == 0)
+                strHTML += _(", has not been successfully broadcast yet");
+            else if (nRequests == 1)
+                strHTML += strprintf(_(", broadcast through %d node"), nRequests);
+            else
+                strHTML += strprintf(_(", broadcast through %d nodes"), nRequests);
+        }
+        strHTML += "<br>";
+
+        strHTML += _("<b>Date:</b> ") + (nTime ? DateTimeStr(nTime) : "") + "<br>";
+
+
+        //
+        // From
+        //
+        if (wtx.IsCoinBase())
+        {
+            strHTML += _("<b>Source:</b> Generated<br>");
+        }
+        else if (!wtx.mapValue["from"].empty())
+        {
+            // Online transaction
+            if (!wtx.mapValue["from"].empty())
+                strHTML += _("<b>From:</b> ") + HtmlEscape(wtx.mapValue["from"]) + "<br>";
+        }
+        else
+        {
+            // Offline transaction
+            if (nNet > 0)
+            {
+                // Credit
+                foreach(const CTxOut& txout, wtx.vout)
+                {
+                    if (txout.IsMine())
+                    {
+                        vector<unsigned char> vchPubKey;
+                        if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey))
+                        {
+                            string strAddress = PubKeyToAddress(vchPubKey);
+                            if (mapAddressBook.count(strAddress))
+                            {
+                                strHTML += string() + _("<b>From:</b> ") + _("unknown") + "<br>";
+                                strHTML += _("<b>To:</b> ");
+                                strHTML += HtmlEscape(strAddress);
+                                if (!mapAddressBook[strAddress].empty())
+                                    strHTML += _(" (yours, label: ") + mapAddressBook[strAddress] + ")";
+                                else
+                                    strHTML += _(" (yours)");
+                                strHTML += "<br>";
+                            }
+                        }
+                        break;
+                    }
+                }
+            }
+        }
+
+
+        //
+        // To
+        //
+        string strAddress;
+        if (!wtx.mapValue["to"].empty())
+        {
+            // Online transaction
+            strAddress = wtx.mapValue["to"];
+            strHTML += _("<b>To:</b> ");
+            if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())
+                strHTML += mapAddressBook[strAddress] + " ";
+            strHTML += HtmlEscape(strAddress) + "<br>";
+        }
+
+
+        //
+        // Amount
+        //
+        if (wtx.IsCoinBase() && nCredit == 0)
+        {
+            //
+            // Coinbase
+            //
+            int64 nUnmatured = 0;
+            foreach(const CTxOut& txout, wtx.vout)
+                nUnmatured += txout.GetCredit();
+            strHTML += _("<b>Credit:</b> ");
+            if (wtx.IsInMainChain())
+                strHTML += strprintf(_("(%s matures in %d more blocks)"), FormatMoney(nUnmatured).c_str(), wtx.GetBlocksToMaturity());
+            else
+                strHTML += _("(not accepted)");
+            strHTML += "<br>";
+        }
+        else if (nNet > 0)
+        {
+            //
+            // Credit
+            //
+            strHTML += _("<b>Credit:</b> ") + FormatMoney(nNet) + "<br>";
+        }
+        else
+        {
+            bool fAllFromMe = true;
+            foreach(const CTxIn& txin, wtx.vin)
+                fAllFromMe = fAllFromMe && txin.IsMine();
+
+            bool fAllToMe = true;
+            foreach(const CTxOut& txout, wtx.vout)
+                fAllToMe = fAllToMe && txout.IsMine();
+
+            if (fAllFromMe)
+            {
+                //
+                // Debit
+                //
+                foreach(const CTxOut& txout, wtx.vout)
+                {
+                    if (txout.IsMine())
+                        continue;
+
+                    if (wtx.mapValue["to"].empty())
+                    {
+                        // Offline transaction
+                        uint160 hash160;
+                        if (ExtractHash160(txout.scriptPubKey, hash160))
+                        {
+                            string strAddress = Hash160ToAddress(hash160);
+                            strHTML += _("<b>To:</b> ");
+                            if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())
+                                strHTML += mapAddressBook[strAddress] + " ";
+                            strHTML += strAddress;
+                            strHTML += "<br>";
+                        }
+                    }
+
+                    strHTML += _("<b>Debit:</b> ") + FormatMoney(-txout.nValue) + "<br>";
+                }
+
+                if (fAllToMe)
+                {
+                    // Payment to self
+                    int64 nChange = wtx.GetChange();
+                    int64 nValue = nCredit - nChange;
+                    strHTML += _("<b>Debit:</b> ") + FormatMoney(-nValue) + "<br>";
+                    strHTML += _("<b>Credit:</b> ") + FormatMoney(nValue) + "<br>";
+                }
+
+                int64 nTxFee = nDebit - wtx.GetValueOut();
+                if (nTxFee > 0)
+                    strHTML += _("<b>Transaction fee:</b> ") + FormatMoney(-nTxFee) + "<br>";
+            }
+            else
+            {
+                //
+                // Mixed debit transaction
+                //
+                foreach(const CTxIn& txin, wtx.vin)
+                    if (txin.IsMine())
+                        strHTML += _("<b>Debit:</b> ") + FormatMoney(-txin.GetDebit()) + "<br>";
+                foreach(const CTxOut& txout, wtx.vout)
+                    if (txout.IsMine())
+                        strHTML += _("<b>Credit:</b> ") + FormatMoney(txout.GetCredit()) + "<br>";
+            }
+        }
+
+        strHTML += _("<b>Net amount:</b> ") + FormatMoney(nNet, true) + "<br>";
+
+
+        //
+        // Message
+        //
+        if (!wtx.mapValue["message"].empty())
+            strHTML += string() + "<br><b>" + _("Message:") + "</b><br>" + HtmlEscape(wtx.mapValue["message"], true) + "<br>";
+        if (!wtx.mapValue["comment"].empty())
+            strHTML += string() + "<br><b>" + _("Comment:") + "</b><br>" + HtmlEscape(wtx.mapValue["comment"], true) + "<br>";
+
+        if (wtx.IsCoinBase())
+            strHTML += string() + "<br>" + _("Generated coins must wait 120 blocks before they can be spent.  When you generated this block, it was broadcast to the network to be added to the block chain.  If it fails to get into the chain, it will change to \"not accepted\" and not be spendable.  This may occasionally happen if another node generates a block within a few seconds of yours.") + "<br>";
+
+
+        //
+        // Debug view
+        //
+        if (fDebug)
+        {
+            strHTML += "<hr><br>debug print<br><br>";
+            foreach(const CTxIn& txin, wtx.vin)
+                if (txin.IsMine())
+                    strHTML += "<b>Debit:</b> " + FormatMoney(-txin.GetDebit()) + "<br>";
+            foreach(const CTxOut& txout, wtx.vout)
+                if (txout.IsMine())
+                    strHTML += "<b>Credit:</b> " + FormatMoney(txout.GetCredit()) + "<br>";
+
+            strHTML += "<br><b>Transaction:</b><br>";
+            strHTML += HtmlEscape(wtx.ToString(), true);
+
+            strHTML += "<br><b>Inputs:</b><br>";
+            CRITICAL_BLOCK(cs_mapWallet)
+            {
+                foreach(const CTxIn& txin, wtx.vin)
+                {
+                    COutPoint prevout = txin.prevout;
+                    map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
+                    if (mi != mapWallet.end())
+                    {
+                        const CWalletTx& prev = (*mi).second;
+                        if (prevout.n < prev.vout.size())
+                        {
+                            strHTML += HtmlEscape(prev.ToString(), true);
+                            strHTML += " &nbsp;&nbsp; " + FormatTxStatus(prev) + ", ";
+                            strHTML = strHTML + "IsMine=" + (prev.vout[prevout.n].IsMine() ? "true" : "false") + "<br>";
+                        }
+                    }
+                }
+            }
+        }
+
+
+
+        strHTML += "</font></html>";
+        string(strHTML.begin(), strHTML.end()).swap(strHTML);
+        m_htmlWin->SetPage(strHTML);
+        m_buttonOK->SetFocus();
+    }
+}
+
+void CTxDetailsDialog::OnButtonOK(wxCommandEvent& event)
+{
+    Close();
+    //Destroy();
+}
+
+
+
+
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// Startup folder
+//
+
+#ifdef __WXMSW__
+string StartupShortcutPath()
+{
+    return MyGetSpecialFolderPath(CSIDL_STARTUP, true) + "\\Bitcoin.lnk";
+}
+
+bool GetStartOnSystemStartup()
+{
+    return filesystem::exists(StartupShortcutPath().c_str());
+}
+
+void SetStartOnSystemStartup(bool fAutoStart)
+{
+    // If the shortcut exists already, remove it for updating
+    remove(StartupShortcutPath().c_str());
+
+    if (fAutoStart)
+    {
+        CoInitialize(NULL);
+
+        // Get a pointer to the IShellLink interface.
+        IShellLink* psl = NULL;
+        HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
+                                CLSCTX_INPROC_SERVER, IID_IShellLink,
+                                reinterpret_cast<void**>(&psl));
+
+        if (SUCCEEDED(hres))
+        {
+            // Get the current executable path
+            TCHAR pszExePath[MAX_PATH];
+            GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
+
+            // Set the path to the shortcut target
+            psl->SetPath(pszExePath);
+            PathRemoveFileSpec(pszExePath);
+            psl->SetWorkingDirectory(pszExePath);
+            psl->SetShowCmd(SW_SHOWMINNOACTIVE);
+
+            // Query IShellLink for the IPersistFile interface for
+            // saving the shortcut in persistent storage.
+            IPersistFile* ppf = NULL;
+            hres = psl->QueryInterface(IID_IPersistFile,
+                                       reinterpret_cast<void**>(&ppf));
+            if (SUCCEEDED(hres))
+            {
+                WCHAR pwsz[MAX_PATH];
+                // Ensure that the string is ANSI.
+                MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().c_str(), -1, pwsz, MAX_PATH);
+                // Save the link by calling IPersistFile::Save.
+                hres = ppf->Save(pwsz, TRUE);
+                ppf->Release();
+            }
+            psl->Release();
+        }
+        CoUninitialize();
+    }
+}
+
+#elif defined(__WXGTK__)
+
+// Follow the Desktop Application Autostart Spec:
+//  http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
+
+boost::filesystem::path GetAutostartDir()
+{
+    namespace fs = boost::filesystem;
+
+    char* pszConfigHome = getenv("XDG_CONFIG_HOME");
+    if (pszConfigHome) return fs::path(pszConfigHome) / fs::path("autostart");
+    char* pszHome = getenv("HOME");
+    if (pszHome) return fs::path(pszHome) / fs::path(".config/autostart");
+    return fs::path();
+}
+
+boost::filesystem::path GetAutostartFilePath()
+{
+    return GetAutostartDir() / boost::filesystem::path("bitcoin.desktop");
+}
+
+bool GetStartOnSystemStartup()
+{
+    boost::filesystem::ifstream optionFile(GetAutostartFilePath());
+    if (!optionFile.good())
+        return false;
+    // Scan through file for "Hidden=true":
+    string line;
+    while (!optionFile.eof())
+    {
+        getline(optionFile, line);
+        if (line.find("Hidden") != string::npos &&
+            line.find("true") != string::npos)
+            return false;
+    }
+    optionFile.close();
+
+    return true;
+}
+
+void SetStartOnSystemStartup(bool fAutoStart)
+{
+    if (!fAutoStart)
+    {
+        unlink(GetAutostartFilePath().native_file_string().c_str());
+    }
+    else
+    {
+        char pszExePath[MAX_PATH+1];
+        memset(pszExePath, 0, sizeof(pszExePath));
+        if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
+            return;
+
+        boost::filesystem::create_directories(GetAutostartDir());
+
+        boost::filesystem::ofstream optionFile(GetAutostartFilePath(), ios_base::out|ios_base::trunc);
+        if (!optionFile.good())
+        {
+            wxMessageBox(_("Cannot write autostart/bitcoin.desktop file"), "Bitcoin");
+            return;
+        }
+        // Write a bitcoin.desktop file to the autostart directory:
+        optionFile << "[Desktop Entry]\n";
+        optionFile << "Type=Application\n";
+        optionFile << "Name=Bitcoin\n";
+        optionFile << "Exec=" << pszExePath << "\n";
+        optionFile << "Terminal=false\n";
+        optionFile << "Hidden=false\n";
+        optionFile.close();
+    }
+}
+#else
+
+// TODO: OSX startup stuff; see:
+// http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
+
+bool GetStartOnSystemStartup() { return false; }
+void SetStartOnSystemStartup(bool fAutoStart) { }
+
+#endif
+
+
+
+
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// COptionsDialog
+//
+
+COptionsDialog::COptionsDialog(wxWindow* parent) : COptionsDialogBase(parent)
+{
+    // Set up list box of page choices
+    m_listBox->Append(_("Main"));
+    //m_listBox->Append(_("Test 2"));
+    m_listBox->SetSelection(0);
+    SelectPage(0);
+#ifndef __WXMSW__
+    SetSize(1.0 * GetSize().GetWidth(), 1.2 * GetSize().GetHeight());
+#endif
+#if defined(__WXGTK__) || defined(__WXMAC_OSX__)
+    m_checkBoxStartOnSystemStartup->SetLabel(_("&Start Bitcoin on window system startup"));
+    if (!GetBoolArg("-minimizetotray"))
+    {
+        // Minimize to tray is just too buggy on Linux
+        fMinimizeToTray = false;
+        m_checkBoxMinimizeToTray->SetValue(false);
+        m_checkBoxMinimizeToTray->Enable(false);
+        m_checkBoxMinimizeOnClose->SetLabel(_("&Minimize on close"));
+    }
+#endif
+#ifdef __WXMAC_OSX__
+    m_checkBoxStartOnSystemStartup->Enable(false); // not implemented yet
+#endif
+
+    // Init values
+    m_textCtrlTransactionFee->SetValue(FormatMoney(nTransactionFee));
+    m_checkBoxLimitProcessors->SetValue(fLimitProcessors);
+    m_spinCtrlLimitProcessors->Enable(fLimitProcessors);
+    m_spinCtrlLimitProcessors->SetValue(nLimitProcessors);
+    int nProcessors = wxThread::GetCPUCount();
+    if (nProcessors < 1)
+        nProcessors = 999;
+    m_spinCtrlLimitProcessors->SetRange(1, nProcessors);
+    m_checkBoxStartOnSystemStartup->SetValue(fTmpStartOnSystemStartup = GetStartOnSystemStartup());
+    m_checkBoxMinimizeToTray->SetValue(fMinimizeToTray);
+    m_checkBoxMinimizeOnClose->SetValue(fMinimizeOnClose);
+    m_checkBoxUseProxy->SetValue(fUseProxy);
+    m_textCtrlProxyIP->Enable(fUseProxy);
+    m_textCtrlProxyPort->Enable(fUseProxy);
+    m_staticTextProxyIP->Enable(fUseProxy);
+    m_staticTextProxyPort->Enable(fUseProxy);
+    m_textCtrlProxyIP->SetValue(addrProxy.ToStringIP());
+    m_textCtrlProxyPort->SetValue(addrProxy.ToStringPort());
+
+    m_buttonOK->SetFocus();
+}
+
+void COptionsDialog::SelectPage(int nPage)
+{
+    m_panelMain->Show(nPage == 0);
+    m_panelTest2->Show(nPage == 1);
+
+    m_scrolledWindow->Layout();
+    m_scrolledWindow->SetScrollbars(0, 0, 0, 0, 0, 0);
+}
+
+void COptionsDialog::OnListBox(wxCommandEvent& event)
+{
+    SelectPage(event.GetSelection());
+}
+
+void COptionsDialog::OnKillFocusTransactionFee(wxFocusEvent& event)
+{
+    event.Skip();
+    int64 nTmp = nTransactionFee;
+    ParseMoney(m_textCtrlTransactionFee->GetValue(), nTmp);
+    m_textCtrlTransactionFee->SetValue(FormatMoney(nTmp));
+}
+
+void COptionsDialog::OnCheckBoxLimitProcessors(wxCommandEvent& event)
+{
+    m_spinCtrlLimitProcessors->Enable(event.IsChecked());
+}
+
+void COptionsDialog::OnCheckBoxUseProxy(wxCommandEvent& event)
+{
+    m_textCtrlProxyIP->Enable(event.IsChecked());
+    m_textCtrlProxyPort->Enable(event.IsChecked());
+    m_staticTextProxyIP->Enable(event.IsChecked());
+    m_staticTextProxyPort->Enable(event.IsChecked());
+}
+
+CAddress COptionsDialog::GetProxyAddr()
+{
+    // Be careful about byte order, addr.ip and addr.port are big endian
+    CAddress addr(m_textCtrlProxyIP->GetValue() + ":" + m_textCtrlProxyPort->GetValue());
+    if (addr.ip == INADDR_NONE)
+        addr.ip = addrProxy.ip;
+    int nPort = atoi(m_textCtrlProxyPort->GetValue());
+    addr.port = htons(nPort);
+    if (nPort <= 0 || nPort > USHRT_MAX)
+        addr.port = addrProxy.port;
+    return addr;
+}
+
+void COptionsDialog::OnKillFocusProxy(wxFocusEvent& event)
+{
+    event.Skip();
+    m_textCtrlProxyIP->SetValue(GetProxyAddr().ToStringIP());
+    m_textCtrlProxyPort->SetValue(GetProxyAddr().ToStringPort());
+}
+
+
+void COptionsDialog::OnButtonOK(wxCommandEvent& event)
+{
+    OnButtonApply(event);
+    Close();
+}
+
+void COptionsDialog::OnButtonCancel(wxCommandEvent& event)
+{
+    Close();
+}
+
+void COptionsDialog::OnButtonApply(wxCommandEvent& event)
+{
+    CWalletDB walletdb;
+
+    int64 nPrevTransactionFee = nTransactionFee;
+    if (ParseMoney(m_textCtrlTransactionFee->GetValue(), nTransactionFee) && nTransactionFee != nPrevTransactionFee)
+        walletdb.WriteSetting("nTransactionFee", nTransactionFee);
+
+    int nPrevMaxProc = (fLimitProcessors ? nLimitProcessors : INT_MAX);
+    if (fLimitProcessors != m_checkBoxLimitProcessors->GetValue())
+    {
+        fLimitProcessors = m_checkBoxLimitProcessors->GetValue();
+        walletdb.WriteSetting("fLimitProcessors", fLimitProcessors);
+    }
+    if (nLimitProcessors != m_spinCtrlLimitProcessors->GetValue())
+    {
+        nLimitProcessors = m_spinCtrlLimitProcessors->GetValue();
+        walletdb.WriteSetting("nLimitProcessors", nLimitProcessors);
+    }
+    if (fGenerateBitcoins && (fLimitProcessors ? nLimitProcessors : INT_MAX) > nPrevMaxProc)
+        GenerateBitcoins(fGenerateBitcoins);
+
+    if (fTmpStartOnSystemStartup != m_checkBoxStartOnSystemStartup->GetValue())
+    {
+        fTmpStartOnSystemStartup = m_checkBoxStartOnSystemStartup->GetValue();
+        SetStartOnSystemStartup(fTmpStartOnSystemStartup);
+    }
+
+    if (fMinimizeToTray != m_checkBoxMinimizeToTray->GetValue())
+    {
+        fMinimizeToTray = m_checkBoxMinimizeToTray->GetValue();
+        walletdb.WriteSetting("fMinimizeToTray", fMinimizeToTray);
+        ptaskbaricon->Show(fMinimizeToTray || fClosedToTray);
+    }
+
+    if (fMinimizeOnClose != m_checkBoxMinimizeOnClose->GetValue())
+    {
+        fMinimizeOnClose = m_checkBoxMinimizeOnClose->GetValue();
+        walletdb.WriteSetting("fMinimizeOnClose", fMinimizeOnClose);
+    }
+
+    fUseProxy = m_checkBoxUseProxy->GetValue();
+    walletdb.WriteSetting("fUseProxy", fUseProxy);
+
+    addrProxy = GetProxyAddr();
+    walletdb.WriteSetting("addrProxy", addrProxy);
+}
+
+
+
+
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CAboutDialog
+//
+
+CAboutDialog::CAboutDialog(wxWindow* parent) : CAboutDialogBase(parent)
+{
+    m_staticTextVersion->SetLabel(strprintf(_("version %s%s BETA"), FormatVersion(VERSION).c_str(), pszSubVer));
+
+    // Change (c) into UTF-8 or ANSI copyright symbol
+    wxString str = m_staticTextMain->GetLabel();
+#if wxUSE_UNICODE
+    str.Replace("(c)", wxString::FromUTF8("\xC2\xA9"));
+#else
+    str.Replace("(c)", "\xA9");
+#endif
+    m_staticTextMain->SetLabel(str);
+#ifndef __WXMSW__
+    // Resize on Linux to make the window fit the text.
+    // The text was wrapped manually rather than using the Wrap setting because
+    // the wrap would be too small on Linux and it can't be changed at this point.
+    wxFont fontTmp = m_staticTextMain->GetFont();
+    if (fontTmp.GetPointSize() > 8);
+        fontTmp.SetPointSize(8);
+    m_staticTextMain->SetFont(fontTmp);
+    SetSize(GetSize().GetWidth() + 44, GetSize().GetHeight() + 10);
+#endif
+}
+
+void CAboutDialog::OnButtonOK(wxCommandEvent& event)
+{
+    Close();
+}
+
+
+
+
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CSendDialog
+//
+
+CSendDialog::CSendDialog(wxWindow* parent, const wxString& strAddress) : CSendDialogBase(parent)
+{
+    // Init
+    m_textCtrlAddress->SetValue(strAddress);
+    m_choiceTransferType->SetSelection(0);
+    m_bitmapCheckMark->Show(false);
+    fEnabledPrev = true;
+    m_textCtrlAddress->SetFocus();
+    //// todo: should add a display of your balance for convenience
+#ifndef __WXMSW__
+    wxFont fontTmp = m_staticTextInstructions->GetFont();
+    if (fontTmp.GetPointSize() > 9);
+        fontTmp.SetPointSize(9);
+    m_staticTextInstructions->SetFont(fontTmp);
+    SetSize(725, 380);
+#endif
+
+    // Set Icon
+    wxIcon iconSend;
+    iconSend.CopyFromBitmap(wxBitmap(send16noshadow_xpm));
+    SetIcon(iconSend);
+
+    wxCommandEvent event;
+    OnTextAddress(event);
+
+    // Fixup the tab order
+    m_buttonPaste->MoveAfterInTabOrder(m_buttonCancel);
+    m_buttonAddress->MoveAfterInTabOrder(m_buttonPaste);
+    this->Layout();
+}
+
+void CSendDialog::OnTextAddress(wxCommandEvent& event)
+{
+    // Check mark
+    event.Skip();
+    bool fBitcoinAddress = IsValidBitcoinAddress(m_textCtrlAddress->GetValue());
+    m_bitmapCheckMark->Show(fBitcoinAddress);
+
+    // Grey out message if bitcoin address
+    bool fEnable = !fBitcoinAddress;
+    m_staticTextFrom->Enable(fEnable);
+    m_textCtrlFrom->Enable(fEnable);
+    m_staticTextMessage->Enable(fEnable);
+    m_textCtrlMessage->Enable(fEnable);
+    m_textCtrlMessage->SetBackgroundColour(wxSystemSettings::GetColour(fEnable ? wxSYS_COLOUR_WINDOW : wxSYS_COLOUR_BTNFACE));
+    if (!fEnable && fEnabledPrev)
+    {
+        strFromSave    = m_textCtrlFrom->GetValue();
+        strMessageSave = m_textCtrlMessage->GetValue();
+        m_textCtrlFrom->SetValue(_("n/a"));
+        m_textCtrlMessage->SetValue(_("Can't include a message when sending to a Bitcoin address"));
+    }
+    else if (fEnable && !fEnabledPrev)
+    {
+        m_textCtrlFrom->SetValue(strFromSave);
+        m_textCtrlMessage->SetValue(strMessageSave);
+    }
+    fEnabledPrev = fEnable;
+}
+
+void CSendDialog::OnKillFocusAmount(wxFocusEvent& event)
+{
+    // Reformat the amount
+    event.Skip();
+    if (m_textCtrlAmount->GetValue().Trim().empty())
+        return;
+    int64 nTmp;
+    if (ParseMoney(m_textCtrlAmount->GetValue(), nTmp))
+        m_textCtrlAmount->SetValue(FormatMoney(nTmp));
+}
+
+void CSendDialog::OnButtonAddressBook(wxCommandEvent& event)
+{
+    // Open address book
+    CAddressBookDialog dialog(this, m_textCtrlAddress->GetValue(), CAddressBookDialog::SENDING, true);
+    if (dialog.ShowModal())
+        m_textCtrlAddress->SetValue(dialog.GetSelectedAddress());
+}
+
+void CSendDialog::OnButtonPaste(wxCommandEvent& event)
+{
+    // Copy clipboard to address box
+    if (wxTheClipboard->Open())
+    {
+        if (wxTheClipboard->IsSupported(wxDF_TEXT))
+        {
+            wxTextDataObject data;
+            wxTheClipboard->GetData(data);
+            m_textCtrlAddress->SetValue(data.GetText());
+        }
+        wxTheClipboard->Close();
+    }
+}
+
+void CSendDialog::OnButtonSend(wxCommandEvent& event)
+{
+    static CCriticalSection cs_sendlock;
+    TRY_CRITICAL_BLOCK(cs_sendlock)
+    {
+        CWalletTx wtx;
+        string strAddress = (string)m_textCtrlAddress->GetValue();
+
+        // Parse amount
+        int64 nValue = 0;
+        if (!ParseMoney(m_textCtrlAmount->GetValue(), nValue) || nValue <= 0)
+        {
+            wxMessageBox(_("Error in amount  "), _("Send Coins"));
+            return;
+        }
+        if (nValue > GetBalance())
+        {
+            wxMessageBox(_("Amount exceeds your balance  "), _("Send Coins"));
+            return;
+        }
+        if (nValue + nTransactionFee > GetBalance())
+        {
+            wxMessageBox(string(_("Total exceeds your balance when the ")) + FormatMoney(nTransactionFee) + _(" transaction fee is included  "), _("Send Coins"));
+            return;
+        }
+
+        // Parse bitcoin address
+        uint160 hash160;
+        bool fBitcoinAddress = AddressToHash160(strAddress, hash160);
+
+        if (fBitcoinAddress)
+        {
+            // Send to bitcoin address
+            CScript scriptPubKey;
+            scriptPubKey << OP_DUP << OP_HASH160 << hash160 << OP_EQUALVERIFY << OP_CHECKSIG;
+
+            string strError = SendMoney(scriptPubKey, nValue, wtx, true);
+            if (strError == "")
+                wxMessageBox(_("Payment sent  "), _("Sending..."));
+            else if (strError == "ABORTED")
+                return; // leave send dialog open
+            else
+            {
+                wxMessageBox(strError + "  ", _("Sending..."));
+                EndModal(false);
+            }
+        }
+        else
+        {
+            // Parse IP address
+            CAddress addr(strAddress);
+            if (!addr.IsValid())
+            {
+                wxMessageBox(_("Invalid address  "), _("Send Coins"));
+                return;
+            }
+
+            // Message
+            wtx.mapValue["to"] = strAddress;
+            wtx.mapValue["from"] = m_textCtrlFrom->GetValue();
+            wtx.mapValue["message"] = m_textCtrlMessage->GetValue();
+
+            // Send to IP address
+            CSendingDialog* pdialog = new CSendingDialog(this, addr, nValue, wtx);
+            if (!pdialog->ShowModal())
+                return;
+        }
+
+        CRITICAL_BLOCK(cs_mapAddressBook)
+            if (!mapAddressBook.count(strAddress))
+                SetAddressBookName(strAddress, "");
+
+        EndModal(true);
+    }
+}
+
+void CSendDialog::OnButtonCancel(wxCommandEvent& event)
+{
+    // Cancel
+    EndModal(false);
+}
+
+
+
+
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CSendingDialog
+//
+
+CSendingDialog::CSendingDialog(wxWindow* parent, const CAddress& addrIn, int64 nPriceIn, const CWalletTx& wtxIn) : CSendingDialogBase(NULL) // we have to give null so parent can't destroy us
+{
+    addr = addrIn;
+    nPrice = nPriceIn;
+    wtx = wtxIn;
+    start = wxDateTime::UNow();
+    memset(pszStatus, 0, sizeof(pszStatus));
+    fCanCancel = true;
+    fAbort = false;
+    fSuccess = false;
+    fUIDone = false;
+    fWorkDone = false;
+#ifndef __WXMSW__
+    SetSize(1.2 * GetSize().GetWidth(), 1.08 * GetSize().GetHeight());
+#endif
+
+    SetTitle(strprintf(_("Sending %s to %s"), FormatMoney(nPrice).c_str(), wtx.mapValue["to"].c_str()));
+    m_textCtrlStatus->SetValue("");
+
+    CreateThread(SendingDialogStartTransfer, this);
+}
+
+CSendingDialog::~CSendingDialog()
+{
+    printf("~CSendingDialog()\n");
+}
+
+void CSendingDialog::Close()
+{
+    // Last one out turn out the lights.
+    // fWorkDone signals that work side is done and UI thread should call destroy.
+    // fUIDone signals that UI window has closed and work thread should call destroy.
+    // This allows the window to disappear and end modality when cancelled
+    // without making the user wait for ConnectNode to return.  The dialog object
+    // hangs around in the background until the work thread exits.
+    if (IsModal())
+        EndModal(fSuccess);
+    else
+        Show(false);
+    if (fWorkDone)
+        Destroy();
+    else
+        fUIDone = true;
+}
+
+void CSendingDialog::OnClose(wxCloseEvent& event)
+{
+    if (!event.CanVeto() || fWorkDone || fAbort || !fCanCancel)
+    {
+        Close();
+    }
+    else
+    {
+        event.Veto();
+        wxCommandEvent cmdevent;
+        OnButtonCancel(cmdevent);
+    }
+}
+
+void CSendingDialog::OnButtonOK(wxCommandEvent& event)
+{
+    if (fWorkDone)
+        Close();
+}
+
+void CSendingDialog::OnButtonCancel(wxCommandEvent& event)
+{
+    if (fCanCancel)
+        fAbort = true;
+}
+
+void CSendingDialog::OnPaint(wxPaintEvent& event)
+{
+    event.Skip();
+    if (strlen(pszStatus) > 130)
+        m_textCtrlStatus->SetValue(string("\n") + pszStatus);
+    else
+        m_textCtrlStatus->SetValue(string("\n\n") + pszStatus);
+    m_staticTextSending->SetFocus();
+    if (!fCanCancel)
+        m_buttonCancel->Enable(false);
+    if (fWorkDone)
+    {
+        m_buttonOK->Enable(true);
+        m_buttonOK->SetFocus();
+        m_buttonCancel->Enable(false);
+    }
+    if (fAbort && fCanCancel && IsShown())
+    {
+        strcpy(pszStatus, _("CANCELLED"));
+        m_buttonOK->Enable(true);
+        m_buttonOK->SetFocus();
+        m_buttonCancel->Enable(false);
+        m_buttonCancel->SetLabel(_("Cancelled"));
+        Close();
+        wxMessageBox(_("Transfer cancelled  "), _("Sending..."), wxOK, this);
+    }
+}
+
+
+//
+// Everything from here on is not in the UI thread and must only communicate
+// with the rest of the dialog through variables and calling repaint.
+//
+
+void CSendingDialog::Repaint()
+{
+    Refresh();
+    wxPaintEvent event;
+    GetEventHandler()->AddPendingEvent(event);
+}
+
+bool CSendingDialog::Status()
+{
+    if (fUIDone)
+    {
+        Destroy();
+        return false;
+    }
+    if (fAbort && fCanCancel)
+    {
+        memset(pszStatus, 0, 10);
+        strcpy(pszStatus, _("CANCELLED"));
+        Repaint();
+        fWorkDone = true;
+        return false;
+    }
+    return true;
+}
+
+bool CSendingDialog::Status(const string& str)
+{
+    if (!Status())
+        return false;
+
+    // This can be read by the UI thread at any time,
+    // so copy in a way that can be read cleanly at all times.
+    memset(pszStatus, 0, min(str.size()+1, sizeof(pszStatus)));
+    strlcpy(pszStatus, str.c_str(), sizeof(pszStatus));
+
+    Repaint();
+    return true;
+}
+
+bool CSendingDialog::Error(const string& str)
+{
+    fCanCancel = false;
+    fWorkDone = true;
+    Status(string(_("Error: ")) + str);
+    return false;
+}
+
+void SendingDialogStartTransfer(void* parg)
+{
+    ((CSendingDialog*)parg)->StartTransfer();
+}
+
+void CSendingDialog::StartTransfer()
+{
+    // Make sure we have enough money
+    if (nPrice + nTransactionFee > GetBalance())
+    {
+        Error(_("Insufficient funds"));
+        return;
+    }
+
+    // We may have connected already for product details
+    if (!Status(_("Connecting...")))
+        return;
+    CNode* pnode = ConnectNode(addr, 15 * 60);
+    if (!pnode)
+    {
+        Error(_("Unable to connect"));
+        return;
+    }
+
+    // Send order to seller, with response going to OnReply2 via event handler
+    if (!Status(_("Requesting public key...")))
+        return;
+    pnode->PushRequest("checkorder", wtx, SendingDialogOnReply2, this);
+}
+
+void SendingDialogOnReply2(void* parg, CDataStream& vRecv)
+{
+    ((CSendingDialog*)parg)->OnReply2(vRecv);
+}
+
+void CSendingDialog::OnReply2(CDataStream& vRecv)
+{
+    if (!Status(_("Received public key...")))
+        return;
+
+    CScript scriptPubKey;
+    int nRet;
+    try
+    {
+        vRecv >> nRet;
+        if (nRet > 0)
+        {
+            string strMessage;
+            if (!vRecv.empty())
+                vRecv >> strMessage;
+            if (nRet == 2)
+                Error(_("Recipient is not accepting transactions sent by IP address"));
+            else
+                Error(_("Transfer was not accepted"));
+            //// todo: enlarge the window and enable a hidden white box to put seller's message
+            return;
+        }
+        vRecv >> scriptPubKey;
+    }
+    catch (...)
+    {
+        //// what do we want to do about this?
+        Error(_("Invalid response received"));
+        return;
+    }
+
+    // Pause to give the user a chance to cancel
+    while (wxDateTime::UNow() < start + wxTimeSpan(0, 0, 0, 2 * 1000))
+    {
+        Sleep(200);
+        if (!Status())
+            return;
+    }
+
+    CRITICAL_BLOCK(cs_main)
+    {
+        // Pay
+        if (!Status(_("Creating transaction...")))
+            return;
+        if (nPrice + nTransactionFee > GetBalance())
+        {
+            Error(_("Insufficient funds"));
+            return;
+        }
+        CReserveKey reservekey;
+        int64 nFeeRequired;
+        if (!CreateTransaction(scriptPubKey, nPrice, wtx, reservekey, nFeeRequired))
+        {
+            if (nPrice + nFeeRequired > GetBalance())
+                Error(strprintf(_("This is an oversized transaction that requires a transaction fee of %s"), FormatMoney(nFeeRequired).c_str()));
+            else
+                Error(_("Transaction creation failed"));
+            return;
+        }
+
+        // Transaction fee
+        if (!ThreadSafeAskFee(nFeeRequired, _("Sending..."), this))
+        {
+            Error(_("Transaction aborted"));
+            return;
+        }
+
+        // Make sure we're still connected
+        CNode* pnode = ConnectNode(addr, 2 * 60 * 60);
+        if (!pnode)
+        {
+            Error(_("Lost connection, transaction cancelled"));
+            return;
+        }
+
+        // Last chance to cancel
+        Sleep(50);
+        if (!Status())
+            return;
+        fCanCancel = false;
+        if (fAbort)
+        {
+            fCanCancel = true;
+            if (!Status())
+                return;
+            fCanCancel = false;
+        }
+        if (!Status(_("Sending payment...")))
+            return;
+
+        // Commit
+        if (!CommitTransaction(wtx, reservekey))
+        {
+            Error(_("The transaction was rejected.  This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."));
+            return;
+        }
+
+        // Send payment tx to seller, with response going to OnReply3 via event handler
+        CWalletTx wtxSend = wtx;
+        wtxSend.fFromMe = false;
+        pnode->PushRequest("submitorder", wtxSend, SendingDialogOnReply3, this);
+
+        Status(_("Waiting for confirmation..."));
+        MainFrameRepaint();
+    }
+}
+
+void SendingDialogOnReply3(void* parg, CDataStream& vRecv)
+{
+    ((CSendingDialog*)parg)->OnReply3(vRecv);
+}
+
+void CSendingDialog::OnReply3(CDataStream& vRecv)
+{
+    int nRet;
+    try
+    {
+        vRecv >> nRet;
+        if (nRet > 0)
+        {
+            Error(_("The payment was sent, but the recipient was unable to verify it.\n"
+                    "The transaction is recorded and will credit to the recipient,\n"
+                    "but the comment information will be blank."));
+            return;
+        }
+    }
+    catch (...)
+    {
+        //// what do we want to do about this?
+        Error(_("Payment was sent, but an invalid response was received"));
+        return;
+    }
+
+    fSuccess = true;
+    fWorkDone = true;
+    Status(_("Payment completed"));
+}
+
+
+
+
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CAddressBookDialog
+//
+
+CAddressBookDialog::CAddressBookDialog(wxWindow* parent, const wxString& strInitSelected, int nPageIn, bool fDuringSendIn) : CAddressBookDialogBase(parent)
+{
+    // Set initially selected page
+    wxNotebookEvent event;
+    event.SetSelection(nPageIn);
+    OnNotebookPageChanged(event);
+    m_notebook->ChangeSelection(nPageIn);
+
+    fDuringSend = fDuringSendIn;
+    if (!fDuringSend)
+        m_buttonCancel->Show(false);
+
+    // Set Icon
+    wxIcon iconAddressBook;
+    iconAddressBook.CopyFromBitmap(wxBitmap(addressbook16_xpm));
+    SetIcon(iconAddressBook);
+
+    // Init column headers
+    m_listCtrlSending->InsertColumn(0, _("Name"), wxLIST_FORMAT_LEFT, 200);
+    m_listCtrlSending->InsertColumn(1, _("Address"), wxLIST_FORMAT_LEFT, 350);
+    m_listCtrlSending->SetFocus();
+    m_listCtrlReceiving->InsertColumn(0, _("Label"), wxLIST_FORMAT_LEFT, 200);
+    m_listCtrlReceiving->InsertColumn(1, _("Bitcoin Address"), wxLIST_FORMAT_LEFT, 350);
+    m_listCtrlReceiving->SetFocus();
+
+    // Fill listctrl with address book data
+    CRITICAL_BLOCK(cs_mapKeys)
+    CRITICAL_BLOCK(cs_mapAddressBook)
+    {
+        string strDefaultReceiving = (string)pframeMain->m_textCtrlAddress->GetValue();
+        foreach(const PAIRTYPE(string, string)& item, mapAddressBook)
+        {
+            string strAddress = item.first;
+            string strName = item.second;
+            uint160 hash160;
+            bool fMine = (AddressToHash160(strAddress, hash160) && mapPubKeys.count(hash160));
+            wxListCtrl* plistCtrl = fMine ? m_listCtrlReceiving : m_listCtrlSending;
+            int nIndex = InsertLine(plistCtrl, strName, strAddress);
+            if (strAddress == (fMine ? strDefaultReceiving : string(strInitSelected)))
+                plistCtrl->SetItemState(nIndex, wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED, wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED);
+        }
+    }
+}
+
+wxString CAddressBookDialog::GetSelectedAddress()
+{
+    int nIndex = GetSelection(m_listCtrl);
+    if (nIndex == -1)
+        return "";
+    return GetItemText(m_listCtrl, nIndex, 1);
+}
+
+wxString CAddressBookDialog::GetSelectedSendingAddress()
+{
+    int nIndex = GetSelection(m_listCtrlSending);
+    if (nIndex == -1)
+        return "";
+    return GetItemText(m_listCtrlSending, nIndex, 1);
+}
+
+wxString CAddressBookDialog::GetSelectedReceivingAddress()
+{
+    int nIndex = GetSelection(m_listCtrlReceiving);
+    if (nIndex == -1)
+        return "";
+    return GetItemText(m_listCtrlReceiving, nIndex, 1);
+}
+
+void CAddressBookDialog::OnNotebookPageChanged(wxNotebookEvent& event)
+{
+    event.Skip();
+    nPage = event.GetSelection();
+    if (nPage == SENDING)
+        m_listCtrl = m_listCtrlSending;
+    else if (nPage == RECEIVING)
+        m_listCtrl = m_listCtrlReceiving;
+    m_buttonDelete->Show(nPage == SENDING);
+    m_buttonCopy->Show(nPage == RECEIVING);
+    this->Layout();
+    m_listCtrl->SetFocus();
+}
+
+void CAddressBookDialog::OnListEndLabelEdit(wxListEvent& event)
+{
+    // Update address book with edited name
+    event.Skip();
+    if (event.IsEditCancelled())
+        return;
+    string strAddress = (string)GetItemText(m_listCtrl, event.GetIndex(), 1);
+    SetAddressBookName(strAddress, string(event.GetText()));
+    pframeMain->RefreshListCtrl();
+}
+
+void CAddressBookDialog::OnListItemSelected(wxListEvent& event)
+{
+    event.Skip();
+    if (nPage == RECEIVING)
+        SetDefaultReceivingAddress((string)GetSelectedReceivingAddress());
+}
+
+void CAddressBookDialog::OnListItemActivated(wxListEvent& event)
+{
+    event.Skip();
+    if (fDuringSend)
+    {
+        // Doubleclick returns selection
+        EndModal(GetSelectedAddress() != "" ? 2 : 0);
+        return;
+    }
+
+    // Doubleclick edits item
+    wxCommandEvent event2;
+    OnButtonEdit(event2);
+}
+
+void CAddressBookDialog::OnButtonDelete(wxCommandEvent& event)
+{
+    if (nPage != SENDING)
+        return;
+    for (int nIndex = m_listCtrl->GetItemCount()-1; nIndex >= 0; nIndex--)
+    {
+        if (m_listCtrl->GetItemState(nIndex, wxLIST_STATE_SELECTED))
+        {
+            string strAddress = (string)GetItemText(m_listCtrl, nIndex, 1);
+            CWalletDB().EraseName(strAddress);
+            m_listCtrl->DeleteItem(nIndex);
+        }
+    }
+    pframeMain->RefreshListCtrl();
+}
+
+void CAddressBookDialog::OnButtonCopy(wxCommandEvent& event)
+{
+    // Copy address box to clipboard
+    if (wxTheClipboard->Open())
+    {
+        wxTheClipboard->SetData(new wxTextDataObject(GetSelectedAddress()));
+        wxTheClipboard->Close();
+    }
+}
+
+bool CAddressBookDialog::CheckIfMine(const string& strAddress, const string& strTitle)
+{
+    uint160 hash160;
+    bool fMine = (AddressToHash160(strAddress, hash160) && mapPubKeys.count(hash160));
+    if (fMine)
+        wxMessageBox(_("This is one of your own addresses for receiving payments and cannot be entered in the address book.  "), strTitle);
+    return fMine;
+}
+
+void CAddressBookDialog::OnButtonEdit(wxCommandEvent& event)
+{
+    int nIndex = GetSelection(m_listCtrl);
+    if (nIndex == -1)
+        return;
+    string strName = (string)m_listCtrl->GetItemText(nIndex);
+    string strAddress = (string)GetItemText(m_listCtrl, nIndex, 1);
+    string strAddressOrg = strAddress;
+
+    if (nPage == SENDING)
+    {
+        // Ask name and address
+        do
+        {
+            CGetTextFromUserDialog dialog(this, _("Edit Address"), _("Name"), strName, _("Address"), strAddress);
+            if (!dialog.ShowModal())
+                return;
+            strName = dialog.GetValue1();
+            strAddress = dialog.GetValue2();
+        }
+        while (CheckIfMine(strAddress, _("Edit Address")));
+
+    }
+    else if (nPage == RECEIVING)
+    {
+        // Ask name
+        CGetTextFromUserDialog dialog(this, _("Edit Address Label"), _("Label"), strName);
+        if (!dialog.ShowModal())
+            return;
+        strName = dialog.GetValue();
+    }
+
+    // Write back
+    if (strAddress != strAddressOrg)
+        CWalletDB().EraseName(strAddressOrg);
+    SetAddressBookName(strAddress, strName);
+    m_listCtrl->SetItem(nIndex, 1, strAddress);
+    m_listCtrl->SetItemText(nIndex, strName);
+    pframeMain->RefreshListCtrl();
+}
+
+void CAddressBookDialog::OnButtonNew(wxCommandEvent& event)
+{
+    string strName;
+    string strAddress;
+
+    if (nPage == SENDING)
+    {
+        // Ask name and address
+        do
+        {
+            CGetTextFromUserDialog dialog(this, _("Add Address"), _("Name"), strName, _("Address"), strAddress);
+            if (!dialog.ShowModal())
+                return;
+            strName = dialog.GetValue1();
+            strAddress = dialog.GetValue2();
+        }
+        while (CheckIfMine(strAddress, _("Add Address")));
+    }
+    else if (nPage == RECEIVING)
+    {
+        // Ask name
+        CGetTextFromUserDialog dialog(this,
+            _("New Receiving Address"),
+            _("You should use a new address for each payment you receive.\n\nLabel"),
+            "");
+        if (!dialog.ShowModal())
+            return;
+        strName = dialog.GetValue();
+
+        // Generate new key
+        strAddress = PubKeyToAddress(GetKeyFromKeyPool());
+    }
+
+    // Add to list and select it
+    SetAddressBookName(strAddress, strName);
+    int nIndex = InsertLine(m_listCtrl, strName, strAddress);
+    SetSelection(m_listCtrl, nIndex);
+    m_listCtrl->SetFocus();
+    if (nPage == SENDING)
+        pframeMain->RefreshListCtrl();
+}
+
+void CAddressBookDialog::OnButtonOK(wxCommandEvent& event)
+{
+    // OK
+    EndModal(GetSelectedAddress() != "" ? 1 : 0);
+}
+
+void CAddressBookDialog::OnButtonCancel(wxCommandEvent& event)
+{
+    // Cancel
+    EndModal(0);
+}
+
+void CAddressBookDialog::OnClose(wxCloseEvent& event)
+{
+    // Close
+    EndModal(0);
+}
+
+
+
+
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CMyTaskBarIcon
+//
+
+enum
+{
+    ID_TASKBAR_RESTORE = 10001,
+    ID_TASKBAR_OPTIONS,
+    ID_TASKBAR_GENERATE,
+    ID_TASKBAR_EXIT,
+};
+
+BEGIN_EVENT_TABLE(CMyTaskBarIcon, wxTaskBarIcon)
+    EVT_TASKBAR_LEFT_DCLICK(CMyTaskBarIcon::OnLeftButtonDClick)
+    EVT_MENU(ID_TASKBAR_RESTORE, CMyTaskBarIcon::OnMenuRestore)
+    EVT_MENU(ID_TASKBAR_OPTIONS, CMyTaskBarIcon::OnMenuOptions)
+    EVT_MENU(ID_TASKBAR_GENERATE, CMyTaskBarIcon::OnMenuGenerate)
+    EVT_UPDATE_UI(ID_TASKBAR_GENERATE, CMyTaskBarIcon::OnUpdateUIGenerate)
+    EVT_MENU(ID_TASKBAR_EXIT, CMyTaskBarIcon::OnMenuExit)
+END_EVENT_TABLE()
+
+void CMyTaskBarIcon::Show(bool fShow)
+{
+    static char pszPrevTip[200];
+    if (fShow)
+    {
+        string strTooltip = _("Bitcoin");
+        if (fGenerateBitcoins)
+            strTooltip = _("Bitcoin - Generating");
+        if (fGenerateBitcoins && vNodes.empty())
+            strTooltip = _("Bitcoin - (not connected)");
+
+        // Optimization, only update when changed, using char array to be reentrant
+        if (strncmp(pszPrevTip, strTooltip.c_str(), sizeof(pszPrevTip)-1) != 0)
+        {
+            strlcpy(pszPrevTip, strTooltip.c_str(), sizeof(pszPrevTip));
+#ifdef __WXMSW__
+            // somehow it'll choose the wrong size and scale it down if
+            // we use the main icon, so we hand it one with only 16x16
+            SetIcon(wxICON(favicon), strTooltip);
+#else
+            SetIcon(bitcoin80_xpm, strTooltip);
+#endif
+        }
+    }
+    else
+    {
+        strlcpy(pszPrevTip, "", sizeof(pszPrevTip));
+        RemoveIcon();
+    }
+}
+
+void CMyTaskBarIcon::Hide()
+{
+    Show(false);
+}
+
+void CMyTaskBarIcon::OnLeftButtonDClick(wxTaskBarIconEvent& event)
+{
+    Restore();
+}
+
+void CMyTaskBarIcon::OnMenuRestore(wxCommandEvent& event)
+{
+    Restore();
+}
+
+void CMyTaskBarIcon::OnMenuOptions(wxCommandEvent& event)
+{
+    // Since it's modal, get the main window to do it
+    wxCommandEvent event2(wxEVT_COMMAND_MENU_SELECTED, wxID_PREFERENCES);
+    pframeMain->GetEventHandler()->AddPendingEvent(event2);
+}
+
+void CMyTaskBarIcon::Restore()
+{
+    pframeMain->Show();
+    wxIconizeEvent event(0, false);
+    pframeMain->GetEventHandler()->AddPendingEvent(event);
+    pframeMain->Iconize(false);
+    pframeMain->Raise();
+}
+
+void CMyTaskBarIcon::OnMenuGenerate(wxCommandEvent& event)
+{
+    GenerateBitcoins(event.IsChecked());
+}
+
+void CMyTaskBarIcon::OnUpdateUIGenerate(wxUpdateUIEvent& event)
+{
+    event.Check(fGenerateBitcoins);
+}
+
+void CMyTaskBarIcon::OnMenuExit(wxCommandEvent& event)
+{
+    pframeMain->Close(true);
+}
+
+void CMyTaskBarIcon::UpdateTooltip()
+{
+    if (IsIconInstalled())
+        Show(true);
+}
+
+wxMenu* CMyTaskBarIcon::CreatePopupMenu()
+{
+    wxMenu* pmenu = new wxMenu;
+    pmenu->Append(ID_TASKBAR_RESTORE, _("&Open Bitcoin"));
+    pmenu->Append(ID_TASKBAR_OPTIONS, _("O&ptions..."));
+    pmenu->AppendCheckItem(ID_TASKBAR_GENERATE, _("&Generate Coins"))->Check(fGenerateBitcoins);
+#ifndef __WXMAC_OSX__ // Mac has built-in quit menu
+    pmenu->AppendSeparator();
+    pmenu->Append(ID_TASKBAR_EXIT, _("E&xit"));
+#endif
+    return pmenu;
+}
+
+
+
+
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CMyApp
+//
+
+void CreateMainWindow()
+{
+    pframeMain = new CMainFrame(NULL);
+    if (GetBoolArg("-min"))
+        pframeMain->Iconize(true);
+#if defined(__WXGTK__) || defined(__WXMAC_OSX__)
+    if (!GetBoolArg("-minimizetotray"))
+        fMinimizeToTray = false;
+#endif
+    pframeMain->Show(true);  // have to show first to get taskbar button to hide
+    if (fMinimizeToTray && pframeMain->IsIconized())
+        fClosedToTray = true;
+    pframeMain->Show(!fClosedToTray);
+    ptaskbaricon->Show(fMinimizeToTray || fClosedToTray);
+    CreateThread(ThreadDelayedRepaint, NULL);
+}
+
+
+// Define a new application
+class CMyApp : public wxApp
+{
+public:
+    CMyApp(){};
+    ~CMyApp(){};
+    bool OnInit();
+    bool OnInit2();
+    int OnExit();
+
+    // Hook Initialize so we can start without GUI
+    virtual bool Initialize(int& argc, wxChar** argv);
+
+    // 2nd-level exception handling: we get all the exceptions occurring in any
+    // event handler here
+    virtual bool OnExceptionInMainLoop();
+
+    // 3rd, and final, level exception handling: whenever an unhandled
+    // exception is caught, this function is called
+    virtual void OnUnhandledException();
+
+    // and now for something different: this function is called in case of a
+    // crash (e.g. dereferencing null pointer, division by 0, ...)
+    virtual void OnFatalException();
+};
+
+IMPLEMENT_APP(CMyApp)
+
+bool CMyApp::Initialize(int& argc, wxChar** argv)
+{
+    for (int i = 1; i < argc; i++)
+        if (!IsSwitchChar(argv[i][0]))
+            fCommandLine = true;
+
+    if (!fCommandLine)
+    {
+        // wxApp::Initialize will remove environment-specific parameters,
+        // so it's too early to call ParseParameters yet
+        for (int i = 1; i < argc; i++)
+        {
+            wxString str = argv[i];
+            #ifdef __WXMSW__
+            if (str.size() >= 1 && str[0] == '/')
+                str[0] = '-';
+            char pszLower[MAX_PATH];
+            strlcpy(pszLower, str.c_str(), sizeof(pszLower));
+            strlwr(pszLower);
+            str = pszLower;
+            #endif
+            if (str == "-daemon")
+                fDaemon = true;
+        }
+    }
+
+#ifdef __WXGTK__
+    if (fDaemon || fCommandLine)
+    {
+        // Call the original Initialize while suppressing error messages
+        // and ignoring failure.  If unable to initialize GTK, it fails
+        // near the end so hopefully the last few things don't matter.
+        {
+            wxLogNull logNo;
+            wxApp::Initialize(argc, argv);
+        }
+
+        if (fDaemon)
+        {
+            // Daemonize
+            pid_t pid = fork();
+            if (pid < 0)
+            {
+                fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
+                return false;
+            }
+            if (pid > 0)
+                pthread_exit((void*)0);
+        }
+
+        return true;
+    }
+#endif
+
+    return wxApp::Initialize(argc, argv);
+}
+
+bool CMyApp::OnInit()
+{
+#if defined(__WXMSW__) && defined(__WXDEBUG__) && defined(GUI)
+    // Disable malfunctioning wxWidgets debug assertion
+    extern int g_isPainting;
+    g_isPainting = 10000;
+#endif
+#ifdef GUI
+    wxImage::AddHandler(new wxPNGHandler);
+#endif
+#if defined(__WXMSW__ ) || defined(__WXMAC_OSX__)
+    SetAppName("Bitcoin");
+#else
+    SetAppName("bitcoin");
+#endif
+#ifdef __WXMSW__
+#if wxUSE_UNICODE
+    // Hack to set wxConvLibc codepage to UTF-8 on Windows,
+    // may break if wxMBConv_win32 implementation in strconv.cpp changes.
+    class wxMBConv_win32 : public wxMBConv
+    {
+    public:
+        long m_CodePage;
+        size_t m_minMBCharWidth;
+    };
+    if (((wxMBConv_win32*)&wxConvLibc)->m_CodePage == CP_ACP)
+        ((wxMBConv_win32*)&wxConvLibc)->m_CodePage = CP_UTF8;
+#endif
+#endif
+
+    // Load locale/<lang>/LC_MESSAGES/bitcoin.mo language file
+    g_locale.Init(wxLANGUAGE_DEFAULT, 0);
+    g_locale.AddCatalogLookupPathPrefix("locale");
+#ifndef __WXMSW__
+    g_locale.AddCatalogLookupPathPrefix("/usr/share/locale");
+    g_locale.AddCatalogLookupPathPrefix("/usr/local/share/locale");
+#endif
+    g_locale.AddCatalog("wxstd"); // wxWidgets standard translations, if any
+    g_locale.AddCatalog("bitcoin");
+
+    return AppInit(argc, argv);
+}
+
+int CMyApp::OnExit()
+{
+    Shutdown(NULL);
+    return wxApp::OnExit();
+}
+
+bool CMyApp::OnExceptionInMainLoop()
+{
+    try
+    {
+        throw;
+    }
+    catch (std::exception& e)
+    {
+        PrintException(&e, "CMyApp::OnExceptionInMainLoop()");
+        wxLogWarning("Exception %s %s", typeid(e).name(), e.what());
+        Sleep(1000);
+        throw;
+    }
+    catch (...)
+    {
+        PrintException(NULL, "CMyApp::OnExceptionInMainLoop()");
+        wxLogWarning("Unknown exception");
+        Sleep(1000);
+        throw;
+    }
+    return true;
+}
+
+void CMyApp::OnUnhandledException()
+{
+    // this shows how we may let some exception propagate uncaught
+    try
+    {
+        throw;
+    }
+    catch (std::exception& e)
+    {
+        PrintException(&e, "CMyApp::OnUnhandledException()");
+        wxLogWarning("Exception %s %s", typeid(e).name(), e.what());
+        Sleep(1000);
+        throw;
+    }
+    catch (...)
+    {
+        PrintException(NULL, "CMyApp::OnUnhandledException()");
+        wxLogWarning("Unknown exception");
+        Sleep(1000);
+        throw;
+    }
+}
+
+void CMyApp::OnFatalException()
+{
+    wxMessageBox(_("Program has crashed and will terminate.  "), "Bitcoin", wxOK | wxICON_ERROR);
+}