Bugfix: Unspendable inputs handling
[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         setBalance(model->getBalance(), model->getBalanceWatchOnly(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance());
97         connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64, qint64)));
98         connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
99
100         // Coin Control
101         connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels()));
102         connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool)));
103         connect(model->getOptionsModel(), SIGNAL(transactionFeeChanged(qint64)), this, SLOT(coinControlUpdateLabels()));
104         ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures());
105         coinControlUpdateLabels();
106     }
107 }
108
109 SendCoinsDialog::~SendCoinsDialog()
110 {
111     delete ui;
112 }
113
114 void SendCoinsDialog::on_sendButton_clicked()
115 {
116     QList<SendCoinsRecipient> recipients;
117     bool valid = true;
118
119     if(!model)
120         return;
121
122     if (ui->lineEditCoinControlChange->isEnabled())
123     {
124         if(!ui->lineEditCoinControlChange->hasAcceptableInput() ||
125            (model && !model->validateAddress(ui->lineEditCoinControlChange->text())))
126         {
127             CoinControlDialog::coinControl->destChange = CNoDestination();
128             ui->lineEditCoinControlChange->setValid(false);
129             valid = false;
130         }
131         else
132             CoinControlDialog::coinControl->destChange = CBitcoinAddress(ui->lineEditCoinControlChange->text().toStdString()).Get();
133     }
134
135     for(int i = 0; i < ui->entries->count(); ++i)
136     {
137         SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
138         if(entry)
139         {
140             if(entry->validate())
141             {
142                 recipients.append(entry->getValue());
143             }
144             else
145             {
146                 valid = false;
147             }
148         }
149     }
150
151     if(!valid || recipients.isEmpty())
152     {
153         return;
154     }
155
156     // Format confirmation message
157     QStringList formatted;
158     foreach(const SendCoinsRecipient &rcp, recipients)
159     {
160         formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address));
161     }
162
163     fNewRecipientAllowed = false;
164
165     QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"),
166                           tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))),
167           QMessageBox::Yes|QMessageBox::Cancel,
168           QMessageBox::Cancel);
169
170     if(retval != QMessageBox::Yes)
171     {
172         fNewRecipientAllowed = true;
173         return;
174     }
175
176     WalletModel::UnlockContext ctx(model->requestUnlock());
177     if(!ctx.isValid())
178     {
179         // Unlock wallet was cancelled
180         fNewRecipientAllowed = true;
181         return;
182     }
183
184     WalletModel::SendCoinsReturn sendstatus;
185
186     if (!model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures())
187         sendstatus = model->sendCoins(recipients);
188     else
189         sendstatus = model->sendCoins(recipients, CoinControlDialog::coinControl);
190
191     switch(sendstatus.status)
192     {
193     case WalletModel::InvalidAddress:
194         QMessageBox::warning(this, tr("Send Coins"),
195             tr("The recipient address is not valid, please recheck."),
196             QMessageBox::Ok, QMessageBox::Ok);
197         break;
198     case WalletModel::InvalidAmount:
199         QMessageBox::warning(this, tr("Send Coins"),
200             tr("The amount to pay must be larger than 0."),
201             QMessageBox::Ok, QMessageBox::Ok);
202         break;
203     case WalletModel::AmountExceedsBalance:
204         QMessageBox::warning(this, tr("Send Coins"),
205             tr("The amount exceeds your balance."),
206             QMessageBox::Ok, QMessageBox::Ok);
207         break;
208     case WalletModel::AmountWithFeeExceedsBalance:
209         QMessageBox::warning(this, tr("Send Coins"),
210             tr("The total exceeds your balance when the %1 transaction fee is included.").
211             arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)),
212             QMessageBox::Ok, QMessageBox::Ok);
213         break;
214     case WalletModel::DuplicateAddress:
215         QMessageBox::warning(this, tr("Send Coins"),
216             tr("Duplicate address found, can only send to each address once per send operation."),
217             QMessageBox::Ok, QMessageBox::Ok);
218         break;
219     case WalletModel::TransactionCreationFailed:
220         QMessageBox::warning(this, tr("Send Coins"),
221             tr("Error: Transaction creation failed."),
222             QMessageBox::Ok, QMessageBox::Ok);
223         break;
224     case WalletModel::TransactionCommitFailed:
225         QMessageBox::warning(this, tr("Send Coins"),
226             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."),
227             QMessageBox::Ok, QMessageBox::Ok);
228         break;
229     case WalletModel::Aborted: // User aborted, nothing to do
230         break;
231     case WalletModel::OK:
232         accept();
233         CoinControlDialog::coinControl->UnSelectAll();
234         coinControlUpdateLabels();
235         break;
236     }
237     fNewRecipientAllowed = true;
238 }
239
240 void SendCoinsDialog::clear()
241 {
242     // Remove entries until only one left
243     while(ui->entries->count())
244     {
245         delete ui->entries->takeAt(0)->widget();
246     }
247     addEntry();
248
249     updateRemoveEnabled();
250
251     ui->sendButton->setDefault(true);
252 }
253
254 void SendCoinsDialog::reject()
255 {
256     clear();
257 }
258
259 void SendCoinsDialog::accept()
260 {
261     clear();
262 }
263
264 SendCoinsEntry *SendCoinsDialog::addEntry()
265 {
266     SendCoinsEntry *entry = new SendCoinsEntry(this);
267     entry->setModel(model);
268     ui->entries->addWidget(entry);
269     connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*)));
270     connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels()));
271
272     updateRemoveEnabled();
273
274     // Focus the field, so that entry can start immediately
275     entry->clear();
276     entry->setFocus();
277     ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());
278     QCoreApplication::instance()->processEvents();
279     QScrollBar* bar = ui->scrollArea->verticalScrollBar();
280     if(bar)
281         bar->setSliderPosition(bar->maximum());
282     return entry;
283 }
284
285 void SendCoinsDialog::updateRemoveEnabled()
286 {
287     // Remove buttons are enabled as soon as there is more than one send-entry
288     bool enabled = (ui->entries->count() > 1);
289     for(int i = 0; i < ui->entries->count(); ++i)
290     {
291         SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
292         if(entry)
293         {
294             entry->setRemoveEnabled(enabled);
295         }
296     }
297     setupTabChain(0);
298     coinControlUpdateLabels();
299 }
300
301 void SendCoinsDialog::removeEntry(SendCoinsEntry* entry)
302 {
303     delete entry;
304     updateRemoveEnabled();
305 }
306
307 QWidget *SendCoinsDialog::setupTabChain(QWidget *prev)
308 {
309     for(int i = 0; i < ui->entries->count(); ++i)
310     {
311         SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
312         if(entry)
313         {
314             prev = entry->setupTabChain(prev);
315         }
316     }
317     QWidget::setTabOrder(prev, ui->addButton);
318     QWidget::setTabOrder(ui->addButton, ui->sendButton);
319     return ui->sendButton;
320 }
321
322 void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv)
323 {
324     if(!fNewRecipientAllowed)
325         return;
326
327     SendCoinsEntry *entry = 0;
328     // Replace the first entry if it is still unused
329     if(ui->entries->count() == 1)
330     {
331         SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
332         if(first->isClear())
333         {
334             entry = first;
335         }
336     }
337     if(!entry)
338     {
339         entry = addEntry();
340     }
341
342     entry->setValue(rv);
343 }
344
345 bool SendCoinsDialog::handleURI(const QString &uri)
346 {
347     SendCoinsRecipient rv;
348     // URI has to be valid
349     if (GUIUtil::parseBitcoinURI(uri, &rv))
350     {
351         CBitcoinAddress address(rv.address.toStdString());
352         if (!address.IsValid())
353             return false;
354         pasteEntry(rv);
355         return true;
356     }
357
358     return false;
359 }
360
361 void SendCoinsDialog::setBalance(qint64 total, qint64 watchOnly, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance)
362 {
363     Q_UNUSED(stake);
364     Q_UNUSED(unconfirmedBalance);
365     Q_UNUSED(immatureBalance);
366     if(!model || !model->getOptionsModel())
367         return;
368
369     int unit = model->getOptionsModel()->getDisplayUnit();
370     ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, total - watchOnly));
371 }
372
373 void SendCoinsDialog::updateDisplayUnit()
374 {
375     if(model && model->getOptionsModel())
376     {
377         // Update labelBalance with the current balance and the current unit
378         ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance() - model->getBalanceWatchOnly()));
379     }
380 }
381
382 // Coin Control: copy label "Quantity" to clipboard
383 void SendCoinsDialog::coinControlClipboardQuantity()
384 {
385     QApplication::clipboard()->setText(ui->labelCoinControlQuantity->text());
386 }
387
388 // Coin Control: copy label "Amount" to clipboard
389 void SendCoinsDialog::coinControlClipboardAmount()
390 {
391     QApplication::clipboard()->setText(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" ")));
392 }
393
394 // Coin Control: copy label "Fee" to clipboard
395 void SendCoinsDialog::coinControlClipboardFee()
396 {
397     QApplication::clipboard()->setText(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")));
398 }
399
400 // Coin Control: copy label "After fee" to clipboard
401 void SendCoinsDialog::coinControlClipboardAfterFee()
402 {
403     QApplication::clipboard()->setText(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")));
404 }
405
406 // Coin Control: copy label "Bytes" to clipboard
407 void SendCoinsDialog::coinControlClipboardBytes()
408 {
409     QApplication::clipboard()->setText(ui->labelCoinControlBytes->text());
410 }
411
412 // Coin Control: copy label "Priority" to clipboard
413 void SendCoinsDialog::coinControlClipboardPriority()
414 {
415     QApplication::clipboard()->setText(ui->labelCoinControlPriority->text());
416 }
417
418 // Coin Control: copy label "Low output" to clipboard
419 void SendCoinsDialog::coinControlClipboardLowOutput()
420 {
421     QApplication::clipboard()->setText(ui->labelCoinControlLowOutput->text());
422 }
423
424 // Coin Control: copy label "Change" to clipboard
425 void SendCoinsDialog::coinControlClipboardChange()
426 {
427     QApplication::clipboard()->setText(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")));
428 }
429
430 // Coin Control: settings menu - coin control enabled/disabled by user
431 void SendCoinsDialog::coinControlFeatureChanged(bool checked)
432 {
433     ui->frameCoinControl->setVisible(checked);
434
435     if (!checked && model) // coin control features disabled
436         CoinControlDialog::coinControl->SetNull();
437 }
438
439 // Coin Control: button inputs -> show actual coin control dialog
440 void SendCoinsDialog::coinControlButtonClicked()
441 {
442     CoinControlDialog dlg;
443     dlg.setModel(model);
444     dlg.exec();
445     coinControlUpdateLabels();
446 }
447
448 // Coin Control: checkbox custom change address
449 void SendCoinsDialog::coinControlChangeChecked(int state)
450 {
451     if (model)
452     {
453         if (state == Qt::Checked)
454             CoinControlDialog::coinControl->destChange = CBitcoinAddress(ui->lineEditCoinControlChange->text().toStdString()).Get();
455         else
456             CoinControlDialog::coinControl->destChange = CNoDestination();
457     }
458
459     ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked));
460 //    ui->labelCoinControlChangeLabel->setEnabled((state == Qt::Checked));
461     ui->addressBookButton->setEnabled((state == Qt::Checked));
462     ui->pasteButton->setEnabled((state == Qt::Checked));
463 }
464
465 void SendCoinsDialog::on_pasteButton_clicked()
466 {
467     // Paste text from clipboard into recipient field
468     ui->lineEditCoinControlChange->setText(QApplication::clipboard()->text());
469 }
470
471 void SendCoinsDialog::on_addressBookButton_clicked()
472 {
473     if(!model)
474         return;
475     AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
476     dlg.setModel(model->getAddressTableModel());
477     if(dlg.exec())
478     {
479         ui->lineEditCoinControlChange->setText(dlg.getReturnValue());
480     }
481 }
482
483 // Coin Control: update labels
484 void SendCoinsDialog::coinControlUpdateLabels()
485 {
486     if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures())
487         return;
488
489     // set pay amounts
490     CoinControlDialog::payAmounts.clear();
491     for(int i = 0; i < ui->entries->count(); ++i)
492     {
493         SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
494         if(entry)
495             CoinControlDialog::payAmounts.append(entry->getValue().amount);
496     }
497
498     if (CoinControlDialog::coinControl->HasSelected())
499     {
500         // actual coin control calculation
501         CoinControlDialog::updateLabels(model, this);
502
503         // show coin control stats
504         ui->labelCoinControlAutomaticallySelected->hide();
505         ui->widgetCoinControl->show();
506     }
507     else
508     {
509         // hide coin control stats
510         ui->labelCoinControlAutomaticallySelected->show();
511         ui->widgetCoinControl->hide();
512         ui->labelCoinControlInsuffFunds->hide();
513     }
514 }