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