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