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