Merge pull request #1025 from Diapolo/GUI-BlockDL
[novacoin.git] / src / qt / bitcoingui.cpp
1 /*
2  * Qt4 bitcoin GUI.
3  *
4  * W.J. van der Laan 20011-2012
5  * The Bitcoin Developers 20011-2012
6  */
7 #include "bitcoingui.h"
8 #include "transactiontablemodel.h"
9 #include "addressbookpage.h"
10 #include "sendcoinsdialog.h"
11 #include "messagepage.h"
12 #include "optionsdialog.h"
13 #include "aboutdialog.h"
14 #include "clientmodel.h"
15 #include "walletmodel.h"
16 #include "editaddressdialog.h"
17 #include "optionsmodel.h"
18 #include "transactiondescdialog.h"
19 #include "addresstablemodel.h"
20 #include "transactionview.h"
21 #include "overviewpage.h"
22 #include "bitcoinunits.h"
23 #include "guiconstants.h"
24 #include "askpassphrasedialog.h"
25 #include "notificator.h"
26
27 #ifdef Q_WS_MAC
28 #include "macdockiconhandler.h"
29 #endif
30
31 #include <QApplication>
32 #include <QMainWindow>
33 #include <QMenuBar>
34 #include <QMenu>
35 #include <QIcon>
36 #include <QTabWidget>
37 #include <QVBoxLayout>
38 #include <QToolBar>
39 #include <QStatusBar>
40 #include <QLabel>
41 #include <QLineEdit>
42 #include <QPushButton>
43 #include <QLocale>
44 #include <QMessageBox>
45 #include <QProgressBar>
46 #include <QStackedWidget>
47 #include <QDateTime>
48 #include <QMovie>
49 #include <QFileDialog>
50 #include <QDesktopServices>
51 #include <QTimer>
52
53 #include <QDragEnterEvent>
54 #include <QUrl>
55
56 #include <iostream>
57
58 BitcoinGUI::BitcoinGUI(QWidget *parent):
59     QMainWindow(parent),
60     clientModel(0),
61     walletModel(0),
62     encryptWalletAction(0),
63     changePassphraseAction(0),
64     aboutQtAction(0),
65     trayIcon(0),
66     notificator(0)
67 {
68     resize(850, 550);
69     setWindowTitle(tr("Bitcoin Wallet"));
70 #ifndef Q_WS_MAC
71     setWindowIcon(QIcon(":icons/bitcoin"));
72 #else
73     setUnifiedTitleAndToolBarOnMac(true);
74     QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
75 #endif
76     // Accept D&D of URIs
77     setAcceptDrops(true);
78
79     // Create actions for the toolbar, menu bar and tray/dock icon
80     createActions();
81
82     // Create application menu bar
83     createMenuBar();
84
85     // Create the toolbars
86     createToolBars();
87
88     // Create the tray icon (or setup the dock icon)
89     createTrayIcon();
90
91     // Create tabs
92     overviewPage = new OverviewPage();
93
94     transactionsPage = new QWidget(this);
95     QVBoxLayout *vbox = new QVBoxLayout();
96     transactionView = new TransactionView(this);
97     vbox->addWidget(transactionView);
98     transactionsPage->setLayout(vbox);
99
100     addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab);
101
102     receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab);
103
104     sendCoinsPage = new SendCoinsDialog(this);
105
106     messagePage = new MessagePage(this);
107
108     centralWidget = new QStackedWidget(this);
109     centralWidget->addWidget(overviewPage);
110     centralWidget->addWidget(transactionsPage);
111     centralWidget->addWidget(addressBookPage);
112     centralWidget->addWidget(receiveCoinsPage);
113     centralWidget->addWidget(sendCoinsPage);
114 #ifdef FIRST_CLASS_MESSAGING
115     centralWidget->addWidget(messagePage);
116 #endif
117     setCentralWidget(centralWidget);
118
119     // Create status bar
120     statusBar();
121
122     // Status bar notification icons
123     QFrame *frameBlocks = new QFrame();
124     frameBlocks->setContentsMargins(0,0,0,0);
125     frameBlocks->setMinimumWidth(56);
126     frameBlocks->setMaximumWidth(56);
127     QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);
128     frameBlocksLayout->setContentsMargins(3,0,3,0);
129     frameBlocksLayout->setSpacing(3);
130     labelEncryptionIcon = new QLabel();
131     labelConnectionsIcon = new QLabel();
132     labelBlocksIcon = new QLabel();
133     frameBlocksLayout->addStretch();
134     frameBlocksLayout->addWidget(labelEncryptionIcon);
135     frameBlocksLayout->addStretch();
136     frameBlocksLayout->addWidget(labelConnectionsIcon);
137     frameBlocksLayout->addStretch();
138     frameBlocksLayout->addWidget(labelBlocksIcon);
139     frameBlocksLayout->addStretch();
140
141     // Progress bar and label for blocks download
142     progressBarLabel = new QLabel();
143     progressBarLabel->setVisible(false);
144     progressBar = new QProgressBar();
145     progressBar->setVisible(false);
146
147     statusBar()->addWidget(progressBarLabel);
148     statusBar()->addWidget(progressBar);
149     statusBar()->addPermanentWidget(frameBlocks);
150
151     // define OS independent progress bar style (has to be placed after addWidget(), otherwise we crash)
152     // we did this, because with some OSes default style, text on the progress bar is unreadable
153     progressBar->setStyleSheet("QProgressBar { background-color: transparent; border: 1px solid grey; border-radius: 2px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); margin: 0px; }");
154
155     syncIconMovie = new QMovie(":/movies/update_spinner", "mng", this);
156
157     // Clicking on a transaction on the overview page simply sends you to transaction history page
158     connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage()));
159
160     // Doubleclicking on a transaction on the transaction history page shows details
161     connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));
162
163     gotoOverviewPage();
164 }
165
166 BitcoinGUI::~BitcoinGUI()
167 {
168     if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu)
169         trayIcon->hide();
170 #ifdef Q_WS_MAC
171     delete appMenuBar;
172 #endif
173 }
174
175 void BitcoinGUI::createActions()
176 {
177     QActionGroup *tabGroup = new QActionGroup(this);
178
179     overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this);
180     overviewAction->setToolTip(tr("Show general overview of wallet"));
181     overviewAction->setCheckable(true);
182     overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));
183     tabGroup->addAction(overviewAction);
184
185     historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this);
186     historyAction->setToolTip(tr("Browse transaction history"));
187     historyAction->setCheckable(true);
188     historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));
189     tabGroup->addAction(historyAction);
190
191     addressBookAction = new QAction(QIcon(":/icons/address-book"), tr("&Address Book"), this);
192     addressBookAction->setToolTip(tr("Edit the list of stored addresses and labels"));
193     addressBookAction->setCheckable(true);
194     addressBookAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5));
195     tabGroup->addAction(addressBookAction);
196
197     receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive coins"), this);
198     receiveCoinsAction->setToolTip(tr("Show the list of addresses for receiving payments"));
199     receiveCoinsAction->setCheckable(true);
200     receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));
201     tabGroup->addAction(receiveCoinsAction);
202
203     sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send coins"), this);
204     sendCoinsAction->setToolTip(tr("Send coins to a bitcoin address"));
205     sendCoinsAction->setCheckable(true);
206     sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));
207     tabGroup->addAction(sendCoinsAction);
208
209     messageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message"), this);
210     messageAction->setToolTip(tr("Prove you control an address"));
211 #ifdef FIRST_CLASS_MESSAGING
212     messageAction->setCheckable(true);
213 #endif
214     tabGroup->addAction(messageAction);
215
216     connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
217     connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
218     connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
219     connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));
220     connect(addressBookAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
221     connect(addressBookAction, SIGNAL(triggered()), this, SLOT(gotoAddressBookPage()));
222     connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
223     connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
224     connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
225     connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
226     connect(messageAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
227     connect(messageAction, SIGNAL(triggered()), this, SLOT(gotoMessagePage()));
228
229     quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this);
230     quitAction->setToolTip(tr("Quit application"));
231     quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
232     quitAction->setMenuRole(QAction::QuitRole);
233     aboutAction = new QAction(QIcon(":/icons/bitcoin"), tr("&About %1").arg(qApp->applicationName()), this);
234     aboutAction->setToolTip(tr("Show information about Bitcoin"));
235     aboutAction->setMenuRole(QAction::AboutRole);
236     aboutQtAction = new QAction(tr("About &Qt"), this);
237     aboutQtAction->setToolTip(tr("Show information about Qt"));
238     aboutQtAction->setMenuRole(QAction::AboutQtRole);
239     optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this);
240     optionsAction->setToolTip(tr("Modify configuration options for bitcoin"));
241     optionsAction->setMenuRole(QAction::PreferencesRole);
242     openBitcoinAction = new QAction(QIcon(":/icons/bitcoin"), tr("Open &Bitcoin"), this);
243     openBitcoinAction->setToolTip(tr("Show the Bitcoin window"));
244     exportAction = new QAction(QIcon(":/icons/export"), tr("&Export..."), this);
245     exportAction->setToolTip(tr("Export the data in the current tab to a file"));
246     encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet"), this);
247     encryptWalletAction->setToolTip(tr("Encrypt or decrypt wallet"));
248     encryptWalletAction->setCheckable(true);
249     backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet"), this);
250     backupWalletAction->setToolTip(tr("Backup wallet to another location"));
251     changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase"), this);
252     changePassphraseAction->setToolTip(tr("Change the passphrase used for wallet encryption"));
253
254     connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
255     connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
256     connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
257     connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
258     connect(openBitcoinAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
259     connect(encryptWalletAction, SIGNAL(triggered(bool)), this, SLOT(encryptWallet(bool)));
260     connect(backupWalletAction, SIGNAL(triggered()), this, SLOT(backupWallet()));
261     connect(changePassphraseAction, SIGNAL(triggered()), this, SLOT(changePassphrase()));
262 }
263
264 void BitcoinGUI::createMenuBar()
265 {
266 #ifdef Q_WS_MAC
267     // Create a decoupled menu bar on Mac which stays even if the window is closed
268     appMenuBar = new QMenuBar();
269 #else
270     // Get the main window's menu bar on other platforms
271     appMenuBar = menuBar();
272 #endif
273
274     // Configure the menus
275     QMenu *file = appMenuBar->addMenu(tr("&File"));
276     file->addAction(backupWalletAction);
277     file->addAction(exportAction);
278 #ifndef FIRST_CLASS_MESSAGING
279     file->addAction(messageAction);
280 #endif
281     file->addSeparator();
282     file->addAction(quitAction);
283
284     QMenu *settings = appMenuBar->addMenu(tr("&Settings"));
285     settings->addAction(encryptWalletAction);
286     settings->addAction(changePassphraseAction);
287     settings->addSeparator();
288     settings->addAction(optionsAction);
289
290     QMenu *help = appMenuBar->addMenu(tr("&Help"));
291     help->addAction(aboutAction);
292     help->addAction(aboutQtAction);
293 }
294
295 void BitcoinGUI::createToolBars()
296 {
297     QToolBar *toolbar = addToolBar(tr("Tabs toolbar"));
298     toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
299     toolbar->addAction(overviewAction);
300     toolbar->addAction(sendCoinsAction);
301     toolbar->addAction(receiveCoinsAction);
302     toolbar->addAction(historyAction);
303     toolbar->addAction(addressBookAction);
304 #ifdef FIRST_CLASS_MESSAGING
305     toolbar->addAction(messageAction);
306 #endif
307
308     QToolBar *toolbar2 = addToolBar(tr("Actions toolbar"));
309     toolbar2->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
310     toolbar2->addAction(exportAction);
311 }
312
313 void BitcoinGUI::setClientModel(ClientModel *clientModel)
314 {
315     this->clientModel = clientModel;
316     if(clientModel)
317     {
318         if(clientModel->isTestNet())
319         {
320             QString title_testnet = windowTitle() + QString(" ") + tr("[testnet]");
321             setWindowTitle(title_testnet);
322 #ifndef Q_WS_MAC
323             setWindowIcon(QIcon(":icons/bitcoin_testnet"));
324 #else
325             MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet"));
326 #endif
327             if(trayIcon)
328             {
329                 trayIcon->setToolTip(title_testnet);
330                 trayIcon->setIcon(QIcon(":/icons/toolbar_testnet"));
331             }
332         }
333
334         // Keep up to date with client
335         setNumConnections(clientModel->getNumConnections());
336         connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
337
338         setNumBlocks(clientModel->getNumBlocks());
339         connect(clientModel, SIGNAL(numBlocksChanged(int)), this, SLOT(setNumBlocks(int)));
340
341         // Report errors from network/worker thread
342         connect(clientModel, SIGNAL(error(QString,QString)), this, SLOT(error(QString,QString)));
343     }
344 }
345
346 void BitcoinGUI::setWalletModel(WalletModel *walletModel)
347 {
348     this->walletModel = walletModel;
349     if(walletModel)
350     {
351         // Report errors from wallet thread
352         connect(walletModel, SIGNAL(error(QString,QString)), this, SLOT(error(QString,QString)));
353
354         // Put transaction list in tabs
355         transactionView->setModel(walletModel);
356
357         overviewPage->setModel(walletModel);
358         addressBookPage->setModel(walletModel->getAddressTableModel());
359         receiveCoinsPage->setModel(walletModel->getAddressTableModel());
360         sendCoinsPage->setModel(walletModel);
361         messagePage->setModel(walletModel);
362
363         setEncryptionStatus(walletModel->getEncryptionStatus());
364         connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SLOT(setEncryptionStatus(int)));
365
366         // Balloon popup for new transaction
367         connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
368                 this, SLOT(incomingTransaction(QModelIndex,int,int)));
369
370         // Ask for passphrase if needed
371         connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet()));
372     }
373 }
374
375 void BitcoinGUI::createTrayIcon()
376 {
377     QMenu *trayIconMenu;
378 #ifndef Q_WS_MAC
379     trayIcon = new QSystemTrayIcon(this);
380     trayIconMenu = new QMenu(this);
381     trayIcon->setContextMenu(trayIconMenu);
382     trayIcon->setToolTip(tr("Bitcoin client"));
383     trayIcon->setIcon(QIcon(":/icons/toolbar"));
384     connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
385             this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
386     trayIcon->show();
387 #else
388     // Note: On Mac, the dock icon is used to provide the tray's functionality.
389     MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance();
390     connect(dockIconHandler, SIGNAL(dockIconClicked()), openBitcoinAction, SLOT(trigger()));
391     trayIconMenu = dockIconHandler->dockMenu();
392 #endif
393
394     // Configuration of the tray icon (or dock icon) icon menu
395     trayIconMenu->addAction(openBitcoinAction);
396     trayIconMenu->addSeparator();
397     trayIconMenu->addAction(messageAction);
398 #ifndef FIRST_CLASS_MESSAGING
399     trayIconMenu->addSeparator();
400 #endif
401     trayIconMenu->addAction(receiveCoinsAction);
402     trayIconMenu->addAction(sendCoinsAction);
403     trayIconMenu->addSeparator();
404     trayIconMenu->addAction(optionsAction);
405 #ifndef Q_WS_MAC // This is built-in on Mac
406     trayIconMenu->addSeparator();
407     trayIconMenu->addAction(quitAction);
408 #endif
409
410     notificator = new Notificator(tr("bitcoin-qt"), trayIcon);
411 }
412
413 #ifndef Q_WS_MAC
414 void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
415 {
416     if(reason == QSystemTrayIcon::Trigger)
417     {
418         // Click on system tray icon triggers "open bitcoin"
419         openBitcoinAction->trigger();
420     }
421 }
422 #endif
423
424 void BitcoinGUI::optionsClicked()
425 {
426     if(!clientModel || !clientModel->getOptionsModel())
427         return;
428     OptionsDialog dlg;
429     dlg.setModel(clientModel->getOptionsModel());
430     dlg.exec();
431 }
432
433 void BitcoinGUI::aboutClicked()
434 {
435     AboutDialog dlg;
436     dlg.setModel(clientModel);
437     dlg.exec();
438 }
439
440 void BitcoinGUI::setNumConnections(int count)
441 {
442     QString icon;
443     switch(count)
444     {
445     case 0: icon = ":/icons/connect_0"; break;
446     case 1: case 2: case 3: icon = ":/icons/connect_1"; break;
447     case 4: case 5: case 6: icon = ":/icons/connect_2"; break;
448     case 7: case 8: case 9: icon = ":/icons/connect_3"; break;
449     default: icon = ":/icons/connect_4"; break;
450     }
451     labelConnectionsIcon->setPixmap(QIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
452     labelConnectionsIcon->setToolTip(tr("%n active connection(s) to Bitcoin network", "", count));
453 }
454
455 void BitcoinGUI::setNumBlocks(int count)
456 {
457     // don't show / hide progressBar and it's label if we have no connection(s) to the network
458     if (!clientModel || clientModel->getNumConnections() == 0)
459     {
460         progressBarLabel->setVisible(false);
461         progressBar->setVisible(false);
462
463         return;
464     }
465
466     int nTotalBlocks = clientModel->getNumBlocksOfPeers();
467     QString tooltip;
468
469     if(count < nTotalBlocks)
470     {
471         int nRemainingBlocks = nTotalBlocks - count;
472         float nPercentageDone = count / (nTotalBlocks * 0.01f);
473
474         if (clientModel->getStatusBarWarnings() == "")
475         {
476             progressBarLabel->setText(tr("Synchronizing with network..."));
477             progressBarLabel->setVisible(true);
478             progressBar->setFormat(tr("~%n block(s) remaining", "", nRemainingBlocks));
479             progressBar->setMaximum(nTotalBlocks);
480             progressBar->setValue(count);
481             progressBar->setVisible(true);
482         }
483         else
484         {
485             progressBarLabel->setText(clientModel->getStatusBarWarnings());
486             progressBarLabel->setVisible(true);
487             progressBar->setVisible(false);
488         }
489         tooltip = tr("Downloaded %1 of %2 blocks of transaction history (%3% done).").arg(count).arg(nTotalBlocks).arg(nPercentageDone, 0, 'f', 2);
490     }
491     else
492     {
493         if (clientModel->getStatusBarWarnings() == "")
494             progressBarLabel->setVisible(false);
495         else
496         {
497             progressBarLabel->setText(clientModel->getStatusBarWarnings());
498             progressBarLabel->setVisible(true);
499         }
500         progressBar->setVisible(false);
501         tooltip = tr("Downloaded %1 blocks of transaction history.").arg(count);
502     }
503
504     QDateTime now = QDateTime::currentDateTime();
505     QDateTime lastBlockDate = clientModel->getLastBlockDate();
506     int secs = lastBlockDate.secsTo(now);
507     QString text;
508
509     // Represent time from last generated block in human readable text
510     if(secs <= 0)
511     {
512         // Fully up to date. Leave text empty.
513     }
514     else if(secs < 60)
515     {
516         text = tr("%n second(s) ago","",secs);
517     }
518     else if(secs < 60*60)
519     {
520         text = tr("%n minute(s) ago","",secs/60);
521     }
522     else if(secs < 24*60*60)
523     {
524         text = tr("%n hour(s) ago","",secs/(60*60));
525     }
526     else
527     {
528         text = tr("%n day(s) ago","",secs/(60*60*24));
529     }
530
531     // Set icon state: spinning if catching up, tick otherwise
532     if(secs < 90*60)
533     {
534         tooltip = tr("Up to date") + QString(".\n") + tooltip;
535         labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
536     }
537     else
538     {
539         tooltip = tr("Catching up...") + QString("\n") + tooltip;
540         labelBlocksIcon->setMovie(syncIconMovie);
541         syncIconMovie->start();
542     }
543
544     if(!text.isEmpty())
545     {
546         tooltip += QString("\n");
547         tooltip += tr("Last received block was generated %1.").arg(text);
548     }
549
550     labelBlocksIcon->setToolTip(tooltip);
551     progressBarLabel->setToolTip(tooltip);
552     progressBar->setToolTip(tooltip);
553 }
554
555 void BitcoinGUI::refreshStatusBar()
556 {
557     /* Might display multiple times in the case of multiple alerts
558     static QString prevStatusBar;
559     QString newStatusBar = clientModel->getStatusBarWarnings();
560     if (prevStatusBar != newStatusBar)
561     {
562         prevStatusBar = newStatusBar;
563         error(tr("Network Alert"), newStatusBar);
564     }*/
565     setNumBlocks(clientModel->getNumBlocks());
566 }
567
568 void BitcoinGUI::error(const QString &title, const QString &message)
569 {
570     // Report errors from network/worker thread
571     notificator->notify(Notificator::Critical, title, message);
572 }
573
574 void BitcoinGUI::changeEvent(QEvent *e)
575 {
576     QMainWindow::changeEvent(e);
577 #ifndef Q_WS_MAC // Ignored on Mac
578     if(e->type() == QEvent::WindowStateChange)
579     {
580         if(clientModel && clientModel->getOptionsModel()->getMinimizeToTray())
581         {
582             QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e);
583             if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized())
584             {
585                 QTimer::singleShot(0, this, SLOT(hide()));
586                 e->ignore();
587             }
588         }
589     }
590 #endif
591 }
592
593 void BitcoinGUI::closeEvent(QCloseEvent *event)
594 {
595     if(clientModel)
596     {
597 #ifndef Q_WS_MAC // Ignored on Mac
598         if(!clientModel->getOptionsModel()->getMinimizeToTray() &&
599            !clientModel->getOptionsModel()->getMinimizeOnClose())
600         {
601             qApp->quit();
602         }
603 #endif
604     }
605     QMainWindow::closeEvent(event);
606 }
607
608 void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee)
609 {
610     QString strMessage =
611         tr("This transaction is over the size limit.  You can still send it for a fee of %1, "
612           "which goes to the nodes that process your transaction and helps to support the network.  "
613           "Do you want to pay the fee?").arg(
614                 BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nFeeRequired));
615     QMessageBox::StandardButton retval = QMessageBox::question(
616           this, tr("Sending..."), strMessage,
617           QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes);
618     *payFee = (retval == QMessageBox::Yes);
619 }
620
621 void BitcoinGUI::incomingTransaction(const QModelIndex & parent, int start, int end)
622 {
623     if(!walletModel || !clientModel)
624         return;
625     TransactionTableModel *ttm = walletModel->getTransactionTableModel();
626     qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent)
627                     .data(Qt::EditRole).toULongLong();
628     if(!clientModel->inInitialBlockDownload())
629     {
630         // On new transaction, make an info balloon
631         // Unless the initial block download is in progress, to prevent balloon-spam
632         QString date = ttm->index(start, TransactionTableModel::Date, parent)
633                         .data().toString();
634         QString type = ttm->index(start, TransactionTableModel::Type, parent)
635                         .data().toString();
636         QString address = ttm->index(start, TransactionTableModel::ToAddress, parent)
637                         .data().toString();
638         QIcon icon = qvariant_cast<QIcon>(ttm->index(start,
639                             TransactionTableModel::ToAddress, parent)
640                         .data(Qt::DecorationRole));
641
642         notificator->notify(Notificator::Information,
643                             (amount)<0 ? tr("Sent transaction") :
644                                          tr("Incoming transaction"),
645                               tr("Date: %1\n"
646                                  "Amount: %2\n"
647                                  "Type: %3\n"
648                                  "Address: %4\n")
649                               .arg(date)
650                               .arg(BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), amount, true))
651                               .arg(type)
652                               .arg(address), icon);
653     }
654 }
655
656 void BitcoinGUI::gotoOverviewPage()
657 {
658     overviewAction->setChecked(true);
659     centralWidget->setCurrentWidget(overviewPage);
660
661     exportAction->setEnabled(false);
662     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
663 }
664
665 void BitcoinGUI::gotoHistoryPage()
666 {
667     historyAction->setChecked(true);
668     centralWidget->setCurrentWidget(transactionsPage);
669
670     exportAction->setEnabled(true);
671     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
672     connect(exportAction, SIGNAL(triggered()), transactionView, SLOT(exportClicked()));
673 }
674
675 void BitcoinGUI::gotoAddressBookPage()
676 {
677     addressBookAction->setChecked(true);
678     centralWidget->setCurrentWidget(addressBookPage);
679
680     exportAction->setEnabled(true);
681     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
682     connect(exportAction, SIGNAL(triggered()), addressBookPage, SLOT(exportClicked()));
683 }
684
685 void BitcoinGUI::gotoReceiveCoinsPage()
686 {
687     receiveCoinsAction->setChecked(true);
688     centralWidget->setCurrentWidget(receiveCoinsPage);
689
690     exportAction->setEnabled(true);
691     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
692     connect(exportAction, SIGNAL(triggered()), receiveCoinsPage, SLOT(exportClicked()));
693 }
694
695 void BitcoinGUI::gotoSendCoinsPage()
696 {
697     sendCoinsAction->setChecked(true);
698     centralWidget->setCurrentWidget(sendCoinsPage);
699
700     exportAction->setEnabled(false);
701     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
702 }
703
704 void BitcoinGUI::gotoMessagePage()
705 {
706 #ifdef FIRST_CLASS_MESSAGING
707     messageAction->setChecked(true);
708     centralWidget->setCurrentWidget(messagePage);
709
710     exportAction->setEnabled(false);
711     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
712 #else
713     messagePage->show();
714     messagePage->setFocus();
715 #endif
716 }
717
718 void BitcoinGUI::gotoMessagePage(QString addr)
719 {
720     gotoMessagePage();
721     messagePage->setAddress(addr);
722 }
723
724 void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event)
725 {
726     // Accept only URLs
727     if(event->mimeData()->hasUrls())
728         event->acceptProposedAction();
729 }
730
731 void BitcoinGUI::dropEvent(QDropEvent *event)
732 {
733     if(event->mimeData()->hasUrls())
734     {
735         gotoSendCoinsPage();
736         QList<QUrl> urls = event->mimeData()->urls();
737         foreach(const QUrl &url, urls)
738         {
739             sendCoinsPage->handleURL(url.toString());
740         }
741     }
742
743     event->acceptProposedAction();
744 }
745
746 void BitcoinGUI::handleURL(QString strURL)
747 {
748     gotoSendCoinsPage();
749     sendCoinsPage->handleURL(strURL);
750
751     if(!isActiveWindow())
752         activateWindow();
753
754     showNormalIfMinimized();
755 }
756
757 void BitcoinGUI::setEncryptionStatus(int status)
758 {
759     switch(status)
760     {
761     case WalletModel::Unencrypted:
762         labelEncryptionIcon->hide();
763         encryptWalletAction->setChecked(false);
764         changePassphraseAction->setEnabled(false);
765         encryptWalletAction->setEnabled(true);
766         break;
767     case WalletModel::Unlocked:
768         labelEncryptionIcon->show();
769         labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
770         labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>"));
771         encryptWalletAction->setChecked(true);
772         changePassphraseAction->setEnabled(true);
773         encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
774         break;
775     case WalletModel::Locked:
776         labelEncryptionIcon->show();
777         labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
778         labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>"));
779         encryptWalletAction->setChecked(true);
780         changePassphraseAction->setEnabled(true);
781         encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
782         break;
783     }
784 }
785
786 void BitcoinGUI::encryptWallet(bool status)
787 {
788     if(!walletModel)
789         return;
790     AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt:
791                                      AskPassphraseDialog::Decrypt, this);
792     dlg.setModel(walletModel);
793     dlg.exec();
794
795     setEncryptionStatus(walletModel->getEncryptionStatus());
796 }
797
798 void BitcoinGUI::backupWallet()
799 {
800     QString saveDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
801     QString filename = QFileDialog::getSaveFileName(this, tr("Backup Wallet"), saveDir, tr("Wallet Data (*.dat)"));
802     if(!filename.isEmpty()) {
803         if(!walletModel->backupWallet(filename)) {
804             QMessageBox::warning(this, tr("Backup Failed"), tr("There was an error trying to save the wallet data to the new location."));
805         }
806     }
807 }
808
809 void BitcoinGUI::changePassphrase()
810 {
811     AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this);
812     dlg.setModel(walletModel);
813     dlg.exec();
814 }
815
816 void BitcoinGUI::unlockWallet()
817 {
818     if(!walletModel)
819         return;
820     // Unlock wallet when requested by wallet model
821     if(walletModel->getEncryptionStatus() == WalletModel::Locked)
822     {
823         AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, this);
824         dlg.setModel(walletModel);
825         dlg.exec();
826     }
827 }
828
829 void BitcoinGUI::showNormalIfMinimized()
830 {
831     if(!isVisible()) // Show, if hidden
832         show();
833     if(isMinimized()) // Unminimize, if minimized
834         showNormal();
835 }