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