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