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