2c9c25d5b584a91598d16726dce774243171bef1
[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
56     createActions();
57
58     // Menus
59     QMenu *file = menuBar()->addMenu("&File");
60     file->addAction(sendCoinsAction);
61     file->addAction(receiveCoinsAction);
62     file->addSeparator();
63     file->addAction(quitAction);
64     
65     QMenu *settings = menuBar()->addMenu("&Settings");
66     settings->addAction(optionsAction);
67
68     QMenu *help = menuBar()->addMenu("&Help");
69     help->addAction(aboutAction);
70     
71     // Toolbar
72     QToolBar *toolbar = addToolBar("Main toolbar");
73     toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
74     toolbar->addAction(overviewAction);
75     toolbar->addAction(sendCoinsAction);
76     toolbar->addAction(receiveCoinsAction);
77     toolbar->addAction(historyAction);
78     toolbar->addAction(addressBookAction);
79
80     QToolBar *toolbar2 = addToolBar("Transactions toolbar");
81     toolbar2->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
82     toolbar2->addAction(exportAction);
83
84     // Overview page
85     overviewPage = new OverviewPage();
86     QVBoxLayout *vbox = new QVBoxLayout();
87
88     transactionView = new TransactionView(this);
89     connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));
90     vbox->addWidget(transactionView);
91
92     transactionsPage = new QWidget(this);
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 "Blocks" notification
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 simply sends you to transaction history page
145     connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage()));
146
147     setAcceptDrops(true);
148
149     gotoOverviewPage();
150 }
151
152 void BitcoinGUI::createActions()
153 {
154     QActionGroup *tabGroup = new QActionGroup(this);
155
156     overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this);
157     overviewAction->setToolTip(tr("Show general overview of wallet"));
158     overviewAction->setCheckable(true);
159     tabGroup->addAction(overviewAction);
160
161     historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this);
162     historyAction->setToolTip(tr("Browse transaction history"));
163     historyAction->setCheckable(true);
164     tabGroup->addAction(historyAction);
165
166     addressBookAction = new QAction(QIcon(":/icons/address-book"), tr("&Address Book"), this);
167     addressBookAction->setToolTip(tr("Edit the list of stored addresses and labels"));
168     addressBookAction->setCheckable(true);
169     tabGroup->addAction(addressBookAction);
170
171     receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive coins"), this);
172     receiveCoinsAction->setToolTip(tr("Show the list of addresses for receiving payments"));
173     receiveCoinsAction->setCheckable(true);
174     tabGroup->addAction(receiveCoinsAction);
175
176     sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send coins"), this);
177     sendCoinsAction->setToolTip(tr("Send coins to a bitcoin address"));
178     sendCoinsAction->setCheckable(true);
179     tabGroup->addAction(sendCoinsAction);
180
181     connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
182     connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));
183     connect(addressBookAction, SIGNAL(triggered()), this, SLOT(gotoAddressBookPage()));
184     connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
185     connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
186
187     quitAction = new QAction(QIcon(":/icons/quit"), tr("&Exit"), this);
188     quitAction->setToolTip(tr("Quit application"));
189     aboutAction = new QAction(QIcon(":/icons/bitcoin"), tr("&About"), this);
190     aboutAction->setToolTip(tr("Show information about Bitcoin"));
191     optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this);
192     optionsAction->setToolTip(tr("Modify configuration options for bitcoin"));
193     openBitcoinAction = new QAction(QIcon(":/icons/bitcoin"), tr("Open &Bitcoin"), this);
194     openBitcoinAction->setToolTip(tr("Show the Bitcoin window"));
195     exportAction = new QAction(QIcon(":/icons/export"), tr("&Export..."), this);
196     exportAction->setToolTip(tr("Export the current view to a file"));
197
198     connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
199     connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
200     connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
201     connect(openBitcoinAction, SIGNAL(triggered()), this, SLOT(show()));
202 }
203
204 void BitcoinGUI::setClientModel(ClientModel *clientModel)
205 {
206     this->clientModel = clientModel;
207
208     if(clientModel->isTestNet())
209     {
210         QString title_testnet = windowTitle() + QString(" ") + tr("[testnet]");
211         setWindowTitle(title_testnet);
212         setWindowIcon(QIcon(":icons/bitcoin_testnet"));
213         if(trayIcon)
214         {
215             trayIcon->setToolTip(title_testnet);
216             trayIcon->setIcon(QIcon(":/icons/toolbar_testnet"));
217         }
218     }
219
220     // Keep up to date with client
221     setNumConnections(clientModel->getNumConnections());
222     connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
223
224     setNumBlocks(clientModel->getNumBlocks());
225     connect(clientModel, SIGNAL(numBlocksChanged(int)), this, SLOT(setNumBlocks(int)));
226
227     // Report errors from network/worker thread
228     connect(clientModel, SIGNAL(error(QString,QString)), this, SLOT(error(QString,QString)));
229 }
230
231 void BitcoinGUI::setWalletModel(WalletModel *walletModel)
232 {
233     this->walletModel = walletModel;
234
235     // Report errors from wallet thread
236     connect(walletModel, SIGNAL(error(QString,QString)), this, SLOT(error(QString,QString)));
237
238     // Put transaction list in tabs
239     transactionView->setModel(walletModel);
240
241     overviewPage->setModel(walletModel);
242     addressBookPage->setModel(walletModel->getAddressTableModel());
243     receiveCoinsPage->setModel(walletModel->getAddressTableModel());
244     sendCoinsPage->setModel(walletModel);
245
246     // Balloon popup for new transaction
247     connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
248             this, SLOT(incomingTransaction(QModelIndex,int,int)));
249 }
250
251 void BitcoinGUI::createTrayIcon()
252 {
253     QMenu *trayIconMenu = new QMenu(this);
254     trayIconMenu->addAction(openBitcoinAction);
255     trayIconMenu->addAction(sendCoinsAction);
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::DoubleClick)
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     // In the label we want to be less specific
351     bool spinning = true;
352     if(secs < 30*60)
353     {
354         tooltip = tr("Up to date") + QString("\n") + tooltip;
355         spinning = false;
356     }
357     else
358     {
359         tooltip = tr("Catching up...") + QString("\n") + tooltip;
360     }
361
362     tooltip += QString("\n");
363     tooltip += tr("Last received block was generated %1.").arg(text);
364
365     if(spinning)
366     {
367         labelBlocksIcon->setMovie(syncIconMovie);
368         syncIconMovie->start();
369     }
370     else
371     {
372         labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(16,16));
373     }
374
375     labelBlocksIcon->setToolTip(tooltip);
376     progressBarLabel->setToolTip(tooltip);
377     progressBar->setToolTip(tooltip);
378 }
379
380 void BitcoinGUI::error(const QString &title, const QString &message)
381 {
382     // Report errors from network/worker thread
383     if(trayIcon->supportsMessages())
384     {
385         // Show as "balloon" message if possible
386         trayIcon->showMessage(title, message, QSystemTrayIcon::Critical);
387     }
388     else
389     {
390         // Fall back to old fashioned popup dialog if not
391         QMessageBox::critical(this, title,
392             message,
393             QMessageBox::Ok, QMessageBox::Ok);
394     }
395 }
396
397 void BitcoinGUI::changeEvent(QEvent *e)
398 {
399     if (e->type() == QEvent::WindowStateChange)
400     {
401         if(clientModel->getOptionsModel()->getMinimizeToTray())
402         {
403             if (isMinimized())
404             {
405                 hide();
406                 e->ignore();
407             }
408             else
409             {
410                 e->accept();
411             }
412         }
413     }
414     QMainWindow::changeEvent(e);
415 }
416
417 void BitcoinGUI::closeEvent(QCloseEvent *event)
418 {
419     if(!clientModel->getOptionsModel()->getMinimizeToTray() &&
420        !clientModel->getOptionsModel()->getMinimizeOnClose())
421     {
422         qApp->quit();
423     }
424     QMainWindow::closeEvent(event);
425 }
426
427 void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee)
428 {
429     QString strMessage =
430         tr("This transaction is over the size limit.  You can still send it for a fee of %1, "
431           "which goes to the nodes that process your transaction and helps to support the network.  "
432           "Do you want to pay the fee?").arg(
433                 BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nFeeRequired));
434     QMessageBox::StandardButton retval = QMessageBox::question(
435           this, tr("Sending..."), strMessage,
436           QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes);
437     *payFee = (retval == QMessageBox::Yes);
438 }
439
440 void BitcoinGUI::incomingTransaction(const QModelIndex & parent, int start, int end)
441 {
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 incoming 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