Merge branch '0.5.x' into 0.6.0.x
[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
8 #include "checkpoints.h"
9
10 #include "bitcoingui.h"
11 #include "transactiontablemodel.h"
12 #include "addressbookpage.h"
13 #include "sendcoinsdialog.h"
14 #include "messagepage.h"
15 #include "optionsdialog.h"
16 #include "aboutdialog.h"
17 #include "clientmodel.h"
18 #include "walletmodel.h"
19 #include "editaddressdialog.h"
20 #include "optionsmodel.h"
21 #include "transactiondescdialog.h"
22 #include "addresstablemodel.h"
23 #include "transactionview.h"
24 #include "overviewpage.h"
25 #include "bitcoinunits.h"
26 #include "guiconstants.h"
27 #include "askpassphrasedialog.h"
28 #include "notificator.h"
29
30 #ifdef Q_WS_MAC
31 #include "macdockiconhandler.h"
32 #endif
33
34 #include <QApplication>
35 #include <QMainWindow>
36 #include <QMenuBar>
37 #include <QMenu>
38 #include <QIcon>
39 #include <QTabWidget>
40 #include <QVBoxLayout>
41 #include <QToolBar>
42 #include <QStatusBar>
43 #include <QLabel>
44 #include <QLineEdit>
45 #include <QPushButton>
46 #include <QLocale>
47 #include <QMessageBox>
48 #include <QProgressBar>
49 #include <QStackedWidget>
50 #include <QDateTime>
51 #include <QMovie>
52 #include <QFileDialog>
53 #include <QDesktopServices>
54 #include <QTimer>
55
56 #include <QDragEnterEvent>
57 #include <QUrl>
58
59 #include <iostream>
60
61 BitcoinGUI::BitcoinGUI(QWidget *parent):
62     QMainWindow(parent),
63     clientModel(0),
64     walletModel(0),
65     encryptWalletAction(0),
66     changePassphraseAction(0),
67     aboutQtAction(0),
68     trayIcon(0),
69     notificator(0)
70 {
71     resize(850, 550);
72     setWindowTitle(tr("Bitcoin Wallet"));
73 #ifndef Q_WS_MAC
74     setWindowIcon(QIcon(":icons/bitcoin"));
75 #else
76     setUnifiedTitleAndToolBarOnMac(true);
77     QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
78 #endif
79     // Accept D&D of URIs
80     setAcceptDrops(true);
81
82     // Create actions for the toolbar, menu bar and tray/dock icon
83     createActions();
84
85     // Create application menu bar
86     createMenuBar();
87
88     // Create the toolbars
89     createToolBars();
90
91     // Create the tray icon (or setup the dock icon)
92     createTrayIcon();
93
94     // Create tabs
95     overviewPage = new OverviewPage();
96
97     transactionsPage = new QWidget(this);
98     QVBoxLayout *vbox = new QVBoxLayout();
99     transactionView = new TransactionView(this);
100     vbox->addWidget(transactionView);
101     transactionsPage->setLayout(vbox);
102
103     addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab);
104
105     receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab);
106
107     sendCoinsPage = new SendCoinsDialog(this);
108
109     messagePage = new MessagePage(this);
110
111     centralWidget = new QStackedWidget(this);
112     centralWidget->addWidget(overviewPage);
113     centralWidget->addWidget(transactionsPage);
114     centralWidget->addWidget(addressBookPage);
115     centralWidget->addWidget(receiveCoinsPage);
116     centralWidget->addWidget(sendCoinsPage);
117 #ifdef FIRST_CLASS_MESSAGING
118     centralWidget->addWidget(messagePage);
119 #endif
120     setCentralWidget(centralWidget);
121
122     // Create status bar
123     statusBar();
124
125     // Status bar notification icons
126     QFrame *frameBlocks = new QFrame();
127     frameBlocks->setContentsMargins(0,0,0,0);
128     frameBlocks->setMinimumWidth(56);
129     frameBlocks->setMaximumWidth(56);
130     QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);
131     frameBlocksLayout->setContentsMargins(3,0,3,0);
132     frameBlocksLayout->setSpacing(3);
133     labelEncryptionIcon = new QLabel();
134     labelConnectionsIcon = new QLabel();
135     labelBlocksIcon = new QLabel();
136     frameBlocksLayout->addStretch();
137     frameBlocksLayout->addWidget(labelEncryptionIcon);
138     frameBlocksLayout->addStretch();
139     frameBlocksLayout->addWidget(labelConnectionsIcon);
140     frameBlocksLayout->addStretch();
141     frameBlocksLayout->addWidget(labelBlocksIcon);
142     frameBlocksLayout->addStretch();
143
144     // Progress bar for blocks download
145     progressBarLabel = new QLabel(tr("Synchronizing with network..."));
146     progressBarLabel->setVisible(false);
147     progressBar = new QProgressBar();
148     progressBar->setToolTip(tr("Block chain synchronization in progress"));
149     progressBar->setVisible(false);
150
151     statusBar()->addWidget(progressBarLabel);
152     statusBar()->addWidget(progressBar);
153     statusBar()->addPermanentWidget(frameBlocks);
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("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     if(!clientModel)
458         return;
459     int total = clientModel->getNumBlocksOfPeers();
460     QString tooltip;
461
462     if(count < total)
463     {
464         if (clientModel->getStatusBarWarnings() == "")
465         {
466             progressBarLabel->setVisible(true);
467             progressBarLabel->setText(tr("Synchronizing with network..."));
468             progressBar->setVisible(true);
469             progressBar->setMaximum(total);
470             progressBar->setValue(count);
471         }
472         else
473         {
474             progressBarLabel->setText(clientModel->getStatusBarWarnings());
475             progressBarLabel->setVisible(true);
476             progressBar->setVisible(false);
477         }
478         tooltip = tr("Downloaded %1 of %2 blocks of transaction history.").arg(count).arg(total);
479     }
480     else
481     {
482         if (clientModel->getStatusBarWarnings() == "")
483             progressBarLabel->setVisible(false);
484         else
485         {
486             progressBarLabel->setText(clientModel->getStatusBarWarnings());
487             progressBarLabel->setVisible(true);
488         }
489         progressBar->setVisible(false);
490         tooltip = tr("Downloaded %1 blocks of transaction history.").arg(count);
491     }
492
493     QDateTime now = QDateTime::currentDateTime();
494     QDateTime lastBlockDate = clientModel->getLastBlockDate();
495     int secs = lastBlockDate.secsTo(now);
496     QString text;
497
498     // Represent time from last generated block in human readable text
499     if(secs <= 0)
500     {
501         // Fully up to date. Leave text empty.
502     }
503     else if(secs < 60)
504     {
505         text = tr("%n second(s) ago","",secs);
506     }
507     else if(secs < 60*60)
508     {
509         text = tr("%n minute(s) ago","",secs/60);
510     }
511     else if(secs < 24*60*60)
512     {
513         text = tr("%n hour(s) ago","",secs/(60*60));
514     }
515     else
516     {
517         text = tr("%n day(s) ago","",secs/(60*60*24));
518     }
519
520     // Set icon state: spinning if catching up, tick otherwise
521     if(secs < 90*60 && count >= Checkpoints::GetTotalBlocksEstimate())
522     {
523         tooltip = tr("Up to date") + QString(".\n") + tooltip;
524         labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
525     }
526     else
527     {
528         tooltip = tr("Catching up...") + QString("\n") + tooltip;
529         labelBlocksIcon->setMovie(syncIconMovie);
530         syncIconMovie->start();
531     }
532
533     if(!text.isEmpty())
534     {
535         tooltip += QString("\n");
536         tooltip += tr("Last received block was generated %1.").arg(text);
537     }
538
539     labelBlocksIcon->setToolTip(tooltip);
540     progressBarLabel->setToolTip(tooltip);
541     progressBar->setToolTip(tooltip);
542 }
543
544 void BitcoinGUI::refreshStatusBar()
545 {
546     /* Might display multiple times in the case of multiple alerts
547     static QString prevStatusBar;
548     QString newStatusBar = clientModel->getStatusBarWarnings();
549     if (prevStatusBar != newStatusBar)
550     {
551         prevStatusBar = newStatusBar;
552         error(tr("Network Alert"), newStatusBar);
553     }*/
554     setNumBlocks(clientModel->getNumBlocks());
555 }
556
557 bool HACK_SHUTDOWN = false;
558
559 void BitcoinGUI::error(const QString &title, const QString &message, bool modal)
560 {
561     // Report errors from network/worker thread
562     if (modal)
563     {
564         QMessageBox::critical(this, title, message, QMessageBox::Ok, QMessageBox::Ok);
565         if (HACK_SHUTDOWN)
566             QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
567     } else {
568         notificator->notify(Notificator::Critical, title, message);
569     }
570 }
571
572 void BitcoinGUI::changeEvent(QEvent *e)
573 {
574     QMainWindow::changeEvent(e);
575 #ifndef Q_WS_MAC // Ignored on Mac
576     if(e->type() == QEvent::WindowStateChange)
577     {
578         if(clientModel && clientModel->getOptionsModel()->getMinimizeToTray())
579         {
580             QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e);
581             if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized())
582             {
583                 QTimer::singleShot(0, this, SLOT(hide()));
584                 e->ignore();
585             }
586         }
587     }
588 #endif
589 }
590
591 void BitcoinGUI::closeEvent(QCloseEvent *event)
592 {
593     if(clientModel)
594     {
595 #ifndef Q_WS_MAC // Ignored on Mac
596         if(!clientModel->getOptionsModel()->getMinimizeToTray() &&
597            !clientModel->getOptionsModel()->getMinimizeOnClose())
598         {
599             qApp->quit();
600         }
601 #endif
602     }
603     QMainWindow::closeEvent(event);
604 }
605
606 void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee)
607 {
608     QString strMessage =
609         tr("This transaction is over the size limit.  You can still send it for a fee of %1, "
610           "which goes to the nodes that process your transaction and helps to support the network.  "
611           "Do you want to pay the fee?").arg(
612                 BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nFeeRequired));
613     QMessageBox::StandardButton retval = QMessageBox::question(
614           this, tr("Sending..."), strMessage,
615           QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes);
616     *payFee = (retval == QMessageBox::Yes);
617 }
618
619 void BitcoinGUI::incomingTransaction(const QModelIndex & parent, int start, int end)
620 {
621     if(!walletModel || !clientModel)
622         return;
623     TransactionTableModel *ttm = walletModel->getTransactionTableModel();
624     qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent)
625                     .data(Qt::EditRole).toULongLong();
626     if(!clientModel->inInitialBlockDownload())
627     {
628         // On new transaction, make an info balloon
629         // Unless the initial block download is in progress, to prevent balloon-spam
630         QString date = ttm->index(start, TransactionTableModel::Date, parent)
631                         .data().toString();
632         QString type = ttm->index(start, TransactionTableModel::Type, parent)
633                         .data().toString();
634         QString address = ttm->index(start, TransactionTableModel::ToAddress, parent)
635                         .data().toString();
636         QIcon icon = qvariant_cast<QIcon>(ttm->index(start,
637                             TransactionTableModel::ToAddress, parent)
638                         .data(Qt::DecorationRole));
639
640         notificator->notify(Notificator::Information,
641                             (amount)<0 ? tr("Sent transaction") :
642                                          tr("Incoming transaction"),
643                               tr("Date: %1\n"
644                                  "Amount: %2\n"
645                                  "Type: %3\n"
646                                  "Address: %4\n")
647                               .arg(date)
648                               .arg(BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), amount, true))
649                               .arg(type)
650                               .arg(address), icon);
651     }
652 }
653
654 void BitcoinGUI::gotoOverviewPage()
655 {
656     overviewAction->setChecked(true);
657     centralWidget->setCurrentWidget(overviewPage);
658
659     exportAction->setEnabled(false);
660     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
661 }
662
663 void BitcoinGUI::gotoHistoryPage()
664 {
665     historyAction->setChecked(true);
666     centralWidget->setCurrentWidget(transactionsPage);
667
668     exportAction->setEnabled(true);
669     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
670     connect(exportAction, SIGNAL(triggered()), transactionView, SLOT(exportClicked()));
671 }
672
673 void BitcoinGUI::gotoAddressBookPage()
674 {
675     addressBookAction->setChecked(true);
676     centralWidget->setCurrentWidget(addressBookPage);
677
678     exportAction->setEnabled(true);
679     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
680     connect(exportAction, SIGNAL(triggered()), addressBookPage, SLOT(exportClicked()));
681 }
682
683 void BitcoinGUI::gotoReceiveCoinsPage()
684 {
685     receiveCoinsAction->setChecked(true);
686     centralWidget->setCurrentWidget(receiveCoinsPage);
687
688     exportAction->setEnabled(true);
689     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
690     connect(exportAction, SIGNAL(triggered()), receiveCoinsPage, SLOT(exportClicked()));
691 }
692
693 void BitcoinGUI::gotoSendCoinsPage()
694 {
695     sendCoinsAction->setChecked(true);
696     centralWidget->setCurrentWidget(sendCoinsPage);
697
698     exportAction->setEnabled(false);
699     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
700 }
701
702 void BitcoinGUI::gotoMessagePage()
703 {
704 #ifdef FIRST_CLASS_MESSAGING
705     messageAction->setChecked(true);
706     centralWidget->setCurrentWidget(messagePage);
707
708     exportAction->setEnabled(false);
709     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
710 #else
711     messagePage->show();
712     messagePage->setFocus();
713 #endif
714 }
715
716 void BitcoinGUI::gotoMessagePage(QString addr)
717 {
718     gotoMessagePage();
719     messagePage->setAddress(addr);
720 }
721
722 void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event)
723 {
724     // Accept only URIs
725     if(event->mimeData()->hasUrls())
726         event->acceptProposedAction();
727 }
728
729 void BitcoinGUI::dropEvent(QDropEvent *event)
730 {
731     if(event->mimeData()->hasUrls())
732     {
733         gotoSendCoinsPage();
734         QList<QUrl> uris = event->mimeData()->urls();
735         foreach(const QUrl &uri, uris)
736         {
737             sendCoinsPage->handleURI(uri.toString());
738         }
739     }
740
741     event->acceptProposedAction();
742 }
743
744 void BitcoinGUI::handleURI(QString strURI)
745 {
746     gotoSendCoinsPage();
747     sendCoinsPage->handleURI(strURI);
748
749     if(!isActiveWindow())
750         activateWindow();
751
752     showNormalIfMinimized();
753 }
754
755 void BitcoinGUI::setEncryptionStatus(int status)
756 {
757     switch(status)
758     {
759     case WalletModel::Unencrypted:
760         labelEncryptionIcon->hide();
761         encryptWalletAction->setChecked(false);
762         changePassphraseAction->setEnabled(false);
763         encryptWalletAction->setEnabled(true);
764         break;
765     case WalletModel::Unlocked:
766         labelEncryptionIcon->show();
767         labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
768         labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>"));
769         encryptWalletAction->setChecked(true);
770         changePassphraseAction->setEnabled(true);
771         encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
772         break;
773     case WalletModel::Locked:
774         labelEncryptionIcon->show();
775         labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
776         labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>"));
777         encryptWalletAction->setChecked(true);
778         changePassphraseAction->setEnabled(true);
779         encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
780         break;
781     }
782 }
783
784 void BitcoinGUI::encryptWallet(bool status)
785 {
786     if(!walletModel)
787         return;
788     AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt:
789                                      AskPassphraseDialog::Decrypt, this);
790     dlg.setModel(walletModel);
791     dlg.exec();
792
793     setEncryptionStatus(walletModel->getEncryptionStatus());
794 }
795
796 void BitcoinGUI::backupWallet()
797 {
798     QString saveDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
799     QString filename = QFileDialog::getSaveFileName(this, tr("Backup Wallet"), saveDir, tr("Wallet Data (*.dat)"));
800     if(!filename.isEmpty()) {
801         if(!walletModel->backupWallet(filename)) {
802             QMessageBox::warning(this, tr("Backup Failed"), tr("There was an error trying to save the wallet data to the new location."));
803         }
804     }
805 }
806
807 void BitcoinGUI::changePassphrase()
808 {
809     AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this);
810     dlg.setModel(walletModel);
811     dlg.exec();
812 }
813
814 void BitcoinGUI::unlockWallet()
815 {
816     if(!walletModel)
817         return;
818     // Unlock wallet when requested by wallet model
819     if(walletModel->getEncryptionStatus() == WalletModel::Locked)
820     {
821         AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, this);
822         dlg.setModel(walletModel);
823         dlg.exec();
824     }
825 }
826
827 void BitcoinGUI::showNormalIfMinimized()
828 {
829     if(!isVisible()) // Show, if hidden
830         show();
831     if(isMinimized()) // Unminimize, if minimized
832         showNormal();
833 }