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