dd94652e3acbd11aeec3accbc3c80035cf08e84e
[novacoin.git] / src / qt / bitcoingui.cpp
1 /*
2  * Qt4 bitcoin GUI.
3  *
4  * W.J. van der Laan 2011
5  */
6 #include "bitcoingui.h"
7 #include "transactiontablemodel.h"
8 #include "addressbookpage.h"
9 #include "sendcoinsdialog.h"
10 #include "optionsdialog.h"
11 #include "aboutdialog.h"
12 #include "clientmodel.h"
13 #include "walletmodel.h"
14 #include "editaddressdialog.h"
15 #include "optionsmodel.h"
16 #include "transactiondescdialog.h"
17 #include "addresstablemodel.h"
18 #include "transactionview.h"
19 #include "overviewpage.h"
20 #include "bitcoinunits.h"
21
22 #include <QApplication>
23 #include <QMainWindow>
24 #include <QMenuBar>
25 #include <QMenu>
26 #include <QIcon>
27 #include <QTabWidget>
28 #include <QVBoxLayout>
29 #include <QToolBar>
30 #include <QStatusBar>
31 #include <QLabel>
32 #include <QLineEdit>
33 #include <QPushButton>
34 #include <QLocale>
35 #include <QMessageBox>
36 #include <QProgressBar>
37 #include <QStackedWidget>
38 #include <QDateTime>
39 #include <QMovie>
40
41 #include <QDragEnterEvent>
42 #include <QUrl>
43
44 #include <iostream>
45
46 BitcoinGUI::BitcoinGUI(QWidget *parent):
47     QMainWindow(parent),
48     clientModel(0),
49     walletModel(0),
50     trayIcon(0)
51 {
52     resize(850, 550);
53     setWindowTitle(tr("Bitcoin Wallet"));
54     setWindowIcon(QIcon(":icons/bitcoin"));
55     // Accept D&D of URIs
56     setAcceptDrops(true);
57
58     createActions();
59
60     // Menus
61     QMenu *file = menuBar()->addMenu("&File");
62     file->addAction(sendCoinsAction);
63     file->addAction(receiveCoinsAction);
64     file->addSeparator();
65     file->addAction(quitAction);
66     
67     QMenu *settings = menuBar()->addMenu("&Settings");
68     settings->addAction(optionsAction);
69
70     QMenu *help = menuBar()->addMenu("&Help");
71     help->addAction(aboutAction);
72     
73     // Toolbars
74     QToolBar *toolbar = addToolBar(tr("Tabs toolbar"));
75     toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
76     toolbar->addAction(overviewAction);
77     toolbar->addAction(sendCoinsAction);
78     toolbar->addAction(receiveCoinsAction);
79     toolbar->addAction(historyAction);
80     toolbar->addAction(addressBookAction);
81
82     QToolBar *toolbar2 = addToolBar(tr("Actions toolbar"));
83     toolbar2->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
84     toolbar2->addAction(exportAction);
85
86     // Create tabs
87     overviewPage = new OverviewPage();
88
89     transactionsPage = new QWidget(this);
90     QVBoxLayout *vbox = new QVBoxLayout();
91     transactionView = new TransactionView(this);
92     vbox->addWidget(transactionView);
93     transactionsPage->setLayout(vbox);
94
95     addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab);
96
97     receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab);
98
99     sendCoinsPage = new SendCoinsDialog(this);
100
101     centralWidget = new QStackedWidget(this);
102     centralWidget->addWidget(overviewPage);
103     centralWidget->addWidget(transactionsPage);
104     centralWidget->addWidget(addressBookPage);
105     centralWidget->addWidget(receiveCoinsPage);
106     centralWidget->addWidget(sendCoinsPage);
107     setCentralWidget(centralWidget);
108     
109     // Create status bar
110     statusBar();
111
112     // Status bar notification icons
113     QFrame *frameBlocks = new QFrame();
114     //frameBlocks->setFrameStyle(QFrame::Panel | QFrame::Sunken);
115     frameBlocks->setContentsMargins(0,0,0,0);
116     frameBlocks->setMinimumWidth(56);
117     frameBlocks->setMaximumWidth(56);
118     QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);
119     frameBlocksLayout->setContentsMargins(3,0,3,0);
120     frameBlocksLayout->setSpacing(3);
121     labelConnectionsIcon = new QLabel();
122     labelBlocksIcon = new QLabel();
123     frameBlocksLayout->addStretch();
124     frameBlocksLayout->addWidget(labelConnectionsIcon);
125     frameBlocksLayout->addStretch();
126     frameBlocksLayout->addWidget(labelBlocksIcon);
127     frameBlocksLayout->addStretch();
128
129     // Progress bar for blocks download
130     progressBarLabel = new QLabel(tr("Synchronizing with network..."));
131     progressBarLabel->setVisible(false);
132     progressBar = new QProgressBar();
133     progressBar->setToolTip(tr("Block chain synchronization in progress"));
134     progressBar->setVisible(false);
135
136     statusBar()->addWidget(progressBarLabel);
137     statusBar()->addWidget(progressBar);
138     statusBar()->addPermanentWidget(frameBlocks);
139
140     createTrayIcon();
141
142     syncIconMovie = new QMovie(":/movies/update_spinner", "mng", this);
143
144     // Clicking on a transaction on the overview page simply sends you to transaction history page
145     connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage()));
146
147     // Doubleclicking on a transaction on the transaction history page shows details
148     connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));
149
150     gotoOverviewPage();
151 }
152
153 void BitcoinGUI::createActions()
154 {
155     QActionGroup *tabGroup = new QActionGroup(this);
156
157     overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this);
158     overviewAction->setToolTip(tr("Show general overview of wallet"));
159     overviewAction->setCheckable(true);
160     tabGroup->addAction(overviewAction);
161
162     historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this);
163     historyAction->setToolTip(tr("Browse transaction history"));
164     historyAction->setCheckable(true);
165     tabGroup->addAction(historyAction);
166
167     addressBookAction = new QAction(QIcon(":/icons/address-book"), tr("&Address Book"), this);
168     addressBookAction->setToolTip(tr("Edit the list of stored addresses and labels"));
169     addressBookAction->setCheckable(true);
170     tabGroup->addAction(addressBookAction);
171
172     receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive coins"), this);
173     receiveCoinsAction->setToolTip(tr("Show the list of addresses for receiving payments"));
174     receiveCoinsAction->setCheckable(true);
175     tabGroup->addAction(receiveCoinsAction);
176
177     sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send coins"), this);
178     sendCoinsAction->setToolTip(tr("Send coins to a bitcoin address"));
179     sendCoinsAction->setCheckable(true);
180     tabGroup->addAction(sendCoinsAction);
181
182     connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
183     connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));
184     connect(addressBookAction, SIGNAL(triggered()), this, SLOT(gotoAddressBookPage()));
185     connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
186     connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
187
188     quitAction = new QAction(QIcon(":/icons/quit"), tr("&Exit"), this);
189     quitAction->setToolTip(tr("Quit application"));
190     aboutAction = new QAction(QIcon(":/icons/bitcoin"), tr("&About"), this);
191     aboutAction->setToolTip(tr("Show information about Bitcoin"));
192     optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this);
193     optionsAction->setToolTip(tr("Modify configuration options for bitcoin"));
194     openBitcoinAction = new QAction(QIcon(":/icons/bitcoin"), tr("Open &Bitcoin"), this);
195     openBitcoinAction->setToolTip(tr("Show the Bitcoin window"));
196     exportAction = new QAction(QIcon(":/icons/export"), tr("&Export..."), this);
197     exportAction->setToolTip(tr("Export the current view to a file"));
198
199     connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
200     connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
201     connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
202     connect(openBitcoinAction, SIGNAL(triggered()), this, SLOT(show()));
203 }
204
205 void BitcoinGUI::setClientModel(ClientModel *clientModel)
206 {
207     this->clientModel = clientModel;
208
209     if(clientModel->isTestNet())
210     {
211         QString title_testnet = windowTitle() + QString(" ") + tr("[testnet]");
212         setWindowTitle(title_testnet);
213         setWindowIcon(QIcon(":icons/bitcoin_testnet"));
214         if(trayIcon)
215         {
216             trayIcon->setToolTip(title_testnet);
217             trayIcon->setIcon(QIcon(":/icons/toolbar_testnet"));
218         }
219     }
220
221     // Keep up to date with client
222     setNumConnections(clientModel->getNumConnections());
223     connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
224
225     setNumBlocks(clientModel->getNumBlocks());
226     connect(clientModel, SIGNAL(numBlocksChanged(int)), this, SLOT(setNumBlocks(int)));
227
228     // Report errors from network/worker thread
229     connect(clientModel, SIGNAL(error(QString,QString)), this, SLOT(error(QString,QString)));
230 }
231
232 void BitcoinGUI::setWalletModel(WalletModel *walletModel)
233 {
234     this->walletModel = walletModel;
235
236     // Report errors from wallet thread
237     connect(walletModel, SIGNAL(error(QString,QString)), this, SLOT(error(QString,QString)));
238
239     // Put transaction list in tabs
240     transactionView->setModel(walletModel);
241
242     overviewPage->setModel(walletModel);
243     addressBookPage->setModel(walletModel->getAddressTableModel());
244     receiveCoinsPage->setModel(walletModel->getAddressTableModel());
245     sendCoinsPage->setModel(walletModel);
246
247     // Balloon popup for new transaction
248     connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
249             this, SLOT(incomingTransaction(QModelIndex,int,int)));
250 }
251
252 void BitcoinGUI::createTrayIcon()
253 {
254     QMenu *trayIconMenu = new QMenu(this);
255     trayIconMenu->addAction(openBitcoinAction);
256     trayIconMenu->addAction(optionsAction);
257     trayIconMenu->addSeparator();
258     trayIconMenu->addAction(quitAction);
259
260     trayIcon = new QSystemTrayIcon(this);
261     trayIcon->setContextMenu(trayIconMenu);
262     trayIcon->setToolTip("Bitcoin client");
263     trayIcon->setIcon(QIcon(":/icons/toolbar"));
264     connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
265             this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
266     trayIcon->show();
267 }
268
269 void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
270 {
271     if(reason == QSystemTrayIcon::Trigger)
272     {
273         // Doubleclick on system tray icon triggers "open bitcoin"
274         openBitcoinAction->trigger();
275     }
276 }
277
278 void BitcoinGUI::optionsClicked()
279 {
280     OptionsDialog dlg;
281     dlg.setModel(clientModel->getOptionsModel());
282     dlg.exec();
283 }
284
285 void BitcoinGUI::aboutClicked()
286 {
287     AboutDialog dlg;
288     dlg.setModel(clientModel);
289     dlg.exec();
290 }
291
292 void BitcoinGUI::setNumConnections(int count)
293 {
294     QString icon;
295     switch(count)
296     {
297     case 0: icon = ":/icons/connect_0"; break;
298     case 1: case 2: case 3: icon = ":/icons/connect_1"; break;
299     case 4: case 5: case 6: icon = ":/icons/connect_2"; break;
300     case 7: case 8: case 9: icon = ":/icons/connect_3"; break;
301     default: icon = ":/icons/connect_4"; break;
302     }
303     labelConnectionsIcon->setPixmap(QIcon(icon).pixmap(16,16));
304     labelConnectionsIcon->setToolTip(tr("%n active connection(s) to Bitcoin network", "", count));
305 }
306
307 void BitcoinGUI::setNumBlocks(int count)
308 {
309     int total = clientModel->getTotalBlocksEstimate();
310     QString tooltip;
311
312     if(count < total)
313     {
314         progressBarLabel->setVisible(true);
315         progressBar->setVisible(true);
316         progressBar->setMaximum(total);
317         progressBar->setValue(count);
318         tooltip = tr("Downloaded %1 of %2 blocks of transaction history.").arg(count).arg(total);
319     }
320     else
321     {
322         progressBarLabel->setVisible(false);
323         progressBar->setVisible(false);
324         tooltip = tr("Downloaded %1 blocks of transaction history.").arg(count);
325     }
326
327     QDateTime now = QDateTime::currentDateTime();
328     QDateTime lastBlockDate = clientModel->getLastBlockDate();
329     int secs = lastBlockDate.secsTo(now);
330     QString text;
331
332     // Represent time from last generated block in human readable text
333     if(secs < 60)
334     {
335         text = tr("%n second(s) ago","",secs);
336     }
337     else if(secs < 60*60)
338     {
339         text = tr("%n minute(s) ago","",secs/60);
340     }
341     else if(secs < 24*60*60)
342     {
343         text = tr("%n hour(s) ago","",secs/(60*60));
344     }
345     else
346     {
347         text = tr("%n day(s) ago","",secs/(60*60*24));
348     }
349
350     // Set icon state: spinning if catching up, tick otherwise
351     if(secs < 30*60)
352     {
353         tooltip = tr("Up to date") + QString("\n") + tooltip;
354         labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(16,16));
355     }
356     else
357     {
358         tooltip = tr("Catching up...") + QString("\n") + tooltip;
359         labelBlocksIcon->setMovie(syncIconMovie);
360         syncIconMovie->start();
361     }
362
363     tooltip += QString("\n");
364     tooltip += tr("Last received block was generated %1.").arg(text);
365
366     labelBlocksIcon->setToolTip(tooltip);
367     progressBarLabel->setToolTip(tooltip);
368     progressBar->setToolTip(tooltip);
369 }
370
371 void BitcoinGUI::error(const QString &title, const QString &message)
372 {
373     // Report errors from network/worker thread
374     if(trayIcon->supportsMessages())
375     {
376         // Show as "balloon" message if possible
377         trayIcon->showMessage(title, message, QSystemTrayIcon::Critical);
378     }
379     else
380     {
381         // Fall back to old fashioned popup dialog if not
382         QMessageBox::critical(this, title,
383             message,
384             QMessageBox::Ok, QMessageBox::Ok);
385     }
386 }
387
388 void BitcoinGUI::changeEvent(QEvent *e)
389 {
390     if (e->type() == QEvent::WindowStateChange)
391     {
392         if(clientModel->getOptionsModel()->getMinimizeToTray())
393         {
394             if (isMinimized())
395             {
396                 hide();
397                 e->ignore();
398             }
399             else
400             {
401                 e->accept();
402             }
403         }
404     }
405     QMainWindow::changeEvent(e);
406 }
407
408 void BitcoinGUI::closeEvent(QCloseEvent *event)
409 {
410     if(!clientModel->getOptionsModel()->getMinimizeToTray() &&
411        !clientModel->getOptionsModel()->getMinimizeOnClose())
412     {
413         qApp->quit();
414     }
415     QMainWindow::closeEvent(event);
416 }
417
418 void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee)
419 {
420     QString strMessage =
421         tr("This transaction is over the size limit.  You can still send it for a fee of %1, "
422           "which goes to the nodes that process your transaction and helps to support the network.  "
423           "Do you want to pay the fee?").arg(
424                 BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nFeeRequired));
425     QMessageBox::StandardButton retval = QMessageBox::question(
426           this, tr("Sending..."), strMessage,
427           QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes);
428     *payFee = (retval == QMessageBox::Yes);
429 }
430
431 void BitcoinGUI::incomingTransaction(const QModelIndex & parent, int start, int end)
432 {
433     if(start == end)
434         return;
435     TransactionTableModel *ttm = walletModel->getTransactionTableModel();
436     qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent)
437                     .data(Qt::EditRole).toULongLong();
438     if(!clientModel->inInitialBlockDownload())
439     {
440         // On new transaction, make an info balloon
441         // Unless the initial block download is in progress, to prevent balloon-spam
442         QString date = ttm->index(start, TransactionTableModel::Date, parent)
443                         .data().toString();
444         QString type = ttm->index(start, TransactionTableModel::Type, parent)
445                         .data().toString();
446         QString address = ttm->index(start, TransactionTableModel::ToAddress, parent)
447                         .data().toString();
448
449         trayIcon->showMessage((amount)<0 ? tr("Sent transaction") :
450                                            tr("Incoming transaction"),
451                               tr("Date: ") + date + "\n" +
452                               tr("Amount: ") + BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), amount, true) + "\n" +
453                               tr("Type: ") + type + "\n" +
454                               tr("Address: ") + address + "\n",
455                               QSystemTrayIcon::Information);
456     }
457 }
458
459 void BitcoinGUI::gotoOverviewPage()
460 {
461     overviewAction->setChecked(true);
462     centralWidget->setCurrentWidget(overviewPage);
463
464     exportAction->setEnabled(false);
465     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
466 }
467
468 void BitcoinGUI::gotoHistoryPage()
469 {
470     historyAction->setChecked(true);
471     centralWidget->setCurrentWidget(transactionsPage);
472
473     exportAction->setEnabled(true);
474     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
475     connect(exportAction, SIGNAL(triggered()), transactionView, SLOT(exportClicked()));
476 }
477
478 void BitcoinGUI::gotoAddressBookPage()
479 {
480     addressBookAction->setChecked(true);
481     centralWidget->setCurrentWidget(addressBookPage);
482
483     exportAction->setEnabled(true);
484     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
485     connect(exportAction, SIGNAL(triggered()), addressBookPage, SLOT(exportClicked()));
486 }
487
488 void BitcoinGUI::gotoReceiveCoinsPage()
489 {
490     receiveCoinsAction->setChecked(true);
491     centralWidget->setCurrentWidget(receiveCoinsPage);
492
493     exportAction->setEnabled(true);
494     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
495     connect(exportAction, SIGNAL(triggered()), receiveCoinsPage, SLOT(exportClicked()));
496 }
497
498 void BitcoinGUI::gotoSendCoinsPage()
499 {
500     sendCoinsAction->setChecked(true);
501     if(centralWidget->currentWidget() != sendCoinsPage)
502     {
503         // Clear the current contents if we arrived from another tab
504         sendCoinsPage->clear();
505     }
506     centralWidget->setCurrentWidget(sendCoinsPage);
507
508     exportAction->setEnabled(false);
509     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
510 }
511
512 void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event)
513 {
514     // Accept only URLs
515     if(event->mimeData()->hasUrls())
516         event->acceptProposedAction();
517 }
518
519 void BitcoinGUI::dropEvent(QDropEvent *event)
520 {
521     if(event->mimeData()->hasUrls())
522     {
523         gotoSendCoinsPage();
524         QList<QUrl> urls = event->mimeData()->urls();
525         foreach(const QUrl &url, urls)
526         {
527             sendCoinsPage->handleURL(&url);
528         }
529     }
530
531     event->acceptProposedAction();
532 }
533