Bugfix: Allow tray icon to linger until Bitcoin-Qt shuts down completely. Fixes #908
[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
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 #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     openBitcoinAction = new QAction(QIcon(":/icons/bitcoin"), tr("Open &Bitcoin"), this);
241     openBitcoinAction->setToolTip(tr("Show 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(openBitcoinAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
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)), this, SLOT(error(QString,QString)));
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)), this, SLOT(error(QString,QString)));
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("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()), openBitcoinAction, SLOT(trigger()));
389     trayIconMenu = dockIconHandler->dockMenu();
390 #endif
391
392     // Configuration of the tray icon (or dock icon) icon menu
393     trayIconMenu->addAction(openBitcoinAction);
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 "open bitcoin"
417         openBitcoinAction->trigger();
418     }
419 }
420 #endif
421
422 void BitcoinGUI::optionsClicked()
423 {
424     if(!clientModel || !clientModel->getOptionsModel())
425         return;
426     OptionsDialog dlg;
427     dlg.setModel(clientModel->getOptionsModel());
428     dlg.exec();
429 }
430
431 void BitcoinGUI::aboutClicked()
432 {
433     AboutDialog dlg;
434     dlg.setModel(clientModel);
435     dlg.exec();
436 }
437
438 void BitcoinGUI::setNumConnections(int count)
439 {
440     QString icon;
441     switch(count)
442     {
443     case 0: icon = ":/icons/connect_0"; break;
444     case 1: case 2: case 3: icon = ":/icons/connect_1"; break;
445     case 4: case 5: case 6: icon = ":/icons/connect_2"; break;
446     case 7: case 8: case 9: icon = ":/icons/connect_3"; break;
447     default: icon = ":/icons/connect_4"; break;
448     }
449     labelConnectionsIcon->setPixmap(QIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
450     labelConnectionsIcon->setToolTip(tr("%n active connection(s) to Bitcoin network", "", count));
451 }
452
453 void BitcoinGUI::setNumBlocks(int count)
454 {
455     if(!clientModel)
456         return;
457     int total = clientModel->getNumBlocksOfPeers();
458     QString tooltip;
459
460     if(count < total)
461     {
462         if (clientModel->getStatusBarWarnings() == "")
463         {
464             progressBarLabel->setVisible(true);
465             progressBarLabel->setText(tr("Synchronizing with network..."));
466             progressBar->setVisible(true);
467             progressBar->setMaximum(total);
468             progressBar->setValue(count);
469         }
470         else
471         {
472             progressBarLabel->setText(clientModel->getStatusBarWarnings());
473             progressBarLabel->setVisible(true);
474             progressBar->setVisible(false);
475         }
476         tooltip = tr("Downloaded %1 of %2 blocks of transaction history.").arg(count).arg(total);
477     }
478     else
479     {
480         if (clientModel->getStatusBarWarnings() == "")
481             progressBarLabel->setVisible(false);
482         else
483         {
484             progressBarLabel->setText(clientModel->getStatusBarWarnings());
485             progressBarLabel->setVisible(true);
486         }
487         progressBar->setVisible(false);
488         tooltip = tr("Downloaded %1 blocks of transaction history.").arg(count);
489     }
490
491     QDateTime now = QDateTime::currentDateTime();
492     QDateTime lastBlockDate = clientModel->getLastBlockDate();
493     int secs = lastBlockDate.secsTo(now);
494     QString text;
495
496     // Represent time from last generated block in human readable text
497     if(secs <= 0)
498     {
499         // Fully up to date. Leave text empty.
500     }
501     else if(secs < 60)
502     {
503         text = tr("%n second(s) ago","",secs);
504     }
505     else if(secs < 60*60)
506     {
507         text = tr("%n minute(s) ago","",secs/60);
508     }
509     else if(secs < 24*60*60)
510     {
511         text = tr("%n hour(s) ago","",secs/(60*60));
512     }
513     else
514     {
515         text = tr("%n day(s) ago","",secs/(60*60*24));
516     }
517
518     // Set icon state: spinning if catching up, tick otherwise
519     if(secs < 90*60 && count >= Checkpoints::GetTotalBlocksEstimate())
520     {
521         tooltip = tr("Up to date") + QString(".\n") + tooltip;
522         labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
523     }
524     else
525     {
526         tooltip = tr("Catching up...") + QString("\n") + tooltip;
527         labelBlocksIcon->setMovie(syncIconMovie);
528         syncIconMovie->start();
529     }
530
531     if(!text.isEmpty())
532     {
533         tooltip += QString("\n");
534         tooltip += tr("Last received block was generated %1.").arg(text);
535     }
536
537     labelBlocksIcon->setToolTip(tooltip);
538     progressBarLabel->setToolTip(tooltip);
539     progressBar->setToolTip(tooltip);
540 }
541
542 void BitcoinGUI::refreshStatusBar()
543 {
544     /* Might display multiple times in the case of multiple alerts
545     static QString prevStatusBar;
546     QString newStatusBar = clientModel->getStatusBarWarnings();
547     if (prevStatusBar != newStatusBar)
548     {
549         prevStatusBar = newStatusBar;
550         error(tr("Network Alert"), newStatusBar);
551     }*/
552     setNumBlocks(clientModel->getNumBlocks());
553 }
554
555 bool HACK_SHUTDOWN = false;
556
557 void BitcoinGUI::error(const QString &title, const QString &message, bool modal)
558 {
559     // Report errors from network/worker thread
560     if (modal)
561     {
562         QMessageBox::critical(this, title, message, QMessageBox::Ok, QMessageBox::Ok);
563         if (HACK_SHUTDOWN)
564             QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
565     } else {
566         notificator->notify(Notificator::Critical, title, message);
567     }
568 }
569
570 void BitcoinGUI::changeEvent(QEvent *e)
571 {
572     QMainWindow::changeEvent(e);
573 #ifndef Q_WS_MAC // Ignored on Mac
574     if(e->type() == QEvent::WindowStateChange)
575     {
576         if(clientModel && clientModel->getOptionsModel()->getMinimizeToTray())
577         {
578             QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e);
579             if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized())
580             {
581                 QTimer::singleShot(0, this, SLOT(hide()));
582                 e->ignore();
583             }
584         }
585     }
586 #endif
587 }
588
589 void BitcoinGUI::closeEvent(QCloseEvent *event)
590 {
591     if(clientModel)
592     {
593 #ifndef Q_WS_MAC // Ignored on Mac
594         if(!clientModel->getOptionsModel()->getMinimizeToTray() &&
595            !clientModel->getOptionsModel()->getMinimizeOnClose())
596         {
597             qApp->quit();
598         }
599 #endif
600     }
601     QMainWindow::closeEvent(event);
602 }
603
604 void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee)
605 {
606     QString strMessage =
607         tr("This transaction is over the size limit.  You can still send it for a fee of %1, "
608           "which goes to the nodes that process your transaction and helps to support the network.  "
609           "Do you want to pay the fee?").arg(
610                 BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nFeeRequired));
611     QMessageBox::StandardButton retval = QMessageBox::question(
612           this, tr("Sending..."), strMessage,
613           QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes);
614     *payFee = (retval == QMessageBox::Yes);
615 }
616
617 void BitcoinGUI::incomingTransaction(const QModelIndex & parent, int start, int end)
618 {
619     if(!walletModel || !clientModel)
620         return;
621     TransactionTableModel *ttm = walletModel->getTransactionTableModel();
622     qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent)
623                     .data(Qt::EditRole).toULongLong();
624     if(!clientModel->inInitialBlockDownload())
625     {
626         // On new transaction, make an info balloon
627         // Unless the initial block download is in progress, to prevent balloon-spam
628         QString date = ttm->index(start, TransactionTableModel::Date, parent)
629                         .data().toString();
630         QString type = ttm->index(start, TransactionTableModel::Type, parent)
631                         .data().toString();
632         QString address = ttm->index(start, TransactionTableModel::ToAddress, parent)
633                         .data().toString();
634         QIcon icon = qvariant_cast<QIcon>(ttm->index(start,
635                             TransactionTableModel::ToAddress, parent)
636                         .data(Qt::DecorationRole));
637
638         notificator->notify(Notificator::Information,
639                             (amount)<0 ? tr("Sent transaction") :
640                                          tr("Incoming transaction"),
641                               tr("Date: %1\n"
642                                  "Amount: %2\n"
643                                  "Type: %3\n"
644                                  "Address: %4\n")
645                               .arg(date)
646                               .arg(BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), amount, true))
647                               .arg(type)
648                               .arg(address), icon);
649     }
650 }
651
652 void BitcoinGUI::gotoOverviewPage()
653 {
654     overviewAction->setChecked(true);
655     centralWidget->setCurrentWidget(overviewPage);
656
657     exportAction->setEnabled(false);
658     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
659 }
660
661 void BitcoinGUI::gotoHistoryPage()
662 {
663     historyAction->setChecked(true);
664     centralWidget->setCurrentWidget(transactionsPage);
665
666     exportAction->setEnabled(true);
667     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
668     connect(exportAction, SIGNAL(triggered()), transactionView, SLOT(exportClicked()));
669 }
670
671 void BitcoinGUI::gotoAddressBookPage()
672 {
673     addressBookAction->setChecked(true);
674     centralWidget->setCurrentWidget(addressBookPage);
675
676     exportAction->setEnabled(true);
677     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
678     connect(exportAction, SIGNAL(triggered()), addressBookPage, SLOT(exportClicked()));
679 }
680
681 void BitcoinGUI::gotoReceiveCoinsPage()
682 {
683     receiveCoinsAction->setChecked(true);
684     centralWidget->setCurrentWidget(receiveCoinsPage);
685
686     exportAction->setEnabled(true);
687     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
688     connect(exportAction, SIGNAL(triggered()), receiveCoinsPage, SLOT(exportClicked()));
689 }
690
691 void BitcoinGUI::gotoSendCoinsPage()
692 {
693     sendCoinsAction->setChecked(true);
694     centralWidget->setCurrentWidget(sendCoinsPage);
695
696     exportAction->setEnabled(false);
697     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
698 }
699
700 void BitcoinGUI::gotoMessagePage()
701 {
702 #ifdef FIRST_CLASS_MESSAGING
703     messageAction->setChecked(true);
704     centralWidget->setCurrentWidget(messagePage);
705
706     exportAction->setEnabled(false);
707     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
708 #else
709     messagePage->show();
710     messagePage->setFocus();
711 #endif
712 }
713
714 void BitcoinGUI::gotoMessagePage(QString addr)
715 {
716     gotoMessagePage();
717     messagePage->setAddress(addr);
718 }
719
720 void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event)
721 {
722     // Accept only URIs
723     if(event->mimeData()->hasUrls())
724         event->acceptProposedAction();
725 }
726
727 void BitcoinGUI::dropEvent(QDropEvent *event)
728 {
729     if(event->mimeData()->hasUrls())
730     {
731         gotoSendCoinsPage();
732         QList<QUrl> uris = event->mimeData()->urls();
733         foreach(const QUrl &uri, uris)
734         {
735             sendCoinsPage->handleURI(uri.toString());
736         }
737     }
738
739     event->acceptProposedAction();
740 }
741
742 void BitcoinGUI::handleURI(QString strURI)
743 {
744     gotoSendCoinsPage();
745     sendCoinsPage->handleURI(strURI);
746
747     if(!isActiveWindow())
748         activateWindow();
749
750     showNormalIfMinimized();
751 }
752
753 void BitcoinGUI::setEncryptionStatus(int status)
754 {
755     switch(status)
756     {
757     case WalletModel::Unencrypted:
758         labelEncryptionIcon->hide();
759         encryptWalletAction->setChecked(false);
760         changePassphraseAction->setEnabled(false);
761         encryptWalletAction->setEnabled(true);
762         break;
763     case WalletModel::Unlocked:
764         labelEncryptionIcon->show();
765         labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
766         labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>"));
767         encryptWalletAction->setChecked(true);
768         changePassphraseAction->setEnabled(true);
769         encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
770         break;
771     case WalletModel::Locked:
772         labelEncryptionIcon->show();
773         labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
774         labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>"));
775         encryptWalletAction->setChecked(true);
776         changePassphraseAction->setEnabled(true);
777         encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
778         break;
779     }
780 }
781
782 void BitcoinGUI::encryptWallet(bool status)
783 {
784     if(!walletModel)
785         return;
786     AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt:
787                                      AskPassphraseDialog::Decrypt, this);
788     dlg.setModel(walletModel);
789     dlg.exec();
790
791     setEncryptionStatus(walletModel->getEncryptionStatus());
792 }
793
794 void BitcoinGUI::backupWallet()
795 {
796     QString saveDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
797     QString filename = QFileDialog::getSaveFileName(this, tr("Backup Wallet"), saveDir, tr("Wallet Data (*.dat)"));
798     if(!filename.isEmpty()) {
799         if(!walletModel->backupWallet(filename)) {
800             QMessageBox::warning(this, tr("Backup Failed"), tr("There was an error trying to save the wallet data to the new location."));
801         }
802     }
803 }
804
805 void BitcoinGUI::changePassphrase()
806 {
807     AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this);
808     dlg.setModel(walletModel);
809     dlg.exec();
810 }
811
812 void BitcoinGUI::unlockWallet()
813 {
814     if(!walletModel)
815         return;
816     // Unlock wallet when requested by wallet model
817     if(walletModel->getEncryptionStatus() == WalletModel::Locked)
818     {
819         AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, this);
820         dlg.setModel(walletModel);
821         dlg.exec();
822     }
823 }
824
825 void BitcoinGUI::showNormalIfMinimized()
826 {
827     if(!isVisible()) // Show, if hidden
828         show();
829     if(isMinimized()) // Unminimize, if minimized
830         showNormal();
831 }