Handle unspendable inputs correctly.
[novacoin.git] / src / qt / sendcoinsdialog.cpp
1 #include "sendcoinsdialog.h"
2 #include "ui_sendcoinsdialog.h"
3
4 #include "init.h"
5 #include "walletmodel.h"
6 #include "addresstablemodel.h"
7 #include "addressbookpage.h"
8
9 #include "bitcoinunits.h"
10 #include "addressbookpage.h"
11 #include "optionsmodel.h"
12 #include "sendcoinsentry.h"
13 #include "guiutil.h"
14 #include "askpassphrasedialog.h"
15
16 #include "coincontrol.h"
17 #include "coincontroldialog.h"
18
19 #include <QMessageBox>
20 #include <QLocale>
21 #include <QTextDocument>
22 #include <QScrollBar>
23 #include <QClipboard>
24
25 SendCoinsDialog::SendCoinsDialog(QWidget *parent) :
26     QDialog(parent),
27     ui(new Ui::SendCoinsDialog),
28     model(0)
29 {
30     ui->setupUi(this);
31
32 #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
33     ui->addButton->setIcon(QIcon());
34     ui->clearButton->setIcon(QIcon());
35     ui->sendButton->setIcon(QIcon());
36 #endif
37
38 #if QT_VERSION >= 0x040700
39     /* Do not move this to the XML file, Qt before 4.7 will choke on it */
40     ui->lineEditCoinControlChange->setPlaceholderText(tr("Enter a NovaCoin address (e.g. 4Zo1ga6xuKuQ7JV7M9rGDoxdbYwV5zgQJ5)"));
41 #endif
42
43     addEntry();
44
45     connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));
46     connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
47
48     // Coin Control
49     ui->lineEditCoinControlChange->setFont(GUIUtil::bitcoinAddressFont());
50     connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked()));
51     connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int)));
52
53     // Coin Control: clipboard actions
54     QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this);
55     QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this);
56     QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this);
57     QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this);
58     QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this);
59     QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this);
60     QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this);
61     QAction *clipboardChangeAction = new QAction(tr("Copy change"), this);
62     connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity()));
63     connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount()));
64     connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee()));
65     connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee()));
66     connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes()));
67     connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority()));
68     connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput()));
69     connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange()));
70     ui->labelCoinControlQuantity->addAction(clipboardQuantityAction);
71     ui->labelCoinControlAmount->addAction(clipboardAmountAction);
72     ui->labelCoinControlFee->addAction(clipboardFeeAction);
73     ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction);
74     ui->labelCoinControlBytes->addAction(clipboardBytesAction);
75     ui->labelCoinControlPriority->addAction(clipboardPriorityAction);
76     ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction);
77     ui->labelCoinControlChange->addAction(clipboardChangeAction);
78
79     fNewRecipientAllowed = true;
80 }
81
82 void SendCoinsDialog::setModel(WalletModel *model)
83 {
84     this->model = model;
85
86     for(int i = 0; i < ui->entries->count(); ++i)
87     {
88         SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
89         if(entry)
90         {
91             entry->setModel(model);
92         }
93     }
94     if(model && model->getOptionsModel())
95     {
96         qint64 nTotal=0, nWatchOnly=0;
97         model->getBalance(nTotal, nWatchOnly);
98         setBalance(nTotal, nWatchOnly, model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance());
99         connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64, qint64)));
100         connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
101
102         // Coin Control
103         connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels()));
104         connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool)));
105         connect(model->getOptionsModel(), SIGNAL(transactionFeeChanged(qint64)), this, SLOT(coinControlUpdateLabels()));
106         ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures());
107         coinControlUpdateLabels();
108     }
109 }
110
111 SendCoinsDialog::~SendCoinsDialog()
112 {
113     delete ui;
114 }
115
116 void SendCoinsDialog::on_sendButton_clicked()
117 {
118     QList<SendCoinsRecipient> recipients;
119     bool valid = true;
120
121     if(!model)
122         return;
123
124     if (ui->lineEditCoinControlChange->isEnabled())
125     {
126         if(!ui->lineEditCoinControlChange->hasAcceptableInput() ||
127            (model && !model->validateAddress(ui->lineEditCoinControlChange->text())))
128         {
129             CoinControlDialog::coinControl->destChange = CNoDestination();
130             ui->lineEditCoinControlChange->setValid(false);
131             valid = false;
132         }
133         else
134             CoinControlDialog::coinControl->destChange = CBitcoinAddress(ui->lineEditCoinControlChange->text().toStdString()).Get();
135     }
136
137     for(int i = 0; i < ui->entries->count(); ++i)
138     {
139         SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
140         if(entry)
141         {
142             if(entry->validate())
143             {
144                 recipients.append(entry->getValue());
145             }
146             else
147             {
148                 valid = false;
149             }
150         }
151     }
152
153     if(!valid || recipients.isEmpty())
154     {
155         return;
156     }
157
158     // Format confirmation message
159     QStringList formatted;
160     foreach(const SendCoinsRecipient &rcp, recipients)
161     {
162         formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address));
163     }
164
165     fNewRecipientAllowed = false;
166
167     QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"),
168                           tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))),
169           QMessageBox::Yes|QMessageBox::Cancel,
170           QMessageBox::Cancel);
171
172     if(retval != QMessageBox::Yes)
173     {
174         fNewRecipientAllowed = true;
175         return;
176     }
177
178     WalletModel::UnlockContext ctx(model->requestUnlock());
179     if(!ctx.isValid())
180     {
181         // Unlock wallet was cancelled
182         fNewRecipientAllowed = true;
183         return;
184     }
185
186     WalletModel::SendCoinsReturn sendstatus;
187
188     if (!model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures())
189         sendstatus = model->sendCoins(recipients);
190     else
191         sendstatus = model->sendCoins(recipients, CoinControlDialog::coinControl);
192
193     switch(sendstatus.status)
194     {
195     case WalletModel::InvalidAddress:
196         QMessageBox::warning(this, tr("Send Coins"),
197             tr("The recipient address is not valid, please recheck."),
198             QMessageBox::Ok, QMessageBox::Ok);
199         break;
200     case WalletModel::InvalidAmount:
201         QMessageBox::warning(this, tr("Send Coins"),
202             tr("The amount to pay must be larger than 0."),
203             QMessageBox::Ok, QMessageBox::Ok);
204         break;
205     case WalletModel::AmountExceedsBalance:
206         QMessageBox::warning(this, tr("Send Coins"),
207             tr("The amount exceeds your balance."),
208             QMessageBox::Ok, QMessageBox::Ok);
209         break;
210     case WalletModel::AmountWithFeeExceedsBalance:
211         QMessageBox::warning(this, tr("Send Coins"),
212             tr("The total exceeds your balance when the %1 transaction fee is included.").
213             arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)),
214             QMessageBox::Ok, QMessageBox::Ok);
215         break;
216     case WalletModel::DuplicateAddress:
217         QMessageBox::warning(this, tr("Send Coins"),
218             tr("Duplicate address found, can only send to each address once per send operation."),
219             QMessageBox::Ok, QMessageBox::Ok);
220         break;
221     case WalletModel::TransactionCreationFailed:
222         QMessageBox::warning(this, tr("Send Coins"),
223             tr("Error: Transaction creation failed."),
224             QMessageBox::Ok, QMessageBox::Ok);
225         break;
226     case WalletModel::TransactionCommitFailed:
227         QMessageBox::warning(this, tr("Send Coins"),
228             tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."),
229             QMessageBox::Ok, QMessageBox::Ok);
230         break;
231     case WalletModel::Aborted: // User aborted, nothing to do
232         break;
233     case WalletModel::OK:
234         accept();
235         CoinControlDialog::coinControl->UnSelectAll();
236         coinControlUpdateLabels();
237         break;
238     }
239     fNewRecipientAllowed = true;
240 }
241
242 void SendCoinsDialog::clear()
243 {
244     // Remove entries until only one left
245     while(ui->entries->count())
246     {
247         delete ui->entries->takeAt(0)->widget();
248     }
249     addEntry();
250
251     updateRemoveEnabled();
252
253     ui->sendButton->setDefault(true);
254 }
255
256 void SendCoinsDialog::reject()
257 {
258     clear();
259 }
260
261 void SendCoinsDialog::accept()
262 {
263     clear();
264 }
265
266 SendCoinsEntry *SendCoinsDialog::addEntry()
267 {
268     SendCoinsEntry *entry = new SendCoinsEntry(this);
269     entry->setModel(model);
270     ui->entries->addWidget(entry);
271     connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*)));
272     connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels()));
273
274     updateRemoveEnabled();
275
276     // Focus the field, so that entry can start immediately
277     entry->clear();
278     entry->setFocus();
279     ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());
280     QCoreApplication::instance()->processEvents();
281     QScrollBar* bar = ui->scrollArea->verticalScrollBar();
282     if(bar)
283         bar->setSliderPosition(bar->maximum());
284     return entry;
285 }
286
287 void SendCoinsDialog::updateRemoveEnabled()
288 {
289     // Remove buttons are enabled as soon as there is more than one send-entry
290     bool enabled = (ui->entries->count() > 1);
291     for(int i = 0; i < ui->entries->count(); ++i)
292     {
293         SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
294         if(entry)
295         {
296             entry->setRemoveEnabled(enabled);
297         }
298     }
299     setupTabChain(0);
300     coinControlUpdateLabels();
301 }
302
303 void SendCoinsDialog::removeEntry(SendCoinsEntry* entry)
304 {
305     delete entry;
306     updateRemoveEnabled();
307 }
308
309 QWidget *SendCoinsDialog::setupTabChain(QWidget *prev)
310 {
311     for(int i = 0; i < ui->entries->count(); ++i)
312     {
313         SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
314         if(entry)
315         {
316             prev = entry->setupTabChain(prev);
317         }
318     }
319     QWidget::setTabOrder(prev, ui->addButton);
320     QWidget::setTabOrder(ui->addButton, ui->sendButton);
321     return ui->sendButton;
322 }
323
324 void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv)
325 {
326     if(!fNewRecipientAllowed)
327         return;
328
329     SendCoinsEntry *entry = 0;
330     // Replace the first entry if it is still unused
331     if(ui->entries->count() == 1)
332     {
333         SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
334         if(first->isClear())
335         {
336             entry = first;
337         }
338     }
339     if(!entry)
340     {
341         entry = addEntry();
342     }
343
344     entry->setValue(rv);
345 }
346
347 bool SendCoinsDialog::handleURI(const QString &uri)
348 {
349     SendCoinsRecipient rv;
350     // URI has to be valid
351     if (GUIUtil::parseBitcoinURI(uri, &rv))
352     {
353         CBitcoinAddress address(rv.address.toStdString());
354         if (!address.IsValid())
355             return false;
356         pasteEntry(rv);
357         return true;
358     }
359
360     return false;
361 }
362
363 void SendCoinsDialog::setBalance(qint64 total, qint64 watchOnly, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance)
364 {
365     Q_UNUSED(stake);
366     Q_UNUSED(unconfirmedBalance);
367     Q_UNUSED(immatureBalance);
368     if(!model || !model->getOptionsModel())
369         return;
370
371     int unit = model->getOptionsModel()->getDisplayUnit();
372     ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, total - watchOnly));
373 }
374
375 void SendCoinsDialog::updateDisplayUnit()
376 {
377     if(model && model->getOptionsModel())
378     {
379         // Update labelBalance with the current balance and the current unit
380         qint64 total=0, watchOnly=0;
381         model->getBalance(total, watchOnly);
382         ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), total - watchOnly));
383     }
384 }
385
386 // Coin Control: copy label "Quantity" to clipboard
387 void SendCoinsDialog::coinControlClipboardQuantity()
388 {
389     QApplication::clipboard()->setText(ui->labelCoinControlQuantity->text());
390 }
391
392 // Coin Control: copy label "Amount" to clipboard
393 void SendCoinsDialog::coinControlClipboardAmount()
394 {
395     QApplication::clipboard()->setText(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" ")));
396 }
397
398 // Coin Control: copy label "Fee" to clipboard
399 void SendCoinsDialog::coinControlClipboardFee()
400 {
401     QApplication::clipboard()->setText(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")));
402 }
403
404 // Coin Control: copy label "After fee" to clipboard
405 void SendCoinsDialog::coinControlClipboardAfterFee()
406 {
407     QApplication::clipboard()->setText(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")));
408 }
409
410 // Coin Control: copy label "Bytes" to clipboard
411 void SendCoinsDialog::coinControlClipboardBytes()
412 {
413     QApplication::clipboard()->setText(ui->labelCoinControlBytes->text());
414 }
415
416 // Coin Control: copy label "Priority" to clipboard
417 void SendCoinsDialog::coinControlClipboardPriority()
418 {
419     QApplication::clipboard()->setText(ui->labelCoinControlPriority->text());
420 }
421
422 // Coin Control: copy label "Low output" to clipboard
423 void SendCoinsDialog::coinControlClipboardLowOutput()
424 {
425     QApplication::clipboard()->setText(ui->labelCoinControlLowOutput->text());
426 }
427
428 // Coin Control: copy label "Change" to clipboard
429 void SendCoinsDialog::coinControlClipboardChange()
430 {
431     QApplication::clipboard()->setText(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")));
432 }
433
434 // Coin Control: settings menu - coin control enabled/disabled by user
435 void SendCoinsDialog::coinControlFeatureChanged(bool checked)
436 {
437     ui->frameCoinControl->setVisible(checked);
438
439     if (!checked && model) // coin control features disabled
440         CoinControlDialog::coinControl->SetNull();
441 }
442
443 // Coin Control: button inputs -> show actual coin control dialog
444 void SendCoinsDialog::coinControlButtonClicked()
445 {
446     CoinControlDialog dlg;
447     dlg.setModel(model);
448     dlg.exec();
449     coinControlUpdateLabels();
450 }
451
452 // Coin Control: checkbox custom change address
453 void SendCoinsDialog::coinControlChangeChecked(int state)
454 {
455     if (model)
456     {
457         if (state == Qt::Checked)
458             CoinControlDialog::coinControl->destChange = CBitcoinAddress(ui->lineEditCoinControlChange->text().toStdString()).Get();
459         else
460             CoinControlDialog::coinControl->destChange = CNoDestination();
461     }
462
463     ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked));
464 //    ui->labelCoinControlChangeLabel->setEnabled((state == Qt::Checked));
465     ui->addressBookButton->setEnabled((state == Qt::Checked));
466     ui->pasteButton->setEnabled((state == Qt::Checked));
467 }
468
469 void SendCoinsDialog::on_pasteButton_clicked()
470 {
471     // Paste text from clipboard into recipient field
472     ui->lineEditCoinControlChange->setText(QApplication::clipboard()->text());
473 }
474
475 void SendCoinsDialog::on_addressBookButton_clicked()
476 {
477     if(!model)
478         return;
479     AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
480     dlg.setModel(model->getAddressTableModel());
481     if(dlg.exec())
482     {
483         ui->lineEditCoinControlChange->setText(dlg.getReturnValue());
484     }
485 }
486
487 // Coin Control: update labels
488 void SendCoinsDialog::coinControlUpdateLabels()
489 {
490     if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures())
491         return;
492
493     // set pay amounts
494     CoinControlDialog::payAmounts.clear();
495     for(int i = 0; i < ui->entries->count(); ++i)
496     {
497         SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
498         if(entry)
499             CoinControlDialog::payAmounts.append(entry->getValue().amount);
500     }
501
502     if (CoinControlDialog::coinControl->HasSelected())
503     {
504         // actual coin control calculation
505         CoinControlDialog::updateLabels(model, this);
506
507         // show coin control stats
508         ui->labelCoinControlAutomaticallySelected->hide();
509         ui->widgetCoinControl->show();
510     }
511     else
512     {
513         // hide coin control stats
514         ui->labelCoinControlAutomaticallySelected->show();
515         ui->widgetCoinControl->hide();
516         ui->labelCoinControlInsuffFunds->hide();
517     }
518 }