Research
Timechain
Search Donate
Sponsors
Cake Wallet, private Bitcoin and Monero walletSideShift.ai, no-signup crypto exchangeOrangeRock, non-custodial bitcoin spot and perps tradingBraiins Hashpower, buy and sell Bitcoin hashrateeCash.com
Bitcoin v0.3.0 · 2010-07-06

ui.cpp

2,543 lines · plain text · GitHub · MIT license (license.txt)
1// Copyright (c) 2009-2010 Satoshi Nakamoto2// Distributed under the MIT/X11 software license, see the accompanying3// file license.txt or http://www.opensource.org/licenses/mit-license.php.45#include "headers.h"6#ifdef _MSC_VER7#include <crtdbg.h>8#endif9101112DEFINE_EVENT_TYPE(wxEVT_UITHREADCALL)1314CMainFrame* pframeMain = NULL;15CMyTaskBarIcon* ptaskbaricon = NULL;16bool fClosedToTray = false;17181920212223242526//////////////////////////////////////////////////////////////////////////////27//28// Util29//3031void HandleCtrlA(wxKeyEvent& event)32{33    // Ctrl-a select all34    event.Skip();35    wxTextCtrl* textCtrl = (wxTextCtrl*)event.GetEventObject();36    if (event.GetModifiers() == wxMOD_CONTROL && event.GetKeyCode() == 'A')37        textCtrl->SetSelection(-1, -1);38}3940bool Is24HourTime()41{42    //char pszHourFormat[256];43    //pszHourFormat[0] = '\0';44    //GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_ITIME, pszHourFormat, 256);45    //return (pszHourFormat[0] != '0');46    return true;47}4849string DateStr(int64 nTime)50{51    // Can only be used safely here in the UI52    return (string)wxDateTime((time_t)nTime).FormatDate();53}5455string DateTimeStr(int64 nTime)56{57    // Can only be used safely here in the UI58    wxDateTime datetime((time_t)nTime);59    if (Is24HourTime())60        return (string)datetime.Format("%x %H:%M");61    else62        return (string)datetime.Format("%x ") + itostr((datetime.GetHour() + 11) % 12 + 1) + (string)datetime.Format(":%M %p");63}6465wxString GetItemText(wxListCtrl* listCtrl, int nIndex, int nColumn)66{67    // Helper to simplify access to listctrl68    wxListItem item;69    item.m_itemId = nIndex;70    item.m_col = nColumn;71    item.m_mask = wxLIST_MASK_TEXT;72    if (!listCtrl->GetItem(item))73        return "";74    return item.GetText();75}7677int InsertLine(wxListCtrl* listCtrl, const wxString& str0, const wxString& str1)78{79    int nIndex = listCtrl->InsertItem(listCtrl->GetItemCount(), str0);80    listCtrl->SetItem(nIndex, 1, str1);81    return nIndex;82}8384int InsertLine(wxListCtrl* listCtrl, const wxString& str0, const wxString& str1, const wxString& str2, const wxString& str3, const wxString& str4)85{86    int nIndex = listCtrl->InsertItem(listCtrl->GetItemCount(), str0);87    listCtrl->SetItem(nIndex, 1, str1);88    listCtrl->SetItem(nIndex, 2, str2);89    listCtrl->SetItem(nIndex, 3, str3);90    listCtrl->SetItem(nIndex, 4, str4);91    return nIndex;92}9394int InsertLine(wxListCtrl* listCtrl, void* pdata, const wxString& str0, const wxString& str1, const wxString& str2, const wxString& str3, const wxString& str4)95{96    int nIndex = listCtrl->InsertItem(listCtrl->GetItemCount(), str0);97    listCtrl->SetItemPtrData(nIndex, (wxUIntPtr)pdata);98    listCtrl->SetItem(nIndex, 1, str1);99    listCtrl->SetItem(nIndex, 2, str2);100    listCtrl->SetItem(nIndex, 3, str3);101    listCtrl->SetItem(nIndex, 4, str4);102    return nIndex;103}104105void SetSelection(wxListCtrl* listCtrl, int nIndex)106{107    int nSize = listCtrl->GetItemCount();108    long nState = (wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED);109    for (int i = 0; i < nSize; i++)110        listCtrl->SetItemState(i, (i == nIndex ? nState : 0), nState);111}112113int GetSelection(wxListCtrl* listCtrl)114{115    int nSize = listCtrl->GetItemCount();116    for (int i = 0; i < nSize; i++)117        if (listCtrl->GetItemState(i, wxLIST_STATE_FOCUSED))118            return i;119    return -1;120}121122string HtmlEscape(const char* psz, bool fMultiLine=false)123{124    int len = 0;125    for (const char* p = psz; *p; p++)126    {127             if (*p == '<') len += 4;128        else if (*p == '>') len += 4;129        else if (*p == '&') len += 5;130        else if (*p == '"') len += 6;131        else if (*p == ' ' && p > psz && p[-1] == ' ' && p[1] == ' ') len += 6;132        else if (*p == '\n' && fMultiLine) len += 5;133        else134            len++;135    }136    string str;137    str.reserve(len);138    for (const char* p = psz; *p; p++)139    {140             if (*p == '<') str += "&lt;";141        else if (*p == '>') str += "&gt;";142        else if (*p == '&') str += "&amp;";143        else if (*p == '"') str += "&quot;";144        else if (*p == ' ' && p > psz && p[-1] == ' ' && p[1] == ' ') str += "&nbsp;";145        else if (*p == '\n' && fMultiLine) str += "<br>\n";146        else147            str += *p;148    }149    return str;150}151152string HtmlEscape(const string& str, bool fMultiLine=false)153{154    return HtmlEscape(str.c_str(), fMultiLine);155}156157void CalledMessageBox(const string& message, const string& caption, int style, wxWindow* parent, int x, int y, int* pnRet, bool* pfDone)158{159    *pnRet = wxMessageBox(message, caption, style, parent, x, y);160    *pfDone = true;161}162163int ThreadSafeMessageBox(const string& message, const string& caption, int style, wxWindow* parent, int x, int y)164{165#ifdef __WXMSW__166    return wxMessageBox(message, caption, style, parent, x, y);167#else168    if (wxThread::IsMain() || fDaemon)169    {170        return wxMessageBox(message, caption, style, parent, x, y);171    }172    else173    {174        int nRet = 0;175        bool fDone = false;176        UIThreadCall(bind(CalledMessageBox, message, caption, style, parent, x, y, &nRet, &fDone));177        while (!fDone)178            Sleep(100);179        return nRet;180    }181#endif182}183184bool ThreadSafeAskFee(int64 nFeeRequired, const string& strCaption, wxWindow* parent)185{186    if (nFeeRequired == 0 || fDaemon)187        return true;188    string strMessage = strprintf(189        _("This transaction is over the size limit.  You can still send it for a fee of %s, "190          "which goes to the nodes that process your transaction and helps to support the network.  "191          "Do you want to pay the fee?"),192        FormatMoney(nFeeRequired).c_str());193    return (ThreadSafeMessageBox(strMessage, strCaption, wxYES_NO, parent) == wxYES);194}195196void CalledSetStatusBar(const string& strText, int nField)197{198    if (pframeMain && pframeMain->m_statusBar)199        pframeMain->m_statusBar->SetStatusText(strText, nField);200}201202void SetDefaultReceivingAddress(const string& strAddress)203{204    // Update main window address and database205    if (pframeMain == NULL)206        return;207    if (strAddress != pframeMain->m_textCtrlAddress->GetValue())208    {209        uint160 hash160;210        if (!AddressToHash160(strAddress, hash160))211            return;212        if (!mapPubKeys.count(hash160))213            return;214        CWalletDB().WriteDefaultKey(mapPubKeys[hash160]);215        pframeMain->m_textCtrlAddress->SetValue(strAddress);216    }217}218219220221222223224225226227228//////////////////////////////////////////////////////////////////////////////229//230// CMainFrame231//232233CMainFrame::CMainFrame(wxWindow* parent) : CMainFrameBase(parent)234{235    Connect(wxEVT_UITHREADCALL, wxCommandEventHandler(CMainFrame::OnUIThreadCall), NULL, this);236237    // Set initially selected page238    wxNotebookEvent event;239    event.SetSelection(0);240    OnNotebookPageChanged(event);241    m_notebook->ChangeSelection(0);242243    // Init244    fRefreshListCtrl = false;245    fRefreshListCtrlRunning = false;246    fOnSetFocusAddress = false;247    fRefresh = false;248    m_choiceFilter->SetSelection(0);249    double dResize = 1.0;250#ifdef __WXMSW__251    SetIcon(wxICON(bitcoin));252#else253    SetIcon(bitcoin80_xpm);254    SetBackgroundColour(m_toolBar->GetBackgroundColour());255    wxFont fontTmp = m_staticText41->GetFont();256    fontTmp.SetFamily(wxFONTFAMILY_TELETYPE);257    m_staticTextBalance->SetFont(fontTmp);258    m_staticTextBalance->SetSize(140, 17);259    // resize to fit ubuntu's huge default font260    dResize = 1.22;261    SetSize(dResize * GetSize().GetWidth(), 1.15 * GetSize().GetHeight());262#endif263    m_staticTextBalance->SetLabel(FormatMoney(GetBalance()) + "  ");264    m_listCtrl->SetFocus();265    ptaskbaricon = new CMyTaskBarIcon();266#ifdef __WXMAC__267    // Mac automatically moves wxID_EXIT, wxID_PREFERENCES and wxID_ABOUT268    // to their standard places, leaving these menus empty.269    GetMenuBar()->Remove(2); // remove Help menu270    GetMenuBar()->Remove(0); // remove File menu271#endif272273    // Init column headers274    int nDateWidth = DateTimeStr(1229413914).size() * 6 + 8;275    if (!strstr(DateTimeStr(1229413914).c_str(), "2008"))276        nDateWidth += 12;277#ifdef __WXMAC__278    nDateWidth += 5;279    dResize -= 0.01;280#endif281    wxListCtrl* pplistCtrl[] = {m_listCtrlAll, m_listCtrlSentReceived, m_listCtrlSent, m_listCtrlReceived};282    foreach(wxListCtrl* p, pplistCtrl)283    {284        p->InsertColumn(0, "",               wxLIST_FORMAT_LEFT,  dResize * 0);285        p->InsertColumn(1, "",               wxLIST_FORMAT_LEFT,  dResize * 0);286        p->InsertColumn(2, _("Status"),      wxLIST_FORMAT_LEFT,  dResize * 112);287        p->InsertColumn(3, _("Date"),        wxLIST_FORMAT_LEFT,  dResize * nDateWidth);288        p->InsertColumn(4, _("Description"), wxLIST_FORMAT_LEFT,  dResize * 409 - nDateWidth);289        p->InsertColumn(5, _("Debit"),       wxLIST_FORMAT_RIGHT, dResize * 79);290        p->InsertColumn(6, _("Credit"),      wxLIST_FORMAT_RIGHT, dResize * 79);291    }292293    // Init status bar294    int pnWidths[3] = { -100, 88, 300 };295#ifndef __WXMSW__296    pnWidths[1] = pnWidths[1] * 1.1 * dResize;297    pnWidths[2] = pnWidths[2] * 1.1 * dResize;298#endif299    m_statusBar->SetFieldsCount(3, pnWidths);300301    // Fill your address text box302    vector<unsigned char> vchPubKey;303    if (CWalletDB("r").ReadDefaultKey(vchPubKey))304        m_textCtrlAddress->SetValue(PubKeyToAddress(vchPubKey));305306    // Fill listctrl with wallet transactions307    RefreshListCtrl();308}309310CMainFrame::~CMainFrame()311{312    pframeMain = NULL;313    delete ptaskbaricon;314    ptaskbaricon = NULL;315}316317void CMainFrame::OnNotebookPageChanged(wxNotebookEvent& event)318{319    event.Skip();320    nPage = event.GetSelection();321    if (nPage == ALL)322    {323        m_listCtrl = m_listCtrlAll;324        fShowGenerated = true;325        fShowSent = true;326        fShowReceived = true;327    }328    else if (nPage == SENTRECEIVED)329    {330        m_listCtrl = m_listCtrlSentReceived;331        fShowGenerated = false;332        fShowSent = true;333        fShowReceived = true;334    }335    else if (nPage == SENT)336    {337        m_listCtrl = m_listCtrlSent;338        fShowGenerated = false;339        fShowSent = true;340        fShowReceived = false;341    }342    else if (nPage == RECEIVED)343    {344        m_listCtrl = m_listCtrlReceived;345        fShowGenerated = false;346        fShowSent = false;347        fShowReceived = true;348    }349    RefreshListCtrl();350    m_listCtrl->SetFocus();351}352353void CMainFrame::OnClose(wxCloseEvent& event)354{355    if (fMinimizeOnClose && event.CanVeto() && !IsIconized())356    {357        // Divert close to minimize358        event.Veto();359        fClosedToTray = true;360        Iconize(true);361    }362    else363    {364        Destroy();365        CreateThread(Shutdown, NULL);366    }367}368369void CMainFrame::OnIconize(wxIconizeEvent& event)370{371    event.Skip();372    // Hide the task bar button when minimized.373    // Event is sent when the frame is minimized or restored.374    // wxWidgets 2.8.9 doesn't have IsIconized() so there's no way375    // to get rid of the deprecated warning.  Just ignore it.376    if (!event.Iconized())377        fClosedToTray = false;378//#ifdef __WXMSW__379    // The tray icon sometimes disappears on ubuntu karmic380    // Hiding the taskbar button doesn't work cleanly on ubuntu lucid381    if (fMinimizeToTray && event.Iconized())382        fClosedToTray = true;383    Show(!fClosedToTray);384//#endif385    ptaskbaricon->Show(fMinimizeToTray || fClosedToTray);386}387388void CMainFrame::OnMouseEvents(wxMouseEvent& event)389{390    event.Skip();391    RandAddSeed();392    RAND_add(&event.m_x, sizeof(event.m_x), 0.25);393    RAND_add(&event.m_y, sizeof(event.m_y), 0.25);394}395396void CMainFrame::OnListColBeginDrag(wxListEvent& event)397{398    // Hidden columns not resizeable399    if (event.GetColumn() <= 1 && !fDebug)400        event.Veto();401    else402        event.Skip();403}404405int CMainFrame::GetSortIndex(const string& strSort)406{407#ifdef __WXMSW__408    return 0;409#else410    // The wx generic listctrl implementation used on GTK doesn't sort,411    // so we have to do it ourselves.  Remember, we sort in reverse order.412    // In the wx generic implementation, they store the list of items413    // in a vector, so indexed lookups are fast, but inserts are slower414    // the closer they are to the top.415    int low = 0;416    int high = m_listCtrl->GetItemCount();417    while (low < high)418    {419        int mid = low + ((high - low) / 2);420        if (strSort.compare(m_listCtrl->GetItemText(mid).c_str()) >= 0)421            high = mid;422        else423            low = mid + 1;424    }425    return low;426#endif427}428429void 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)430{431    strSort = " " + strSort;       // leading space to workaround wx2.9.0 ubuntu 9.10 bug432    long nData = *(long*)&hashKey; //  where first char of hidden column is displayed433434    // Find item435    if (!fNew && nIndex == -1)436    {437        string strHash = " " + hashKey.ToString();438        while ((nIndex = m_listCtrl->FindItem(nIndex, nData)) != -1)439            if (GetItemText(m_listCtrl, nIndex, 1) == strHash)440                break;441    }442443    // fNew is for blind insert, only use if you're sure it's new444    if (fNew || nIndex == -1)445    {446        nIndex = m_listCtrl->InsertItem(GetSortIndex(strSort), strSort);447    }448    else449    {450        // If sort key changed, must delete and reinsert to make it relocate451        if (GetItemText(m_listCtrl, nIndex, 0) != strSort)452        {453            m_listCtrl->DeleteItem(nIndex);454            nIndex = m_listCtrl->InsertItem(GetSortIndex(strSort), strSort);455        }456    }457458    m_listCtrl->SetItem(nIndex, 1, " " + hashKey.ToString());459    m_listCtrl->SetItem(nIndex, 2, str2);460    m_listCtrl->SetItem(nIndex, 3, str3);461    m_listCtrl->SetItem(nIndex, 4, str4);462    m_listCtrl->SetItem(nIndex, 5, str5);463    m_listCtrl->SetItem(nIndex, 6, str6);464    m_listCtrl->SetItemData(nIndex, nData);465}466467bool CMainFrame::DeleteLine(uint256 hashKey)468{469    long nData = *(long*)&hashKey;470471    // Find item472    int nIndex = -1;473    string strHash = " " + hashKey.ToString();474    while ((nIndex = m_listCtrl->FindItem(nIndex, nData)) != -1)475        if (GetItemText(m_listCtrl, nIndex, 1) == strHash)476            break;477478    if (nIndex != -1)479        m_listCtrl->DeleteItem(nIndex);480481    return nIndex != -1;482}483484string FormatTxStatus(const CWalletTx& wtx)485{486    // Status487    if (!wtx.IsFinal())488    {489        if (wtx.nLockTime < 500000000)490            return strprintf(_("Open for %d blocks"), nBestHeight - wtx.nLockTime);491        else492            return strprintf(_("Open until %s"), DateTimeStr(wtx.nLockTime).c_str());493    }494    else495    {496        int nDepth = wtx.GetDepthInMainChain();497        if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)498            return strprintf(_("%d/offline?"), nDepth);499        else if (nDepth < 6)500            return strprintf(_("%d/unconfirmed"), nDepth);501        else502            return strprintf(_("%d confirmations"), nDepth);503    }504}505506string SingleLine(const string& strIn)507{508    string strOut;509    bool fOneSpace = false;510    foreach(int c, strIn)511    {512        if (isspace(c))513        {514            fOneSpace = true;515        }516        else if (c > ' ')517        {518            if (fOneSpace && !strOut.empty())519                strOut += ' ';520            strOut += c;521            fOneSpace = false;522        }523    }524    return strOut;525}526527bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex)528{529    int64 nTime = wtx.nTimeDisplayed = wtx.GetTxTime();530    int64 nCredit = wtx.GetCredit(true);531    int64 nDebit = wtx.GetDebit();532    int64 nNet = nCredit - nDebit;533    uint256 hash = wtx.GetHash();534    string strStatus = FormatTxStatus(wtx);535    map<string, string> mapValue = wtx.mapValue;536    wtx.nLinesDisplayed = 1;537    nListViewUpdated++;538539    // Filter540    if (wtx.IsCoinBase())541    {542        // Don't show generated coin until confirmed by at least one block after it543        // so we don't get the user's hopes up until it looks like it's probably accepted.544        //545        // It is not an error when generated blocks are not accepted.  By design,546        // some percentage of blocks, like 10% or more, will end up not accepted.547        // This is the normal mechanism by which the network copes with latency.548        //549        // We display regular transactions right away before any confirmation550        // because they can always get into some block eventually.  Generated coins551        // are special because if their block is not accepted, they are not valid.552        //553        if (wtx.GetDepthInMainChain() < 2)554        {555            wtx.nLinesDisplayed = 0;556            return false;557        }558559        if (!fShowGenerated)560            return false;561    }562563    // Find the block the tx is in564    CBlockIndex* pindex = NULL;565    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(wtx.hashBlock);566    if (mi != mapBlockIndex.end())567        pindex = (*mi).second;568569    // Sort order, unrecorded transactions sort to the top570    string strSort = strprintf("%010d-%01d-%010u",571        (pindex ? pindex->nHeight : INT_MAX),572        (wtx.IsCoinBase() ? 1 : 0),573        wtx.nTimeReceived);574575    // Insert line576    if (nNet > 0 || wtx.IsCoinBase())577    {578        //579        // Credit580        //581        string strDescription;582        if (wtx.IsCoinBase())583        {584            // Generated585            strDescription = _("Generated");586            if (nCredit == 0)587            {588                int64 nUnmatured = 0;589                foreach(const CTxOut& txout, wtx.vout)590                    nUnmatured += txout.GetCredit();591                if (wtx.IsInMainChain())592                {593                    strDescription = strprintf(_("Generated (%s matures in %d more blocks)"), FormatMoney(nUnmatured).c_str(), wtx.GetBlocksToMaturity());594595                    // Check if the block was requested by anyone596                    if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)597                        strDescription = _("Generated - Warning: This block was not received by any other nodes and will probably not be accepted!");598                }599                else600                {601                    strDescription = _("Generated (not accepted)");602                }603            }604        }605        else if (!mapValue["from"].empty() || !mapValue["message"].empty())606        {607            // Received by IP connection608            if (!fShowReceived)609                return false;610            if (!mapValue["from"].empty())611                strDescription += _("From: ") + mapValue["from"];612            if (!mapValue["message"].empty())613            {614                if (!strDescription.empty())615                    strDescription += " - ";616                strDescription += mapValue["message"];617            }618        }619        else620        {621            // Received by Bitcoin Address622            if (!fShowReceived)623                return false;624            foreach(const CTxOut& txout, wtx.vout)625            {626                if (txout.IsMine())627                {628                    vector<unsigned char> vchPubKey;629                    if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey))630                    {631                        CRITICAL_BLOCK(cs_mapAddressBook)632                        {633                            //strDescription += _("Received payment to ");634                            //strDescription += _("Received with address ");635                            strDescription += _("From: unknown, Received with: ");636                            string strAddress = PubKeyToAddress(vchPubKey);637                            map<string, string>::iterator mi = mapAddressBook.find(strAddress);638                            if (mi != mapAddressBook.end() && !(*mi).second.empty())639                            {640                                string strLabel = (*mi).second;641                                strDescription += strAddress.substr(0,12) + "... ";642                                strDescription += "(" + strLabel + ")";643                            }644                            else645                                strDescription += strAddress;646                        }647                    }648                    break;649                }650            }651        }652653        InsertLine(fNew, nIndex, hash, strSort,654                   strStatus,655                   nTime ? DateTimeStr(nTime) : "",656                   SingleLine(strDescription),657                   "",658                   FormatMoney(nNet, true));659    }660    else661    {662        bool fAllFromMe = true;663        foreach(const CTxIn& txin, wtx.vin)664            fAllFromMe = fAllFromMe && txin.IsMine();665666        bool fAllToMe = true;667        foreach(const CTxOut& txout, wtx.vout)668            fAllToMe = fAllToMe && txout.IsMine();669670        if (fAllFromMe && fAllToMe)671        {672            // Payment to self673            int64 nValue = wtx.vout[0].nValue;674            InsertLine(fNew, nIndex, hash, strSort,675                       strStatus,676                       nTime ? DateTimeStr(nTime) : "",677                       _("Payment to yourself"),678                       "",679                       "");680            /// issue: can't tell which is the payment and which is the change anymore681            //           FormatMoney(nNet - nValue, true),682            //           FormatMoney(nValue, true));683        }684        else if (fAllFromMe)685        {686            //687            // Debit688            //689            if (!fShowSent)690                return false;691692            int64 nTxFee = nDebit - wtx.GetValueOut();693            wtx.nLinesDisplayed = 0;694            for (int nOut = 0; nOut < wtx.vout.size(); nOut++)695            {696                const CTxOut& txout = wtx.vout[nOut];697                if (txout.IsMine())698                    continue;699700                string strAddress;701                if (!mapValue["to"].empty())702                {703                    // Sent to IP704                    strAddress = mapValue["to"];705                }706                else707                {708                    // Sent to Bitcoin Address709                    uint160 hash160;710                    if (ExtractHash160(txout.scriptPubKey, hash160))711                        strAddress = Hash160ToAddress(hash160);712                }713714                string strDescription = _("To: ");715                CRITICAL_BLOCK(cs_mapAddressBook)716                    if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())717                        strDescription += mapAddressBook[strAddress] + " ";718                strDescription += strAddress;719                if (!mapValue["message"].empty())720                {721                    if (!strDescription.empty())722                        strDescription += " - ";723                    strDescription += mapValue["message"];724                }725726                int64 nValue = txout.nValue;727                if (nTxFee > 0)728                {729                    nValue += nTxFee;730                    nTxFee = 0;731                }732733                InsertLine(fNew, nIndex, hash, strprintf("%s-%d", strSort.c_str(), nOut),734                           strStatus,735                           nTime ? DateTimeStr(nTime) : "",736                           SingleLine(strDescription),737                           FormatMoney(-nValue, true),738                           "");739                wtx.nLinesDisplayed++;740            }741        }742        else743        {744            //745            // Mixed debit transaction, can't break down payees746            //747            bool fAllMine = true;748            foreach(const CTxOut& txout, wtx.vout)749                fAllMine = fAllMine && txout.IsMine();750            foreach(const CTxIn& txin, wtx.vin)751                fAllMine = fAllMine && txin.IsMine();752753            InsertLine(fNew, nIndex, hash, strSort,754                       strStatus,755                       nTime ? DateTimeStr(nTime) : "",756                       "",757                       FormatMoney(nNet, true),758                       "");759        }760    }761762    return true;763}764765void CMainFrame::RefreshListCtrl()766{767    fRefreshListCtrl = true;768    ::wxWakeUpIdle();769}770771void CMainFrame::OnIdle(wxIdleEvent& event)772{773    if (fRefreshListCtrl)774    {775        // Collect list of wallet transactions and sort newest first776        bool fEntered = false;777        vector<pair<unsigned int, uint256> > vSorted;778        TRY_CRITICAL_BLOCK(cs_mapWallet)779        {780            printf("RefreshListCtrl starting\n");781            fEntered = true;782            fRefreshListCtrl = false;783            vWalletUpdated.clear();784785            // Do the newest transactions first786            vSorted.reserve(mapWallet.size());787            for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)788            {789                const CWalletTx& wtx = (*it).second;790                unsigned int nTime = UINT_MAX - wtx.GetTxTime();791                vSorted.push_back(make_pair(nTime, (*it).first));792            }793            m_listCtrl->DeleteAllItems();794        }795        if (!fEntered)796            return;797798        sort(vSorted.begin(), vSorted.end());799800        // Fill list control801        for (int i = 0; i < vSorted.size();)802        {803            if (fShutdown)804                return;805            bool fEntered = false;806            TRY_CRITICAL_BLOCK(cs_mapWallet)807            {808                fEntered = true;809                uint256& hash = vSorted[i++].second;810                map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);811                if (mi != mapWallet.end())812                    InsertTransaction((*mi).second, true);813            }814            if (!fEntered || i == 100 || i % 500 == 0)815                wxYield();816        }817818        printf("RefreshListCtrl done\n");819820        // Update transaction total display821        MainFrameRepaint();822    }823    else824    {825        // Check for time updates826        static int64 nLastTime;827        if (GetTime() > nLastTime + 30)828        {829            TRY_CRITICAL_BLOCK(cs_mapWallet)830            {831                nLastTime = GetTime();832                for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)833                {834                    CWalletTx& wtx = (*it).second;835                    if (wtx.nTimeDisplayed && wtx.nTimeDisplayed != wtx.GetTxTime())836                        InsertTransaction(wtx, false);837                }838            }839        }840    }841}842843void CMainFrame::RefreshStatusColumn()844{845    static int nLastTop;846    static CBlockIndex* pindexLastBest;847    static unsigned int nLastRefreshed;848849    int nTop = max((int)m_listCtrl->GetTopItem(), 0);850    if (nTop == nLastTop && pindexLastBest == pindexBest)851        return;852853    TRY_CRITICAL_BLOCK(cs_mapWallet)854    {855        int nStart = nTop;856        int nEnd = min(nStart + 100, m_listCtrl->GetItemCount());857858        if (pindexLastBest == pindexBest && nLastRefreshed == nListViewUpdated)859        {860            // If no updates, only need to do the part that moved onto the screen861            if (nStart >= nLastTop && nStart < nLastTop + 100)862                nStart = nLastTop + 100;863            if (nEnd >= nLastTop && nEnd < nLastTop + 100)864                nEnd = nLastTop;865        }866        nLastTop = nTop;867        pindexLastBest = pindexBest;868        nLastRefreshed = nListViewUpdated;869870        for (int nIndex = nStart; nIndex < min(nEnd, m_listCtrl->GetItemCount()); nIndex++)871        {872            uint256 hash((string)GetItemText(m_listCtrl, nIndex, 1));873            map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);874            if (mi == mapWallet.end())875            {876                printf("CMainFrame::RefreshStatusColumn() : tx not found in mapWallet\n");877                continue;878            }879            CWalletTx& wtx = (*mi).second;880            if (wtx.IsCoinBase() || wtx.GetTxTime() != wtx.nTimeDisplayed)881            {882                if (!InsertTransaction(wtx, false, nIndex))883                    m_listCtrl->DeleteItem(nIndex--);884            }885            else886                m_listCtrl->SetItem(nIndex, 2, FormatTxStatus(wtx));887        }888    }889}890891void CMainFrame::OnPaint(wxPaintEvent& event)892{893    event.Skip();894    if (fRefresh)895    {896        fRefresh = false;897        Refresh();898    }899}900901902unsigned int nNeedRepaint = 0;903unsigned int nLastRepaint = 0;904int64 nLastRepaintTime = 0;905int64 nRepaintInterval = 500;906907void ThreadDelayedRepaint(void* parg)908{909    while (!fShutdown)910    {911        if (nLastRepaint != nNeedRepaint && GetTimeMillis() - nLastRepaintTime >= nRepaintInterval)912        {913            nLastRepaint = nNeedRepaint;914            if (pframeMain)915            {916                printf("DelayedRepaint\n");917                wxPaintEvent event;918                pframeMain->fRefresh = true;919                pframeMain->GetEventHandler()->AddPendingEvent(event);920            }921        }922        Sleep(nRepaintInterval);923    }924}925926void MainFrameRepaint()927{928    // This is called by network code that shouldn't access pframeMain929    // directly because it could still be running after the UI is closed.930    if (pframeMain)931    {932        // Don't repaint too often933        static int64 nLastRepaintRequest;934        if (GetTimeMillis() - nLastRepaintRequest < 100)935        {936            nNeedRepaint++;937            return;938        }939        nLastRepaintRequest = GetTimeMillis();940941        printf("MainFrameRepaint\n");942        wxPaintEvent event;943        pframeMain->fRefresh = true;944        pframeMain->GetEventHandler()->AddPendingEvent(event);945    }946}947948void CMainFrame::OnPaintListCtrl(wxPaintEvent& event)949{950    // Skip lets the listctrl do the paint, we're just hooking the message951    event.Skip();952953    if (ptaskbaricon)954        ptaskbaricon->UpdateTooltip();955956    //957    // Slower stuff958    //959    static int nTransactionCount;960    bool fPaintedBalance = false;961    if (GetTimeMillis() - nLastRepaintTime >= nRepaintInterval)962    {963        nLastRepaint = nNeedRepaint;964        nLastRepaintTime = GetTimeMillis();965966        // Update listctrl contents967        if (!vWalletUpdated.empty())968        {969            TRY_CRITICAL_BLOCK(cs_mapWallet)970            {971                string strTop;972                if (m_listCtrl->GetItemCount())973                    strTop = (string)m_listCtrl->GetItemText(0);974                foreach(uint256 hash, vWalletUpdated)975                {976                    map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);977                    if (mi != mapWallet.end())978                        InsertTransaction((*mi).second, false);979                }980                vWalletUpdated.clear();981                if (m_listCtrl->GetItemCount() && strTop != (string)m_listCtrl->GetItemText(0))982                    m_listCtrl->ScrollList(0, INT_MIN/2);983            }984        }985986        // Balance total987        TRY_CRITICAL_BLOCK(cs_mapWallet)988        {989            fPaintedBalance = true;990            m_staticTextBalance->SetLabel(FormatMoney(GetBalance()) + "  ");991992            // Count hidden and multi-line transactions993            nTransactionCount = 0;994            for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)995            {996                CWalletTx& wtx = (*it).second;997                nTransactionCount += wtx.nLinesDisplayed;998            }999        }1000    }1001    if (!vWalletUpdated.empty() || !fPaintedBalance)1002        nNeedRepaint++;10031004    // Update status column of visible items only1005    RefreshStatusColumn();10061007    // Update status bar1008    string strGen = "";1009    if (fGenerateBitcoins)1010        strGen = _("    Generating");1011    if (fGenerateBitcoins && vNodes.empty())1012        strGen = _("(not connected)");1013    m_statusBar->SetStatusText(strGen, 1);10141015    string strStatus = strprintf(_("     %d connections     %d blocks     %d transactions"), vNodes.size(), nBestHeight + 1, nTransactionCount);1016    m_statusBar->SetStatusText(strStatus, 2);10171018    if (fDebug && GetTime() - nThreadSocketHandlerHeartbeat > 60)1019        m_statusBar->SetStatusText("     ERROR: ThreadSocketHandler has stopped", 0);10201021    // Update receiving address1022    string strDefaultAddress = PubKeyToAddress(vchDefaultKey);1023    if (m_textCtrlAddress->GetValue() != strDefaultAddress)1024        m_textCtrlAddress->SetValue(strDefaultAddress);1025}102610271028void UIThreadCall(boost::function0<void> fn)1029{1030    // Call this with a function object created with bind.1031    // bind needs all parameters to match the function's expected types1032    // and all default parameters specified.  Some examples:1033    //  UIThreadCall(bind(wxBell));1034    //  UIThreadCall(bind(wxMessageBox, wxT("Message"), wxT("Title"), wxOK, (wxWindow*)NULL, -1, -1));1035    //  UIThreadCall(bind(&CMainFrame::OnMenuHelpAbout, pframeMain, event));1036    if (pframeMain)1037    {1038        wxCommandEvent event(wxEVT_UITHREADCALL);1039        event.SetClientData((void*)new boost::function0<void>(fn));1040        pframeMain->GetEventHandler()->AddPendingEvent(event);1041    }1042}10431044void CMainFrame::OnUIThreadCall(wxCommandEvent& event)1045{1046    boost::function0<void>* pfn = (boost::function0<void>*)event.GetClientData();1047    (*pfn)();1048    delete pfn;1049}10501051void CMainFrame::OnMenuFileExit(wxCommandEvent& event)1052{1053    // File->Exit1054    Close(true);1055}10561057void CMainFrame::OnMenuOptionsGenerate(wxCommandEvent& event)1058{1059    // Options->Generate Coins1060    GenerateBitcoins(event.IsChecked());1061}10621063void CMainFrame::OnUpdateUIOptionsGenerate(wxUpdateUIEvent& event)1064{1065    event.Check(fGenerateBitcoins);1066}10671068void CMainFrame::OnMenuOptionsChangeYourAddress(wxCommandEvent& event)1069{1070    // Options->Your Receiving Addresses1071    CAddressBookDialog dialog(this, "", CAddressBookDialog::RECEIVING, false);1072    if (!dialog.ShowModal())1073        return;1074}10751076void CMainFrame::OnMenuOptionsOptions(wxCommandEvent& event)1077{1078    // Options->Options1079    COptionsDialog dialog(this);1080    dialog.ShowModal();1081}10821083void CMainFrame::OnMenuHelpAbout(wxCommandEvent& event)1084{1085    // Help->About1086    CAboutDialog dialog(this);1087    dialog.ShowModal();1088}10891090void CMainFrame::OnButtonSend(wxCommandEvent& event)1091{1092    // Toolbar: Send1093    CSendDialog dialog(this);1094    dialog.ShowModal();1095}10961097void CMainFrame::OnButtonAddressBook(wxCommandEvent& event)1098{1099    // Toolbar: Address Book1100    CAddressBookDialog dialogAddr(this, "", CAddressBookDialog::SENDING, false);1101    if (dialogAddr.ShowModal() == 2)1102    {1103        // Send1104        CSendDialog dialogSend(this, dialogAddr.GetSelectedAddress());1105        dialogSend.ShowModal();1106    }1107}11081109void CMainFrame::OnSetFocusAddress(wxFocusEvent& event)1110{1111    // Automatically select-all when entering window1112    event.Skip();1113    m_textCtrlAddress->SetSelection(-1, -1);1114    fOnSetFocusAddress = true;1115}11161117void CMainFrame::OnMouseEventsAddress(wxMouseEvent& event)1118{1119    event.Skip();1120    if (fOnSetFocusAddress)1121        m_textCtrlAddress->SetSelection(-1, -1);1122    fOnSetFocusAddress = false;1123}11241125void CMainFrame::OnButtonNew(wxCommandEvent& event)1126{1127    // Ask name1128    CGetTextFromUserDialog dialog(this,1129        _("New Receiving Address"),1130        _("It's good policy to use a new address for each payment you receive.\n\nLabel"),1131        "");1132    if (!dialog.ShowModal())1133        return;1134    string strName = dialog.GetValue();11351136    // Generate new key1137    string strAddress = PubKeyToAddress(GenerateNewKey());11381139    // Save1140    SetAddressBookName(strAddress, strName);1141    SetDefaultReceivingAddress(strAddress);1142}11431144void CMainFrame::OnButtonCopy(wxCommandEvent& event)1145{1146    // Copy address box to clipboard1147    if (wxTheClipboard->Open())1148    {1149        wxTheClipboard->SetData(new wxTextDataObject(m_textCtrlAddress->GetValue()));1150        wxTheClipboard->Close();1151    }1152}11531154void CMainFrame::OnListItemActivated(wxListEvent& event)1155{1156    uint256 hash((string)GetItemText(m_listCtrl, event.GetIndex(), 1));1157    CWalletTx wtx;1158    CRITICAL_BLOCK(cs_mapWallet)1159    {1160        map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);1161        if (mi == mapWallet.end())1162        {1163            printf("CMainFrame::OnListItemActivated() : tx not found in mapWallet\n");1164            return;1165        }1166        wtx = (*mi).second;1167    }1168    CTxDetailsDialog dialog(this, wtx);1169    dialog.ShowModal();1170    //CTxDetailsDialog* pdialog = new CTxDetailsDialog(this, wtx);1171    //pdialog->Show();1172}1173117411751176117711781179//////////////////////////////////////////////////////////////////////////////1180//1181// CTxDetailsDialog1182//11831184CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetailsDialogBase(parent)1185{1186    CRITICAL_BLOCK(cs_mapAddressBook)1187    {1188        string strHTML;1189        strHTML.reserve(4000);1190        strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>";11911192        int64 nTime = wtx.GetTxTime();1193        int64 nCredit = wtx.GetCredit();1194        int64 nDebit = wtx.GetDebit();1195        int64 nNet = nCredit - nDebit;1196119711981199        strHTML += _("<b>Status:</b> ") + FormatTxStatus(wtx);1200        int nRequests = wtx.GetRequestCount();1201        if (nRequests != -1)1202        {1203            if (nRequests == 0)1204                strHTML += _(", has not been successfully broadcast yet");1205            else if (nRequests == 1)1206                strHTML += strprintf(_(", broadcast through %d node"), nRequests);1207            else1208                strHTML += strprintf(_(", broadcast through %d nodes"), nRequests);1209        }1210        strHTML += "<br>";12111212        strHTML += _("<b>Date:</b> ") + (nTime ? DateTimeStr(nTime) : "") + "<br>";121312141215        //1216        // From1217        //1218        if (wtx.IsCoinBase())1219        {1220            strHTML += _("<b>Source:</b> Generated<br>");1221        }1222        else if (!wtx.mapValue["from"].empty())1223        {1224            // Online transaction1225            if (!wtx.mapValue["from"].empty())1226                strHTML += _("<b>From:</b> ") + HtmlEscape(wtx.mapValue["from"]) + "<br>";1227        }1228        else1229        {1230            // Offline transaction1231            if (nNet > 0)1232            {1233                // Credit1234                foreach(const CTxOut& txout, wtx.vout)1235                {1236                    if (txout.IsMine())1237                    {1238                        vector<unsigned char> vchPubKey;1239                        if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey))1240                        {1241                            string strAddress = PubKeyToAddress(vchPubKey);1242                            if (mapAddressBook.count(strAddress))1243                            {1244                                strHTML += string() + _("<b>From:</b> ") + _("unknown") + "<br>";1245                                strHTML += _("<b>To:</b> ");1246                                strHTML += HtmlEscape(strAddress);1247                                if (!mapAddressBook[strAddress].empty())1248                                    strHTML += _(" (yours, label: ") + mapAddressBook[strAddress] + ")";1249                                else1250                                    strHTML += _(" (yours)");1251                                strHTML += "<br>";1252                            }1253                        }1254                        break;1255                    }1256                }1257            }1258        }125912601261        //1262        // To1263        //1264        string strAddress;1265        if (!wtx.mapValue["to"].empty())1266        {1267            // Online transaction1268            strAddress = wtx.mapValue["to"];1269            strHTML += _("<b>To:</b> ");1270            if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())1271                strHTML += mapAddressBook[strAddress] + " ";1272            strHTML += HtmlEscape(strAddress) + "<br>";1273        }127412751276        //1277        // Amount1278        //1279        if (wtx.IsCoinBase() && nCredit == 0)1280        {1281            //1282            // Coinbase1283            //1284            int64 nUnmatured = 0;1285            foreach(const CTxOut& txout, wtx.vout)1286                nUnmatured += txout.GetCredit();1287            strHTML += _("<b>Credit:</b> ");1288            if (wtx.IsInMainChain())1289                strHTML += strprintf(_("(%s matures in %d more blocks)"), FormatMoney(nUnmatured).c_str(), wtx.GetBlocksToMaturity());1290            else1291                strHTML += _("(not accepted)");1292            strHTML += "<br>";1293        }1294        else if (nNet > 0)1295        {1296            //1297            // Credit1298            //1299            strHTML += _("<b>Credit:</b> ") + FormatMoney(nNet) + "<br>";1300        }1301        else1302        {1303            bool fAllFromMe = true;1304            foreach(const CTxIn& txin, wtx.vin)1305                fAllFromMe = fAllFromMe && txin.IsMine();13061307            bool fAllToMe = true;1308            foreach(const CTxOut& txout, wtx.vout)1309                fAllToMe = fAllToMe && txout.IsMine();13101311            if (fAllFromMe)1312            {1313                //1314                // Debit1315                //1316                foreach(const CTxOut& txout, wtx.vout)1317                {1318                    if (txout.IsMine())1319                        continue;13201321                    if (wtx.mapValue["to"].empty())1322                    {1323                        // Offline transaction1324                        uint160 hash160;1325                        if (ExtractHash160(txout.scriptPubKey, hash160))1326                        {1327                            string strAddress = Hash160ToAddress(hash160);1328                            strHTML += _("<b>To:</b> ");1329                            if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())1330                                strHTML += mapAddressBook[strAddress] + " ";1331                            strHTML += strAddress;1332                            strHTML += "<br>";1333                        }1334                    }13351336                    strHTML += _("<b>Debit:</b> ") + FormatMoney(-txout.nValue) + "<br>";1337                }13381339                if (fAllToMe)1340                {1341                    // Payment to self1342                    /// issue: can't tell which is the payment and which is the change anymore1343                    //int64 nValue = wtx.vout[0].nValue;1344                    //strHTML += _("<b>Debit:</b> ") + FormatMoney(-nValue) + "<br>";1345                    //strHTML += _("<b>Credit:</b> ") + FormatMoney(nValue) + "<br>";1346                }13471348                int64 nTxFee = nDebit - wtx.GetValueOut();1349                if (nTxFee > 0)1350                    strHTML += _("<b>Transaction fee:</b> ") + FormatMoney(-nTxFee) + "<br>";1351            }1352            else1353            {1354                //1355                // Mixed debit transaction1356                //1357                foreach(const CTxIn& txin, wtx.vin)1358                    if (txin.IsMine())1359                        strHTML += _("<b>Debit:</b> ") + FormatMoney(-txin.GetDebit()) + "<br>";1360                foreach(const CTxOut& txout, wtx.vout)1361                    if (txout.IsMine())1362                        strHTML += _("<b>Credit:</b> ") + FormatMoney(txout.GetCredit()) + "<br>";1363            }1364        }13651366        strHTML += _("<b>Net amount:</b> ") + FormatMoney(nNet, true) + "<br>";136713681369        //1370        // Message1371        //1372        if (!wtx.mapValue["message"].empty())1373            strHTML += string() + "<br><b>" + _("Message:") + "</b><br>" + HtmlEscape(wtx.mapValue["message"], true) + "<br>";13741375        if (wtx.IsCoinBase())1376            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>";137713781379        //1380        // Debug view1381        //1382        if (fDebug)1383        {1384            strHTML += "<hr><br>debug print<br><br>";1385            foreach(const CTxIn& txin, wtx.vin)1386                if (txin.IsMine())1387                    strHTML += "<b>Debit:</b> " + FormatMoney(-txin.GetDebit()) + "<br>";1388            foreach(const CTxOut& txout, wtx.vout)1389                if (txout.IsMine())1390                    strHTML += "<b>Credit:</b> " + FormatMoney(txout.GetCredit()) + "<br>";13911392            strHTML += "<b>Inputs:</b><br>";1393            CRITICAL_BLOCK(cs_mapWallet)1394            {1395                foreach(const CTxIn& txin, wtx.vin)1396                {1397                    COutPoint prevout = txin.prevout;1398                    map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);1399                    if (mi != mapWallet.end())1400                    {1401                        const CWalletTx& prev = (*mi).second;1402                        if (prevout.n < prev.vout.size())1403                        {1404                            strHTML += HtmlEscape(prev.ToString(), true);1405                            strHTML += " &nbsp;&nbsp; " + FormatTxStatus(prev) + ", ";1406                            strHTML = strHTML + "IsMine=" + (prev.vout[prevout.n].IsMine() ? "true" : "false") + "<br>";1407                        }1408                    }1409                }1410            }14111412            strHTML += "<br><hr><br><b>Transaction:</b><br>";1413            strHTML += HtmlEscape(wtx.ToString(), true);1414        }1415141614171418        strHTML += "</font></html>";1419        string(strHTML.begin(), strHTML.end()).swap(strHTML);1420        m_htmlWin->SetPage(strHTML);1421        m_buttonOK->SetFocus();1422    }1423}14241425void CTxDetailsDialog::OnButtonOK(wxCommandEvent& event)1426{1427    Close();1428    //Destroy();1429}143014311432143314341435//////////////////////////////////////////////////////////////////////////////1436//1437// COptionsDialog1438//14391440COptionsDialog::COptionsDialog(wxWindow* parent) : COptionsDialogBase(parent)1441{1442    // Set up list box of page choices1443    m_listBox->Append(_("Main"));1444    //m_listBox->Append(_("Test 2"));1445    m_listBox->SetSelection(0);1446    SelectPage(0);1447#ifndef __WXMSW__1448    m_checkBoxMinimizeOnClose->SetLabel(_("&Minimize on close"));1449    m_checkBoxStartOnSystemStartup->Enable(false); // not implemented yet1450#endif14511452    // Init values1453    m_textCtrlTransactionFee->SetValue(FormatMoney(nTransactionFee));1454    m_checkBoxLimitProcessors->SetValue(fLimitProcessors);1455    m_spinCtrlLimitProcessors->Enable(fLimitProcessors);1456    m_spinCtrlLimitProcessors->SetValue(nLimitProcessors);1457    int nProcessors = wxThread::GetCPUCount();1458    if (nProcessors < 1)1459        nProcessors = 999;1460    m_spinCtrlLimitProcessors->SetRange(1, nProcessors);1461    m_checkBoxStartOnSystemStartup->SetValue(fTmpStartOnSystemStartup = GetStartOnSystemStartup());1462    m_checkBoxMinimizeToTray->SetValue(fMinimizeToTray);1463    m_checkBoxMinimizeOnClose->SetValue(fMinimizeOnClose);1464    m_checkBoxUseProxy->SetValue(fUseProxy);1465    m_textCtrlProxyIP->Enable(fUseProxy);1466    m_textCtrlProxyPort->Enable(fUseProxy);1467    m_staticTextProxyIP->Enable(fUseProxy);1468    m_staticTextProxyPort->Enable(fUseProxy);1469    m_textCtrlProxyIP->SetValue(addrProxy.ToStringIP());1470    m_textCtrlProxyPort->SetValue(addrProxy.ToStringPort());14711472    m_buttonOK->SetFocus();1473}14741475void COptionsDialog::SelectPage(int nPage)1476{1477    m_panelMain->Show(nPage == 0);1478    m_panelTest2->Show(nPage == 1);14791480    m_scrolledWindow->Layout();1481    m_scrolledWindow->SetScrollbars(0, 0, 0, 0, 0, 0);1482}14831484void COptionsDialog::OnListBox(wxCommandEvent& event)1485{1486    SelectPage(event.GetSelection());1487}14881489void COptionsDialog::OnKillFocusTransactionFee(wxFocusEvent& event)1490{1491    event.Skip();1492    int64 nTmp = nTransactionFee;1493    ParseMoney(m_textCtrlTransactionFee->GetValue(), nTmp);1494    m_textCtrlTransactionFee->SetValue(FormatMoney(nTmp));1495}14961497void COptionsDialog::OnCheckBoxLimitProcessors(wxCommandEvent& event)1498{1499    m_spinCtrlLimitProcessors->Enable(event.IsChecked());1500}15011502void COptionsDialog::OnCheckBoxUseProxy(wxCommandEvent& event)1503{1504    m_textCtrlProxyIP->Enable(event.IsChecked());1505    m_textCtrlProxyPort->Enable(event.IsChecked());1506    m_staticTextProxyIP->Enable(event.IsChecked());1507    m_staticTextProxyPort->Enable(event.IsChecked());1508}15091510CAddress COptionsDialog::GetProxyAddr()1511{1512    // Be careful about byte order, addr.ip and addr.port are big endian1513    CAddress addr(m_textCtrlProxyIP->GetValue() + ":" + m_textCtrlProxyPort->GetValue());1514    if (addr.ip == INADDR_NONE)1515        addr.ip = addrProxy.ip;1516    int nPort = atoi(m_textCtrlProxyPort->GetValue());1517    addr.port = htons(nPort);1518    if (nPort <= 0 || nPort > USHRT_MAX)1519        addr.port = addrProxy.port;1520    return addr;1521}15221523void COptionsDialog::OnKillFocusProxy(wxFocusEvent& event)1524{1525    event.Skip();1526    m_textCtrlProxyIP->SetValue(GetProxyAddr().ToStringIP());1527    m_textCtrlProxyPort->SetValue(GetProxyAddr().ToStringPort());1528}152915301531void COptionsDialog::OnButtonOK(wxCommandEvent& event)1532{1533    OnButtonApply(event);1534    Close();1535}15361537void COptionsDialog::OnButtonCancel(wxCommandEvent& event)1538{1539    Close();1540}15411542void COptionsDialog::OnButtonApply(wxCommandEvent& event)1543{1544    CWalletDB walletdb;15451546    int64 nPrevTransactionFee = nTransactionFee;1547    if (ParseMoney(m_textCtrlTransactionFee->GetValue(), nTransactionFee) && nTransactionFee != nPrevTransactionFee)1548        walletdb.WriteSetting("nTransactionFee", nTransactionFee);15491550    int nPrevMaxProc = (fLimitProcessors ? nLimitProcessors : INT_MAX);1551    if (fLimitProcessors != m_checkBoxLimitProcessors->GetValue())1552    {1553        fLimitProcessors = m_checkBoxLimitProcessors->GetValue();1554        walletdb.WriteSetting("fLimitProcessors", fLimitProcessors);1555    }1556    if (nLimitProcessors != m_spinCtrlLimitProcessors->GetValue())1557    {1558        nLimitProcessors = m_spinCtrlLimitProcessors->GetValue();1559        walletdb.WriteSetting("nLimitProcessors", nLimitProcessors);1560    }1561    if (fGenerateBitcoins && (fLimitProcessors ? nLimitProcessors : INT_MAX) > nPrevMaxProc)1562        GenerateBitcoins(fGenerateBitcoins);15631564    if (fTmpStartOnSystemStartup != m_checkBoxStartOnSystemStartup->GetValue())1565    {1566        fTmpStartOnSystemStartup = m_checkBoxStartOnSystemStartup->GetValue();1567        SetStartOnSystemStartup(fTmpStartOnSystemStartup);1568    }15691570    if (fMinimizeToTray != m_checkBoxMinimizeToTray->GetValue())1571    {1572        fMinimizeToTray = m_checkBoxMinimizeToTray->GetValue();1573        walletdb.WriteSetting("fMinimizeToTray", fMinimizeToTray);1574        ptaskbaricon->Show(fMinimizeToTray || fClosedToTray);1575    }15761577    if (fMinimizeOnClose != m_checkBoxMinimizeOnClose->GetValue())1578    {1579        fMinimizeOnClose = m_checkBoxMinimizeOnClose->GetValue();1580        walletdb.WriteSetting("fMinimizeOnClose", fMinimizeOnClose);1581    }15821583    fUseProxy = m_checkBoxUseProxy->GetValue();1584    walletdb.WriteSetting("fUseProxy", fUseProxy);15851586    addrProxy = GetProxyAddr();1587    walletdb.WriteSetting("addrProxy", addrProxy);1588}158915901591159215931594//////////////////////////////////////////////////////////////////////////////1595//1596// CAboutDialog1597//15981599CAboutDialog::CAboutDialog(wxWindow* parent) : CAboutDialogBase(parent)1600{1601    m_staticTextVersion->SetLabel(strprintf(_("version %d.%d.%d beta"), VERSION/10000, (VERSION/100)%100, VERSION%100));16021603    // Change (c) into UTF-8 or ANSI copyright symbol1604    wxString str = m_staticTextMain->GetLabel();1605#if wxUSE_UNICODE1606    str.Replace("(c)", wxString::FromUTF8("\xC2\xA9"));1607#else1608    str.Replace("(c)", "\xA9");1609#endif1610    m_staticTextMain->SetLabel(str);1611#ifndef __WXMSW__1612    // Resize on Linux to make the window fit the text.1613    // The text was wrapped manually rather than using the Wrap setting because1614    // the wrap would be too small on Linux and it can't be changed at this point.1615    wxFont fontTmp = m_staticTextMain->GetFont();1616    if (fontTmp.GetPointSize() > 8);1617        fontTmp.SetPointSize(8);1618    m_staticTextMain->SetFont(fontTmp);1619    SetSize(GetSize().GetWidth() + 44, GetSize().GetHeight() + 10);1620#endif1621}16221623void CAboutDialog::OnButtonOK(wxCommandEvent& event)1624{1625    Close();1626}1627162816291630163116321633//////////////////////////////////////////////////////////////////////////////1634//1635// CSendDialog1636//16371638CSendDialog::CSendDialog(wxWindow* parent, const wxString& strAddress) : CSendDialogBase(parent)1639{1640    // Init1641    m_textCtrlAddress->SetValue(strAddress);1642    m_choiceTransferType->SetSelection(0);1643    m_bitmapCheckMark->Show(false);1644    fEnabledPrev = true;1645    m_textCtrlAddress->SetFocus();1646    //// todo: should add a display of your balance for convenience1647#ifndef __WXMSW__1648    wxFont fontTmp = m_staticTextInstructions->GetFont();1649    if (fontTmp.GetPointSize() > 9);1650        fontTmp.SetPointSize(9);1651    m_staticTextInstructions->SetFont(fontTmp);1652    SetSize(725, 380);1653#endif16541655    // Set Icon1656    wxIcon iconSend;1657    iconSend.CopyFromBitmap(wxBitmap(send16noshadow_xpm));1658    SetIcon(iconSend);16591660    wxCommandEvent event;1661    OnTextAddress(event);16621663    // Fixup the tab order1664    m_buttonPaste->MoveAfterInTabOrder(m_buttonCancel);1665    m_buttonAddress->MoveAfterInTabOrder(m_buttonPaste);1666    this->Layout();1667}16681669void CSendDialog::OnTextAddress(wxCommandEvent& event)1670{1671    // Check mark1672    event.Skip();1673    bool fBitcoinAddress = IsValidBitcoinAddress(m_textCtrlAddress->GetValue());1674    m_bitmapCheckMark->Show(fBitcoinAddress);16751676    // Grey out message if bitcoin address1677    bool fEnable = !fBitcoinAddress;1678    m_staticTextFrom->Enable(fEnable);1679    m_textCtrlFrom->Enable(fEnable);1680    m_staticTextMessage->Enable(fEnable);1681    m_textCtrlMessage->Enable(fEnable);1682    m_textCtrlMessage->SetBackgroundColour(wxSystemSettings::GetColour(fEnable ? wxSYS_COLOUR_WINDOW : wxSYS_COLOUR_BTNFACE));1683    if (!fEnable && fEnabledPrev)1684    {1685        strFromSave    = m_textCtrlFrom->GetValue();1686        strMessageSave = m_textCtrlMessage->GetValue();1687        m_textCtrlFrom->SetValue(_("Will appear as \"From: Unknown\""));1688        m_textCtrlMessage->SetValue(_("Can't include a message when sending to a Bitcoin address"));1689    }1690    else if (fEnable && !fEnabledPrev)1691    {1692        m_textCtrlFrom->SetValue(strFromSave);1693        m_textCtrlMessage->SetValue(strMessageSave);1694    }1695    fEnabledPrev = fEnable;1696}16971698void CSendDialog::OnKillFocusAmount(wxFocusEvent& event)1699{1700    // Reformat the amount1701    event.Skip();1702    if (m_textCtrlAmount->GetValue().Trim().empty())1703        return;1704    int64 nTmp;1705    if (ParseMoney(m_textCtrlAmount->GetValue(), nTmp))1706        m_textCtrlAmount->SetValue(FormatMoney(nTmp));1707}17081709void CSendDialog::OnButtonAddressBook(wxCommandEvent& event)1710{1711    // Open address book1712    CAddressBookDialog dialog(this, m_textCtrlAddress->GetValue(), CAddressBookDialog::SENDING, true);1713    if (dialog.ShowModal())1714        m_textCtrlAddress->SetValue(dialog.GetSelectedAddress());1715}17161717void CSendDialog::OnButtonPaste(wxCommandEvent& event)1718{1719    // Copy clipboard to address box1720    if (wxTheClipboard->Open())1721    {1722        if (wxTheClipboard->IsSupported(wxDF_TEXT))1723        {1724            wxTextDataObject data;1725            wxTheClipboard->GetData(data);1726            m_textCtrlAddress->SetValue(data.GetText());1727        }1728        wxTheClipboard->Close();1729    }1730}17311732void CSendDialog::OnButtonSend(wxCommandEvent& event)1733{1734    CWalletTx wtx;1735    string strAddress = (string)m_textCtrlAddress->GetValue();17361737    // Parse amount1738    int64 nValue = 0;1739    if (!ParseMoney(m_textCtrlAmount->GetValue(), nValue) || nValue <= 0)1740    {1741        wxMessageBox(_("Error in amount  "), _("Send Coins"));1742        return;1743    }1744    if (nValue > GetBalance())1745    {1746        wxMessageBox(_("Amount exceeds your balance  "), _("Send Coins"));1747        return;1748    }1749    if (nValue + nTransactionFee > GetBalance())1750    {1751        wxMessageBox(string(_("Total exceeds your balance when the ")) + FormatMoney(nTransactionFee) + _(" transaction fee is included  "), _("Send Coins"));1752        return;1753    }17541755    // Parse bitcoin address1756    uint160 hash160;1757    bool fBitcoinAddress = AddressToHash160(strAddress, hash160);17581759    if (fBitcoinAddress)1760    {1761        // Send to bitcoin address1762        CScript scriptPubKey;1763        scriptPubKey << OP_DUP << OP_HASH160 << hash160 << OP_EQUALVERIFY << OP_CHECKSIG;17641765        string strError = SendMoney(scriptPubKey, nValue, wtx, true);1766        if (strError == "")1767            wxMessageBox(_("Payment sent  "), _("Sending..."));1768        else if (strError != "ABORTED")1769            wxMessageBox(strError + "  ", _("Sending..."));1770    }1771    else1772    {1773        // Parse IP address1774        CAddress addr(strAddress);1775        if (!addr.IsValid())1776        {1777            wxMessageBox(_("Invalid address  "), _("Send Coins"));1778            return;1779        }17801781        // Message1782        wtx.mapValue["to"] = strAddress;1783        wtx.mapValue["from"] = m_textCtrlFrom->GetValue();1784        wtx.mapValue["message"] = m_textCtrlMessage->GetValue();17851786        // Send to IP address1787        CSendingDialog* pdialog = new CSendingDialog(this, addr, nValue, wtx);1788        if (!pdialog->ShowModal())1789            return;1790    }17911792    CRITICAL_BLOCK(cs_mapAddressBook)1793        if (!mapAddressBook.count(strAddress))1794            SetAddressBookName(strAddress, "");17951796    EndModal(true);1797}17981799void CSendDialog::OnButtonCancel(wxCommandEvent& event)1800{1801    // Cancel1802    EndModal(false);1803}1804180518061807180818091810//////////////////////////////////////////////////////////////////////////////1811//1812// CSendingDialog1813//18141815CSendingDialog::CSendingDialog(wxWindow* parent, const CAddress& addrIn, int64 nPriceIn, const CWalletTx& wtxIn) : CSendingDialogBase(NULL) // we have to give null so parent can't destroy us1816{1817    addr = addrIn;1818    nPrice = nPriceIn;1819    wtx = wtxIn;1820    start = wxDateTime::UNow();1821    memset(pszStatus, 0, sizeof(pszStatus));1822    fCanCancel = true;1823    fAbort = false;1824    fSuccess = false;1825    fUIDone = false;1826    fWorkDone = false;1827#ifndef __WXMSW__1828    SetSize(1.2 * GetSize().GetWidth(), 1.08 * GetSize().GetHeight());1829#endif18301831    SetTitle(strprintf(_("Sending %s to %s"), FormatMoney(nPrice).c_str(), wtx.mapValue["to"].c_str()));1832    m_textCtrlStatus->SetValue("");18331834    CreateThread(SendingDialogStartTransfer, this);1835}18361837CSendingDialog::~CSendingDialog()1838{1839    printf("~CSendingDialog()\n");1840}18411842void CSendingDialog::Close()1843{1844    // Last one out turn out the lights.1845    // fWorkDone signals that work side is done and UI thread should call destroy.1846    // fUIDone signals that UI window has closed and work thread should call destroy.1847    // This allows the window to disappear and end modality when cancelled1848    // without making the user wait for ConnectNode to return.  The dialog object1849    // hangs around in the background until the work thread exits.1850    if (IsModal())1851        EndModal(fSuccess);1852    else1853        Show(false);1854    if (fWorkDone)1855        Destroy();1856    else1857        fUIDone = true;1858}18591860void CSendingDialog::OnClose(wxCloseEvent& event)1861{1862    if (!event.CanVeto() || fWorkDone || fAbort || !fCanCancel)1863    {1864        Close();1865    }1866    else1867    {1868        event.Veto();1869        wxCommandEvent cmdevent;1870        OnButtonCancel(cmdevent);1871    }1872}18731874void CSendingDialog::OnButtonOK(wxCommandEvent& event)1875{1876    if (fWorkDone)1877        Close();1878}18791880void CSendingDialog::OnButtonCancel(wxCommandEvent& event)1881{1882    if (fCanCancel)1883        fAbort = true;1884}18851886void CSendingDialog::OnPaint(wxPaintEvent& event)1887{1888    event.Skip();1889    if (strlen(pszStatus) > 130)1890        m_textCtrlStatus->SetValue(string("\n") + pszStatus);1891    else1892        m_textCtrlStatus->SetValue(string("\n\n") + pszStatus);1893    m_staticTextSending->SetFocus();1894    if (!fCanCancel)1895        m_buttonCancel->Enable(false);1896    if (fWorkDone)1897    {1898        m_buttonOK->Enable(true);1899        m_buttonOK->SetFocus();1900        m_buttonCancel->Enable(false);1901    }1902    if (fAbort && fCanCancel && IsShown())1903    {1904        strcpy(pszStatus, _("CANCELLED"));1905        m_buttonOK->Enable(true);1906        m_buttonOK->SetFocus();1907        m_buttonCancel->Enable(false);1908        m_buttonCancel->SetLabel(_("Cancelled"));1909        Close();1910        wxMessageBox(_("Transfer cancelled  "), _("Sending..."), wxOK, this);1911    }1912}191319141915//1916// Everything from here on is not in the UI thread and must only communicate1917// with the rest of the dialog through variables and calling repaint.1918//19191920void CSendingDialog::Repaint()1921{1922    Refresh();1923    wxPaintEvent event;1924    GetEventHandler()->AddPendingEvent(event);1925}19261927bool CSendingDialog::Status()1928{1929    if (fUIDone)1930    {1931        Destroy();1932        return false;1933    }1934    if (fAbort && fCanCancel)1935    {1936        memset(pszStatus, 0, 10);1937        strcpy(pszStatus, _("CANCELLED"));1938        Repaint();1939        fWorkDone = true;1940        return false;1941    }1942    return true;1943}19441945bool CSendingDialog::Status(const string& str)1946{1947    if (!Status())1948        return false;19491950    // This can be read by the UI thread at any time,1951    // so copy in a way that can be read cleanly at all times.1952    memset(pszStatus, 0, min(str.size()+1, sizeof(pszStatus)));1953    strlcpy(pszStatus, str.c_str(), sizeof(pszStatus));19541955    Repaint();1956    return true;1957}19581959bool CSendingDialog::Error(const string& str)1960{1961    fCanCancel = false;1962    fWorkDone = true;1963    Status(string(_("Error: ")) + str);1964    return false;1965}19661967void SendingDialogStartTransfer(void* parg)1968{1969    ((CSendingDialog*)parg)->StartTransfer();1970}19711972void CSendingDialog::StartTransfer()1973{1974    // Make sure we have enough money1975    if (nPrice + nTransactionFee > GetBalance())1976    {1977        Error(_("Insufficient funds"));1978        return;1979    }19801981    // We may have connected already for product details1982    if (!Status(_("Connecting...")))1983        return;1984    CNode* pnode = ConnectNode(addr, 15 * 60);1985    if (!pnode)1986    {1987        Error(_("Unable to connect"));1988        return;1989    }19901991    // Send order to seller, with response going to OnReply2 via event handler1992    if (!Status(_("Requesting public key...")))1993        return;1994    pnode->PushRequest("checkorder", wtx, SendingDialogOnReply2, this);1995}19961997void SendingDialogOnReply2(void* parg, CDataStream& vRecv)1998{1999    ((CSendingDialog*)parg)->OnReply2(vRecv);2000}20012002void CSendingDialog::OnReply2(CDataStream& vRecv)2003{2004    if (!Status(_("Received public key...")))2005        return;20062007    CScript scriptPubKey;2008    int nRet;2009    try2010    {2011        vRecv >> nRet;2012        if (nRet > 0)2013        {2014            string strMessage;2015            vRecv >> strMessage;2016            Error(_("Transfer was not accepted"));2017            //// todo: enlarge the window and enable a hidden white box to put seller's message2018            return;2019        }2020        vRecv >> scriptPubKey;2021    }2022    catch (...)2023    {2024        //// what do we want to do about this?2025        Error(_("Invalid response received"));2026        return;2027    }20282029    // Pause to give the user a chance to cancel2030    while (wxDateTime::UNow() < start + wxTimeSpan(0, 0, 0, 2 * 1000))2031    {2032        Sleep(200);2033        if (!Status())2034            return;2035    }20362037    CRITICAL_BLOCK(cs_main)2038    {2039        // Pay2040        if (!Status(_("Creating transaction...")))2041            return;2042        if (nPrice + nTransactionFee > GetBalance())2043        {2044            Error(_("Insufficient funds"));2045            return;2046        }2047        CKey key;2048        int64 nFeeRequired;2049        if (!CreateTransaction(scriptPubKey, nPrice, wtx, key, nFeeRequired))2050        {2051            if (nPrice + nFeeRequired > GetBalance())2052                Error(strprintf(_("This is an oversized transaction that requires a transaction fee of %s"), FormatMoney(nFeeRequired).c_str()));2053            else2054                Error(_("Transaction creation failed"));2055            return;2056        }20572058        // Transaction fee2059        if (!ThreadSafeAskFee(nFeeRequired, _("Sending..."), this))2060        {2061            Error(_("Transaction aborted"));2062            return;2063        }20642065        // Make sure we're still connected2066        CNode* pnode = ConnectNode(addr, 2 * 60 * 60);2067        if (!pnode)2068        {2069            Error(_("Lost connection, transaction cancelled"));2070            return;2071        }20722073        // Last chance to cancel2074        Sleep(50);2075        if (!Status())2076            return;2077        fCanCancel = false;2078        if (fAbort)2079        {2080            fCanCancel = true;2081            if (!Status())2082                return;2083            fCanCancel = false;2084        }2085        if (!Status(_("Sending payment...")))2086            return;20872088        // Commit2089        if (!CommitTransaction(wtx, key))2090        {2091            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."));2092            return;2093        }20942095        // Send payment tx to seller, with response going to OnReply3 via event handler2096        CWalletTx wtxSend = wtx;2097        wtxSend.fFromMe = false;2098        pnode->PushRequest("submitorder", wtxSend, SendingDialogOnReply3, this);20992100        Status(_("Waiting for confirmation..."));2101        MainFrameRepaint();2102    }2103}21042105void SendingDialogOnReply3(void* parg, CDataStream& vRecv)2106{2107    ((CSendingDialog*)parg)->OnReply3(vRecv);2108}21092110void CSendingDialog::OnReply3(CDataStream& vRecv)2111{2112    int nRet;2113    try2114    {2115        vRecv >> nRet;2116        if (nRet > 0)2117        {2118            Error(_("The payment was sent, but the recipient was unable to verify it.\n"2119                    "The transaction is recorded and will credit to the recipient,\n"2120                    "but the comment information will be blank."));2121            return;2122        }2123    }2124    catch (...)2125    {2126        //// what do we want to do about this?2127        Error(_("Payment was sent, but an invalid response was received"));2128        return;2129    }21302131    fSuccess = true;2132    fWorkDone = true;2133    Status(_("Payment completed"));2134}2135213621372138213921402141//////////////////////////////////////////////////////////////////////////////2142//2143// CAddressBookDialog2144//21452146CAddressBookDialog::CAddressBookDialog(wxWindow* parent, const wxString& strInitSelected, int nPageIn, bool fDuringSendIn) : CAddressBookDialogBase(parent)2147{2148    // Set initially selected page2149    wxNotebookEvent event;2150    event.SetSelection(nPageIn);2151    OnNotebookPageChanged(event);2152    m_notebook->ChangeSelection(nPageIn);21532154    fDuringSend = fDuringSendIn;2155    if (!fDuringSend)2156        m_buttonCancel->Show(false);21572158    // Set Icon2159    wxIcon iconAddressBook;2160    iconAddressBook.CopyFromBitmap(wxBitmap(addressbook16_xpm));2161    SetIcon(iconAddressBook);21622163    // Init column headers2164    m_listCtrlSending->InsertColumn(0, _("Name"), wxLIST_FORMAT_LEFT, 200);2165    m_listCtrlSending->InsertColumn(1, _("Address"), wxLIST_FORMAT_LEFT, 350);2166    m_listCtrlSending->SetFocus();2167    m_listCtrlReceiving->InsertColumn(0, _("Label"), wxLIST_FORMAT_LEFT, 200);2168    m_listCtrlReceiving->InsertColumn(1, _("Bitcoin Address"), wxLIST_FORMAT_LEFT, 350);2169    m_listCtrlReceiving->SetFocus();21702171    // Fill listctrl with address book data2172    CRITICAL_BLOCK(cs_mapKeys)2173    CRITICAL_BLOCK(cs_mapAddressBook)2174    {2175        string strDefaultReceiving = (string)pframeMain->m_textCtrlAddress->GetValue();2176        foreach(const PAIRTYPE(string, string)& item, mapAddressBook)2177        {2178            string strAddress = item.first;2179            string strName = item.second;2180            uint160 hash160;2181            bool fMine = (AddressToHash160(strAddress, hash160) && mapPubKeys.count(hash160));2182            wxListCtrl* plistCtrl = fMine ? m_listCtrlReceiving : m_listCtrlSending;2183            int nIndex = InsertLine(plistCtrl, strName, strAddress);2184            if (strAddress == (fMine ? strDefaultReceiving : string(strInitSelected)))2185                plistCtrl->SetItemState(nIndex, wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED, wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED);2186        }2187    }2188}21892190wxString CAddressBookDialog::GetSelectedAddress()2191{2192    int nIndex = GetSelection(m_listCtrl);2193    if (nIndex == -1)2194        return "";2195    return GetItemText(m_listCtrl, nIndex, 1);2196}21972198wxString CAddressBookDialog::GetSelectedSendingAddress()2199{2200    int nIndex = GetSelection(m_listCtrlSending);2201    if (nIndex == -1)2202        return "";2203    return GetItemText(m_listCtrlSending, nIndex, 1);2204}22052206wxString CAddressBookDialog::GetSelectedReceivingAddress()2207{2208    int nIndex = GetSelection(m_listCtrlReceiving);2209    if (nIndex == -1)2210        return "";2211    return GetItemText(m_listCtrlReceiving, nIndex, 1);2212}22132214void CAddressBookDialog::OnNotebookPageChanged(wxNotebookEvent& event)2215{2216    event.Skip();2217    nPage = event.GetSelection();2218    if (nPage == SENDING)2219        m_listCtrl = m_listCtrlSending;2220    else if (nPage == RECEIVING)2221        m_listCtrl = m_listCtrlReceiving;2222    m_buttonDelete->Show(nPage == SENDING);2223    m_buttonCopy->Show(nPage == RECEIVING);2224    this->Layout();2225    m_listCtrl->SetFocus();2226}22272228void CAddressBookDialog::OnListEndLabelEdit(wxListEvent& event)2229{2230    // Update address book with edited name2231    event.Skip();2232    if (event.IsEditCancelled())2233        return;2234    string strAddress = (string)GetItemText(m_listCtrl, event.GetIndex(), 1);2235    SetAddressBookName(strAddress, string(event.GetText()));2236    pframeMain->RefreshListCtrl();2237}22382239void CAddressBookDialog::OnListItemSelected(wxListEvent& event)2240{2241    event.Skip();2242    if (nPage == RECEIVING)2243        SetDefaultReceivingAddress((string)GetSelectedReceivingAddress());2244}22452246void CAddressBookDialog::OnListItemActivated(wxListEvent& event)2247{2248    event.Skip();2249    if (fDuringSend)2250    {2251        // Doubleclick returns selection2252        EndModal(GetSelectedAddress() != "" ? 2 : 0);2253        return;2254    }22552256    // Doubleclick edits item2257    wxCommandEvent event2;2258    OnButtonEdit(event2);2259}22602261void CAddressBookDialog::OnButtonDelete(wxCommandEvent& event)2262{2263    if (nPage != SENDING)2264        return;2265    for (int nIndex = m_listCtrl->GetItemCount()-1; nIndex >= 0; nIndex--)2266    {2267        if (m_listCtrl->GetItemState(nIndex, wxLIST_STATE_SELECTED))2268        {2269            string strAddress = (string)GetItemText(m_listCtrl, nIndex, 1);2270            CWalletDB().EraseName(strAddress);2271            m_listCtrl->DeleteItem(nIndex);2272        }2273    }2274    pframeMain->RefreshListCtrl();2275}22762277void CAddressBookDialog::OnButtonCopy(wxCommandEvent& event)2278{2279    // Copy address box to clipboard2280    if (wxTheClipboard->Open())2281    {2282        wxTheClipboard->SetData(new wxTextDataObject(GetSelectedAddress()));2283        wxTheClipboard->Close();2284    }2285}22862287bool CAddressBookDialog::CheckIfMine(const string& strAddress, const string& strTitle)2288{2289    uint160 hash160;2290    bool fMine = (AddressToHash160(strAddress, hash160) && mapPubKeys.count(hash160));2291    if (fMine)2292        wxMessageBox(_("This is one of your own addresses for receiving payments and cannot be entered in the address book.  "), strTitle);2293    return fMine;2294}22952296void CAddressBookDialog::OnButtonEdit(wxCommandEvent& event)2297{2298    int nIndex = GetSelection(m_listCtrl);2299    if (nIndex == -1)2300        return;2301    string strName = (string)m_listCtrl->GetItemText(nIndex);2302    string strAddress = (string)GetItemText(m_listCtrl, nIndex, 1);2303    string strAddressOrg = strAddress;23042305    if (nPage == SENDING)2306    {2307        // Ask name and address2308        do2309        {2310            CGetTextFromUserDialog dialog(this, _("Edit Address"), _("Name"), strName, _("Address"), strAddress);2311            if (!dialog.ShowModal())2312                return;2313            strName = dialog.GetValue1();2314            strAddress = dialog.GetValue2();2315        }2316        while (CheckIfMine(strAddress, _("Edit Address")));23172318    }2319    else if (nPage == RECEIVING)2320    {2321        // Ask name2322        CGetTextFromUserDialog dialog(this, _("Edit Address Label"), _("Label"), strName);2323        if (!dialog.ShowModal())2324            return;2325        strName = dialog.GetValue();2326    }23272328    // Write back2329    if (strAddress != strAddressOrg)2330        CWalletDB().EraseName(strAddressOrg);2331    SetAddressBookName(strAddress, strName);2332    m_listCtrl->SetItem(nIndex, 1, strAddress);2333    m_listCtrl->SetItemText(nIndex, strName);2334    pframeMain->RefreshListCtrl();2335}23362337void CAddressBookDialog::OnButtonNew(wxCommandEvent& event)2338{2339    string strName;2340    string strAddress;23412342    if (nPage == SENDING)2343    {2344        // Ask name and address2345        do2346        {2347            CGetTextFromUserDialog dialog(this, _("Add Address"), _("Name"), strName, _("Address"), strAddress);2348            if (!dialog.ShowModal())2349                return;2350            strName = dialog.GetValue1();2351            strAddress = dialog.GetValue2();2352        }2353        while (CheckIfMine(strAddress, _("Add Address")));2354    }2355    else if (nPage == RECEIVING)2356    {2357        // Ask name2358        CGetTextFromUserDialog dialog(this,2359            _("New Receiving Address"),2360            _("It's good policy to use a new address for each payment you receive.\n\nLabel"),2361            "");2362        if (!dialog.ShowModal())2363            return;2364        strName = dialog.GetValue();23652366        // Generate new key2367        strAddress = PubKeyToAddress(GenerateNewKey());2368    }23692370    // Add to list and select it2371    SetAddressBookName(strAddress, strName);2372    int nIndex = InsertLine(m_listCtrl, strName, strAddress);2373    SetSelection(m_listCtrl, nIndex);2374    m_listCtrl->SetFocus();2375    if (nPage == SENDING)2376        pframeMain->RefreshListCtrl();2377}23782379void CAddressBookDialog::OnButtonOK(wxCommandEvent& event)2380{2381    // OK2382    EndModal(GetSelectedAddress() != "" ? 1 : 0);2383}23842385void CAddressBookDialog::OnButtonCancel(wxCommandEvent& event)2386{2387    // Cancel2388    EndModal(0);2389}23902391void CAddressBookDialog::OnClose(wxCloseEvent& event)2392{2393    // Close2394    EndModal(0);2395}2396239723982399240024012402//////////////////////////////////////////////////////////////////////////////2403//2404// CMyTaskBarIcon2405//24062407enum2408{2409    ID_TASKBAR_RESTORE = 10001,2410    ID_TASKBAR_OPTIONS,2411    ID_TASKBAR_GENERATE,2412    ID_TASKBAR_EXIT,2413};24142415BEGIN_EVENT_TABLE(CMyTaskBarIcon, wxTaskBarIcon)2416    EVT_TASKBAR_LEFT_DCLICK(CMyTaskBarIcon::OnLeftButtonDClick)2417    EVT_MENU(ID_TASKBAR_RESTORE, CMyTaskBarIcon::OnMenuRestore)2418    EVT_MENU(ID_TASKBAR_OPTIONS, CMyTaskBarIcon::OnMenuOptions)2419    EVT_MENU(ID_TASKBAR_GENERATE, CMyTaskBarIcon::OnMenuGenerate)2420    EVT_UPDATE_UI(ID_TASKBAR_GENERATE, CMyTaskBarIcon::OnUpdateUIGenerate)2421    EVT_MENU(ID_TASKBAR_EXIT, CMyTaskBarIcon::OnMenuExit)2422END_EVENT_TABLE()24232424void CMyTaskBarIcon::Show(bool fShow)2425{2426    static char pszPrevTip[200];2427    if (fShow)2428    {2429        string strTooltip = _("Bitcoin");2430        if (fGenerateBitcoins)2431            strTooltip = _("Bitcoin - Generating");2432        if (fGenerateBitcoins && vNodes.empty())2433            strTooltip = _("Bitcoin - (not connected)");24342435        // Optimization, only update when changed, using char array to be reentrant2436        if (strncmp(pszPrevTip, strTooltip.c_str(), sizeof(pszPrevTip)-1) != 0)2437        {2438            strlcpy(pszPrevTip, strTooltip.c_str(), sizeof(pszPrevTip));2439#ifdef __WXMSW__2440            // somehow it'll choose the wrong size and scale it down if2441            // we use the main icon, so we hand it one with only 16x162442            SetIcon(wxICON(favicon), strTooltip);2443#else2444            SetIcon(bitcoin80_xpm, strTooltip);2445#endif2446        }2447    }2448    else2449    {2450        strlcpy(pszPrevTip, "", sizeof(pszPrevTip));2451        RemoveIcon();2452    }2453}24542455void CMyTaskBarIcon::Hide()2456{2457    Show(false);2458}24592460void CMyTaskBarIcon::OnLeftButtonDClick(wxTaskBarIconEvent& event)2461{2462    Restore();2463}24642465void CMyTaskBarIcon::OnMenuRestore(wxCommandEvent& event)2466{2467    Restore();2468}24692470void CMyTaskBarIcon::OnMenuOptions(wxCommandEvent& event)2471{2472    // Since it's modal, get the main window to do it2473    wxCommandEvent event2(wxEVT_COMMAND_MENU_SELECTED, wxID_PREFERENCES);2474    pframeMain->GetEventHandler()->AddPendingEvent(event2);2475}24762477void CMyTaskBarIcon::Restore()2478{2479    pframeMain->Show();2480    wxIconizeEvent event(0, false);2481    pframeMain->GetEventHandler()->AddPendingEvent(event);2482    pframeMain->Iconize(false);2483    pframeMain->Raise();2484}24852486void CMyTaskBarIcon::OnMenuGenerate(wxCommandEvent& event)2487{2488    GenerateBitcoins(event.IsChecked());2489}24902491void CMyTaskBarIcon::OnUpdateUIGenerate(wxUpdateUIEvent& event)2492{2493    event.Check(fGenerateBitcoins);2494}24952496void CMyTaskBarIcon::OnMenuExit(wxCommandEvent& event)2497{2498    pframeMain->Close(true);2499}25002501void CMyTaskBarIcon::UpdateTooltip()2502{2503    if (IsIconInstalled())2504        Show(true);2505}25062507wxMenu* CMyTaskBarIcon::CreatePopupMenu()2508{2509    wxMenu* pmenu = new wxMenu;2510    pmenu->Append(ID_TASKBAR_RESTORE, _("&Open Bitcoin"));2511    pmenu->Append(ID_TASKBAR_OPTIONS, _("O&ptions..."));2512    pmenu->AppendCheckItem(ID_TASKBAR_GENERATE, _("&Generate Coins"))->Check(fGenerateBitcoins);2513#ifndef __WXMAC_OSX__ // Mac has built-in quit menu2514    pmenu->AppendSeparator();2515    pmenu->Append(ID_TASKBAR_EXIT, _("E&xit"));2516#endif2517    return pmenu;2518}25192520252125222523252425252526252725282529253025312532void CreateMainWindow()2533{2534    pframeMain = new CMainFrame(NULL);2535    if (mapArgs.count("-min"))2536        pframeMain->Iconize(true);2537    pframeMain->Show(true);  // have to show first to get taskbar button to hide2538    if (fMinimizeToTray && pframeMain->IsIconized())2539        fClosedToTray = true;2540    pframeMain->Show(!fClosedToTray);2541    ptaskbaricon->Show(fMinimizeToTray || fClosedToTray);2542    CreateThread(ThreadDelayedRepaint, NULL);2543}

Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.

0:000:00