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