Add input weight to coin control interface
[novacoin.git] / src / qt / coincontroldialog.cpp
1 #include "coincontroldialog.h"
2 #include "ui_coincontroldialog.h"
3
4 #include "init.h"
5 #include "bitcoinunits.h"
6 #include "walletmodel.h"
7 #include "addresstablemodel.h"
8 #include "optionsmodel.h"
9 #include "coincontrol.h"
10
11 #include <QApplication>
12 #include <QCheckBox>
13 #include <QClipboard>
14 #include <QColor>
15 #include <QCursor>
16 #include <QDateTime>
17 #include <QDialogButtonBox>
18 #include <QFlags>
19 #include <QIcon>
20 #include <QString>
21 #include <QTreeWidget>
22 #include <QTreeWidgetItem>
23
24 using namespace std;
25 QList<qint64> CoinControlDialog::payAmounts;
26 CCoinControl* CoinControlDialog::coinControl = new CCoinControl();
27
28 CoinControlDialog::CoinControlDialog(QWidget *parent) :
29     QDialog(parent),
30     ui(new Ui::CoinControlDialog),
31     model(0)
32 {
33     ui->setupUi(this);
34
35     // context menu actions
36     QAction *copyAddressAction = new QAction(tr("Copy address"), this);
37     QAction *copyLabelAction = new QAction(tr("Copy label"), this);
38     QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
39              copyTransactionHashAction = new QAction(tr("Copy transaction ID"), this);  // we need to enable/disable this
40              //lockAction = new QAction(tr("Lock unspent"), this);                        // we need to enable/disable this
41              //unlockAction = new QAction(tr("Unlock unspent"), this);                    // we need to enable/disable this
42
43     // context menu
44     contextMenu = new QMenu();
45     contextMenu->addAction(copyAddressAction);
46     contextMenu->addAction(copyLabelAction);
47     contextMenu->addAction(copyAmountAction);
48     contextMenu->addAction(copyTransactionHashAction);
49     //contextMenu->addSeparator();
50     //contextMenu->addAction(lockAction);
51     //contextMenu->addAction(unlockAction);
52
53     // context menu signals
54     connect(ui->treeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint)));
55     connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));
56     connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
57     connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
58     connect(copyTransactionHashAction, SIGNAL(triggered()), this, SLOT(copyTransactionHash()));
59     //connect(lockAction, SIGNAL(triggered()), this, SLOT(lockCoin()));
60     //connect(unlockAction, SIGNAL(triggered()), this, SLOT(unlockCoin()));
61
62     // clipboard actions
63     QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this);
64     QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this);
65     QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this);
66     QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this);
67     QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this);
68     QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this);
69     QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this);
70     QAction *clipboardChangeAction = new QAction(tr("Copy change"), this);
71
72     connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(clipboardQuantity()));
73     connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(clipboardAmount()));
74     connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(clipboardFee()));
75     connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(clipboardAfterFee()));
76     connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(clipboardBytes()));
77     connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(clipboardPriority()));
78     connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(clipboardLowOutput()));
79     connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(clipboardChange()));
80
81     ui->labelCoinControlQuantity->addAction(clipboardQuantityAction);
82     ui->labelCoinControlAmount->addAction(clipboardAmountAction);
83     ui->labelCoinControlFee->addAction(clipboardFeeAction);
84     ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction);
85     ui->labelCoinControlBytes->addAction(clipboardBytesAction);
86     ui->labelCoinControlPriority->addAction(clipboardPriorityAction);
87     ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction);
88     ui->labelCoinControlChange->addAction(clipboardChangeAction);
89
90     // toggle tree/list mode
91     connect(ui->radioTreeMode, SIGNAL(toggled(bool)), this, SLOT(radioTreeMode(bool)));
92     connect(ui->radioListMode, SIGNAL(toggled(bool)), this, SLOT(radioListMode(bool)));
93
94     // click on checkbox
95     connect(ui->treeWidget, SIGNAL(itemChanged( QTreeWidgetItem*, int)), this, SLOT(viewItemChanged( QTreeWidgetItem*, int)));
96
97     // click on header
98     ui->treeWidget->header()->setClickable(true);
99     connect(ui->treeWidget->header(), SIGNAL(sectionClicked(int)), this, SLOT(headerSectionClicked(int)));
100
101     // ok button
102     connect(ui->buttonBox, SIGNAL(clicked( QAbstractButton*)), this, SLOT(buttonBoxClicked(QAbstractButton*)));
103
104     // (un)select all
105     connect(ui->pushButtonSelectAll, SIGNAL(clicked()), this, SLOT(buttonSelectAllClicked()));
106
107     ui->treeWidget->setColumnWidth(COLUMN_CHECKBOX, 84);
108     ui->treeWidget->setColumnWidth(COLUMN_AMOUNT, 100);
109     ui->treeWidget->setColumnWidth(COLUMN_LABEL, 170);
110     ui->treeWidget->setColumnWidth(COLUMN_ADDRESS, 250);
111     ui->treeWidget->setColumnWidth(COLUMN_DATE, 90);
112     ui->treeWidget->setColumnWidth(COLUMN_CONFIRMATIONS, 70);
113     ui->treeWidget->setColumnWidth(COLUMN_PRIORITY, 100);
114     ui->treeWidget->setColumnWidth(COLUMN_WEIGHT, 100);
115     ui->treeWidget->setColumnHidden(COLUMN_TXHASH, true);         // store transacton hash in this column, but dont show it
116     ui->treeWidget->setColumnHidden(COLUMN_VOUT_INDEX, true);     // store vout index in this column, but dont show it
117     ui->treeWidget->setColumnHidden(COLUMN_AMOUNT_INT64, true);   // store amount int64 in this column, but dont show it
118     ui->treeWidget->setColumnHidden(COLUMN_PRIORITY_INT64, true); // store priority int64 in this column, but dont show it
119
120     // default view is sorted by amount desc
121     sortView(COLUMN_AMOUNT_INT64, Qt::DescendingOrder);
122 }
123
124 CoinControlDialog::~CoinControlDialog()
125 {
126     delete ui;
127 }
128
129 void CoinControlDialog::setModel(WalletModel *model)
130 {
131     this->model = model;
132
133     if(model && model->getOptionsModel() && model->getAddressTableModel())
134     {
135         updateView();
136         //updateLabelLocked();
137         CoinControlDialog::updateLabels(model, this);
138     }
139 }
140
141 // helper function str_pad
142 QString CoinControlDialog::strPad(QString s, int nPadLength, QString sPadding)
143 {
144     while (s.length() < nPadLength)
145         s = sPadding + s;
146
147     return s;
148 }
149
150 // ok button
151 void CoinControlDialog::buttonBoxClicked(QAbstractButton* button)
152 {
153     if (ui->buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole)
154         done(QDialog::Accepted); // closes the dialog
155 }
156
157 // (un)select all
158 void CoinControlDialog::buttonSelectAllClicked()
159 {
160     Qt::CheckState state = Qt::Checked;
161     for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
162     {
163         if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != Qt::Unchecked)
164         {
165             state = Qt::Unchecked;
166             break;
167         }
168     }
169     ui->treeWidget->setEnabled(false);
170     for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
171             if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != state)
172                 ui->treeWidget->topLevelItem(i)->setCheckState(COLUMN_CHECKBOX, state);
173     ui->treeWidget->setEnabled(true);
174     CoinControlDialog::updateLabels(model, this);
175 }
176
177 // context menu
178 void CoinControlDialog::showMenu(const QPoint &point)
179 {
180     QTreeWidgetItem *item = ui->treeWidget->itemAt(point);
181     if(item)
182     {
183         contextMenuItem = item;
184
185         // disable some items (like Copy Transaction ID, lock, unlock) for tree roots in context menu
186         if (item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode)
187         {
188             copyTransactionHashAction->setEnabled(true);
189             //if (model->isLockedCoin(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt()))
190             //{
191             //    lockAction->setEnabled(false);
192             //    unlockAction->setEnabled(true);
193             //}
194             //else
195             //{
196             //    lockAction->setEnabled(true);
197             //    unlockAction->setEnabled(false);
198             //}
199         }
200         else // this means click on parent node in tree mode -> disable all
201         {
202             copyTransactionHashAction->setEnabled(false);
203             //lockAction->setEnabled(false);
204             //unlockAction->setEnabled(false);
205         }
206
207         // show context menu
208         contextMenu->exec(QCursor::pos());
209     }
210 }
211
212 // context menu action: copy amount
213 void CoinControlDialog::copyAmount()
214 {
215     QApplication::clipboard()->setText(contextMenuItem->text(COLUMN_AMOUNT));
216 }
217
218 // context menu action: copy label
219 void CoinControlDialog::copyLabel()
220 {
221     if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_LABEL).length() == 0 && contextMenuItem->parent())
222         QApplication::clipboard()->setText(contextMenuItem->parent()->text(COLUMN_LABEL));
223     else
224         QApplication::clipboard()->setText(contextMenuItem->text(COLUMN_LABEL));
225 }
226
227 // context menu action: copy address
228 void CoinControlDialog::copyAddress()
229 {
230     if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_ADDRESS).length() == 0 && contextMenuItem->parent())
231         QApplication::clipboard()->setText(contextMenuItem->parent()->text(COLUMN_ADDRESS));
232     else
233         QApplication::clipboard()->setText(contextMenuItem->text(COLUMN_ADDRESS));
234 }
235
236 // context menu action: copy transaction id
237 void CoinControlDialog::copyTransactionHash()
238 {
239     QApplication::clipboard()->setText(contextMenuItem->text(COLUMN_TXHASH));
240 }
241
242 // context menu action: lock coin
243 /*void CoinControlDialog::lockCoin()
244 {
245     if (contextMenuItem->checkState(COLUMN_CHECKBOX) == Qt::Checked)
246         contextMenuItem->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
247
248     COutPoint outpt(uint256(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt());
249     model->lockCoin(outpt);
250     contextMenuItem->setDisabled(true);
251     contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed"));
252     updateLabelLocked();
253 }*/
254
255 // context menu action: unlock coin
256 /*void CoinControlDialog::unlockCoin()
257 {
258     COutPoint outpt(uint256(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt());
259     model->unlockCoin(outpt);
260     contextMenuItem->setDisabled(false);
261     contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon());
262     updateLabelLocked();
263 }*/
264
265 // copy label "Quantity" to clipboard
266 void CoinControlDialog::clipboardQuantity()
267 {
268     QApplication::clipboard()->setText(ui->labelCoinControlQuantity->text());
269 }
270
271 // copy label "Amount" to clipboard
272 void CoinControlDialog::clipboardAmount()
273 {
274     QApplication::clipboard()->setText(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" ")));
275 }
276
277 // copy label "Fee" to clipboard
278 void CoinControlDialog::clipboardFee()
279 {
280     QApplication::clipboard()->setText(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")));
281 }
282
283 // copy label "After fee" to clipboard
284 void CoinControlDialog::clipboardAfterFee()
285 {
286     QApplication::clipboard()->setText(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")));
287 }
288
289 // copy label "Bytes" to clipboard
290 void CoinControlDialog::clipboardBytes()
291 {
292     QApplication::clipboard()->setText(ui->labelCoinControlBytes->text());
293 }
294
295 // copy label "Priority" to clipboard
296 void CoinControlDialog::clipboardPriority()
297 {
298     QApplication::clipboard()->setText(ui->labelCoinControlPriority->text());
299 }
300
301 // copy label "Low output" to clipboard
302 void CoinControlDialog::clipboardLowOutput()
303 {
304     QApplication::clipboard()->setText(ui->labelCoinControlLowOutput->text());
305 }
306
307 // copy label "Change" to clipboard
308 void CoinControlDialog::clipboardChange()
309 {
310     QApplication::clipboard()->setText(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")));
311 }
312
313 // treeview: sort
314 void CoinControlDialog::sortView(int column, Qt::SortOrder order)
315 {
316     sortColumn = column;
317     sortOrder = order;
318     ui->treeWidget->sortItems(column, order);
319     ui->treeWidget->header()->setSortIndicator((sortColumn == COLUMN_AMOUNT_INT64 ? COLUMN_AMOUNT : (sortColumn == COLUMN_PRIORITY_INT64 ? COLUMN_PRIORITY : sortColumn)), sortOrder);
320 }
321
322 // treeview: clicked on header
323 void CoinControlDialog::headerSectionClicked(int logicalIndex)
324 {
325     if (logicalIndex == COLUMN_CHECKBOX) // click on most left column -> do nothing
326     {
327         ui->treeWidget->header()->setSortIndicator((sortColumn == COLUMN_AMOUNT_INT64 ? COLUMN_AMOUNT : (sortColumn == COLUMN_PRIORITY_INT64 ? COLUMN_PRIORITY : sortColumn)), sortOrder);
328     }
329     else
330     {
331         if (logicalIndex == COLUMN_AMOUNT) // sort by amount
332             logicalIndex = COLUMN_AMOUNT_INT64;
333
334         if (logicalIndex == COLUMN_PRIORITY) // sort by priority
335             logicalIndex = COLUMN_PRIORITY_INT64;
336
337         if (sortColumn == logicalIndex)
338             sortOrder = ((sortOrder == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder);
339         else
340         {
341             sortColumn = logicalIndex;
342             sortOrder = ((sortColumn == COLUMN_AMOUNT_INT64 || sortColumn == COLUMN_PRIORITY_INT64 || sortColumn == COLUMN_DATE || sortColumn == COLUMN_CONFIRMATIONS || sortColumn == COLUMN_WEIGHT) ? Qt::DescendingOrder : Qt::AscendingOrder); // if amount,date,conf,priority then default => desc, else default => asc
343         }
344
345         sortView(sortColumn, sortOrder);
346     }
347 }
348
349 // toggle tree mode
350 void CoinControlDialog::radioTreeMode(bool checked)
351 {
352     if (checked && model)
353         updateView();
354 }
355
356 // toggle list mode
357 void CoinControlDialog::radioListMode(bool checked)
358 {
359     if (checked && model)
360         updateView();
361 }
362
363 // checkbox clicked by user
364 void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column)
365 {
366     if (column == COLUMN_CHECKBOX && item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode)
367     {
368         COutPoint outpt(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt());
369
370         if (item->checkState(COLUMN_CHECKBOX) == Qt::Unchecked)
371             coinControl->UnSelect(outpt);
372         else if (item->isDisabled()) // locked (this happens if "check all" through parent node)
373             item->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
374         else
375             coinControl->Select(outpt);
376
377         // selection changed -> update labels
378         if (ui->treeWidget->isEnabled()) // do not update on every click for (un)select all
379             CoinControlDialog::updateLabels(model, this);
380     }
381 }
382
383 // helper function, return human readable label for priority number
384 QString CoinControlDialog::getPriorityLabel(double dPriority)
385 {
386     if (dPriority > 576000ULL) // at least medium, this number is from AllowFree(), the other thresholds are kinda random
387     {
388         if      (dPriority > 5760000000ULL)   return tr("highest");
389         else if (dPriority > 576000000ULL)    return tr("high");
390         else if (dPriority > 57600000ULL)     return tr("medium-high");
391         else                                    return tr("medium");
392     }
393     else
394     {
395         if      (dPriority > 5760ULL) return tr("low-medium");
396         else if (dPriority > 58ULL)   return tr("low");
397         else                            return tr("lowest");
398     }
399 }
400
401 // shows count of locked unspent outputs
402 /*void CoinControlDialog::updateLabelLocked()
403 {
404     vector<COutPoint> vOutpts;
405     model->listLockedCoins(vOutpts);
406     if (vOutpts.size() > 0)
407     {
408        ui->labelLocked->setText(tr("(%1 locked)").arg(vOutpts.size()));
409        ui->labelLocked->setVisible(true); 
410     }
411     else ui->labelLocked->setVisible(false);
412 }*/
413
414 void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog)
415 {
416     if (!model) return;
417
418     // nPayAmount
419     qint64 nPayAmount = 0;
420     bool fLowOutput = false;
421     bool fDust = false;
422     CTransaction txDummy;
423     foreach(const qint64 &amount, CoinControlDialog::payAmounts)
424     {
425         nPayAmount += amount;
426
427         if (amount > 0)
428         {
429             if (amount < CENT)
430                 fLowOutput = true;
431
432             CTxOut txout(amount, (CScript)vector<unsigned char>(24, 0));
433             txDummy.vout.push_back(txout);
434         }
435     }
436
437     QString sPriorityLabel      = "";
438     int64 nAmount               = 0;
439     int64 nPayFee               = 0;
440     int64 nAfterFee             = 0;
441     int64 nChange               = 0;
442     unsigned int nBytes         = 0;
443     unsigned int nBytesInputs   = 0;
444     double dPriority            = 0;
445     double dPriorityInputs      = 0;
446     unsigned int nQuantity      = 0;
447
448     vector<COutPoint> vCoinControl;
449     vector<COutput>   vOutputs;
450     coinControl->ListSelected(vCoinControl);
451     model->getOutputs(vCoinControl, vOutputs);
452
453     BOOST_FOREACH(const COutput& out, vOutputs)
454     {
455         // Quantity
456         nQuantity++;
457
458         // Amount
459         nAmount += out.tx->vout[out.i].nValue;
460
461         // Priority
462         dPriorityInputs += (double)out.tx->vout[out.i].nValue * (out.nDepth+1);
463
464         // Bytes
465         CTxDestination address;
466         if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
467         {
468             CPubKey pubkey;
469             CKeyID *keyid = boost::get< CKeyID >(&address);
470             if (keyid && model->getPubKey(*keyid, pubkey))
471                 nBytesInputs += (pubkey.IsCompressed() ? 148 : 180);
472             else
473                 nBytesInputs += 148; // in all error cases, simply assume 148 here
474         }
475         else nBytesInputs += 148;
476     }
477
478     // calculation
479     if (nQuantity > 0)
480     {
481         // Bytes
482         nBytes = nBytesInputs + ((CoinControlDialog::payAmounts.size() > 0 ? CoinControlDialog::payAmounts.size() + 1 : 2) * 34) + 10; // always assume +1 output for change here
483
484         // Priority
485         dPriority = dPriorityInputs / nBytes;
486         sPriorityLabel = CoinControlDialog::getPriorityLabel(dPriority);
487
488         // Fee
489         int64 nFee = nTransactionFee * (1 + (int64)nBytes / 1000);
490
491         // Min Fee
492         bool fAllowFree = CTransaction::AllowFree(dPriority);
493
494         // Disable free transactions until 1 July 2014
495         if (!fTestNet && txDummy.nTime < FEE_SWITCH_TIME)
496         {
497             fAllowFree = false;
498         }
499
500         int64 nMinFee = txDummy.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
501
502         nPayFee = max(nFee, nMinFee);
503
504         if (nPayAmount > 0)
505         {
506             nChange = nAmount - nPayFee - nPayAmount;
507
508             // if sub-cent change is required, the fee must be raised to at least CTransaction::nMinTxFee   
509             if (txDummy.nTime < FEE_SWITCH_TIME && !fTestNet)
510             {
511                 if (nPayFee < CENT && nChange > 0 && nChange < CENT)
512                 {
513                     if (nChange < CENT) // change < 0.01 => simply move all change to fees
514                     {
515                         nPayFee = nChange;
516                         nChange = 0;
517                     }
518                     else
519                     {
520                         nChange = nChange + nPayFee - CENT;
521                         nPayFee = CENT;
522                     }
523                 }
524             }
525
526             if (nChange == 0)
527                 nBytes -= 34;
528         }
529
530         // after fee
531         nAfterFee = nAmount - nPayFee;
532         if (nAfterFee < 0)
533             nAfterFee = 0;
534     }
535
536     // actually update labels
537     int nDisplayUnit = BitcoinUnits::BTC;
538     if (model && model->getOptionsModel())
539         nDisplayUnit = model->getOptionsModel()->getDisplayUnit();
540
541     QLabel *l1 = dialog->findChild<QLabel *>("labelCoinControlQuantity");
542     QLabel *l2 = dialog->findChild<QLabel *>("labelCoinControlAmount");
543     QLabel *l3 = dialog->findChild<QLabel *>("labelCoinControlFee");
544     QLabel *l4 = dialog->findChild<QLabel *>("labelCoinControlAfterFee");
545     QLabel *l5 = dialog->findChild<QLabel *>("labelCoinControlBytes");
546     QLabel *l6 = dialog->findChild<QLabel *>("labelCoinControlPriority");
547     QLabel *l7 = dialog->findChild<QLabel *>("labelCoinControlLowOutput");
548     QLabel *l8 = dialog->findChild<QLabel *>("labelCoinControlChange");
549
550     // enable/disable "low output" and "change"
551     dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setEnabled(nPayAmount > 0);
552     dialog->findChild<QLabel *>("labelCoinControlLowOutput")    ->setEnabled(nPayAmount > 0);
553     dialog->findChild<QLabel *>("labelCoinControlChangeText")   ->setEnabled(nPayAmount > 0);
554     dialog->findChild<QLabel *>("labelCoinControlChange")       ->setEnabled(nPayAmount > 0);
555
556     // stats
557     l1->setText(QString::number(nQuantity));                                 // Quantity        
558     l2->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAmount));        // Amount
559     l3->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nPayFee));        // Fee
560     l4->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAfterFee));      // After Fee
561     l5->setText(((nBytes > 0) ? "~" : "") + QString::number(nBytes));                                    // Bytes
562     l6->setText(sPriorityLabel);                                             // Priority
563     l7->setText((fLowOutput ? (fDust ? tr("DUST") : tr("yes")) : tr("no"))); // Low Output / Dust
564     l8->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nChange));        // Change
565
566     // turn labels "red"
567     l5->setStyleSheet((nBytes >= 5000) ? "color:red;" : "");               // Bytes >= 5000
568     l6->setStyleSheet((dPriority <= 576000) ? "color:red;" : "");         // Priority < "medium"
569     l7->setStyleSheet((fLowOutput) ? "color:red;" : "");                    // Low Output = "yes"
570     l8->setStyleSheet((nChange > 0 && nChange < CENT) ? "color:red;" : ""); // Change < 0.01BTC
571
572     // tool tips
573     l5->setToolTip(tr("This label turns red, if the transaction size is bigger than 5000 bytes.\n\n This means a fee of at least %1 per kb is required.\n\n Can vary +/- 1 Byte per input.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CENT)));
574     l6->setToolTip(tr("Transactions with higher priority get more likely into a block.\n\nThis label turns red, if the priority is smaller than \"medium\".\n\n This means a fee of at least %1 per kb is required.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CENT)));
575     l7->setToolTip(tr("This label turns red, if any recipient receives an amount smaller than %1.\n\n This means a fee of at least %2 is required. \n\n Amounts below 0.546 times the minimum relay fee are shown as DUST.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CENT)).arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CENT)));
576     l8->setToolTip(tr("This label turns red, if the change is smaller than %1.\n\n This means a fee of at least %2 is required.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CENT)).arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CENT)));
577     dialog->findChild<QLabel *>("labelCoinControlBytesText")    ->setToolTip(l5->toolTip());
578     dialog->findChild<QLabel *>("labelCoinControlPriorityText") ->setToolTip(l6->toolTip());
579     dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setToolTip(l7->toolTip());
580     dialog->findChild<QLabel *>("labelCoinControlChangeText")   ->setToolTip(l8->toolTip());
581
582     // Insufficient funds
583     QLabel *label = dialog->findChild<QLabel *>("labelCoinControlInsuffFunds");
584     if (label)
585         label->setVisible(nChange < 0);
586 }
587
588 void CoinControlDialog::updateView()
589 {
590     bool treeMode = ui->radioTreeMode->isChecked();
591
592     ui->treeWidget->clear();
593     ui->treeWidget->setEnabled(false); // performance, otherwise updateLabels would be called for every checked checkbox
594     ui->treeWidget->setAlternatingRowColors(!treeMode);
595     QFlags<Qt::ItemFlag> flgCheckbox=Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;
596     QFlags<Qt::ItemFlag> flgTristate=Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsTristate;    
597
598     int nDisplayUnit = BitcoinUnits::BTC;
599     if (model && model->getOptionsModel())
600         nDisplayUnit = model->getOptionsModel()->getDisplayUnit();
601
602     map<QString, vector<COutput> > mapCoins;
603     model->listCoins(mapCoins);
604
605     BOOST_FOREACH(PAIRTYPE(QString, vector<COutput>) coins, mapCoins)
606     {
607         QTreeWidgetItem *itemWalletAddress = new QTreeWidgetItem();
608         QString sWalletAddress = coins.first;
609         QString sWalletLabel = "";
610         if (model->getAddressTableModel())
611             sWalletLabel = model->getAddressTableModel()->labelForAddress(sWalletAddress);
612         if (sWalletLabel.length() == 0)
613             sWalletLabel = tr("(no label)");
614
615         if (treeMode)
616         {
617             // wallet address
618             ui->treeWidget->addTopLevelItem(itemWalletAddress);
619
620             itemWalletAddress->setFlags(flgTristate);
621             itemWalletAddress->setCheckState(COLUMN_CHECKBOX,Qt::Unchecked);
622
623             for (int i = 0; i < ui->treeWidget->columnCount(); i++)
624                 itemWalletAddress->setBackground(i, QColor(248, 247, 246));
625
626             // label
627             itemWalletAddress->setText(COLUMN_LABEL, sWalletLabel);
628
629             // address
630             itemWalletAddress->setText(COLUMN_ADDRESS, sWalletAddress);
631         }
632
633         int64 nSum = 0;
634         double dPrioritySum = 0;
635         int nChildren = 0;
636         int nInputSum = 0;
637         uint64 nTxWeight = 0, nTxWeightSum = 0;
638         BOOST_FOREACH(const COutput& out, coins.second)
639         {
640             int nInputSize = 148; // 180 if uncompressed public key
641             nSum += out.tx->vout[out.i].nValue;
642             model->getStakeWeightFromValue(out.tx->GetTxTime(), out.tx->vout[out.i].nValue, nTxWeight);
643             nTxWeightSum += nTxWeight;
644             nChildren++;
645
646             QTreeWidgetItem *itemOutput;
647             if (treeMode)    itemOutput = new QTreeWidgetItem(itemWalletAddress);
648             else             itemOutput = new QTreeWidgetItem(ui->treeWidget);
649             itemOutput->setFlags(flgCheckbox);
650             itemOutput->setCheckState(COLUMN_CHECKBOX,Qt::Unchecked);
651
652             // address
653             CTxDestination outputAddress;
654             QString sAddress = "";
655             if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, outputAddress))
656             {
657                 sAddress = CBitcoinAddress(outputAddress).ToString().c_str();
658
659                 // if listMode or change => show bitcoin address. In tree mode, address is not shown again for direct wallet address outputs
660                 if (!treeMode || (!(sAddress == sWalletAddress)))
661                     itemOutput->setText(COLUMN_ADDRESS, sAddress);
662
663                 CPubKey pubkey;
664                 CKeyID *keyid = boost::get< CKeyID >(&outputAddress);
665                 if (keyid && model->getPubKey(*keyid, pubkey) && !pubkey.IsCompressed())
666                     nInputSize = 180;
667             }
668
669             // label
670             if (!(sAddress == sWalletAddress)) // change
671             {
672                 // tooltip from where the change comes from
673                 itemOutput->setToolTip(COLUMN_LABEL, tr("change from %1 (%2)").arg(sWalletLabel).arg(sWalletAddress));
674                 itemOutput->setText(COLUMN_LABEL, tr("(change)"));
675             }
676             else if (!treeMode)
677             {
678                 QString sLabel = "";
679                 if (model->getAddressTableModel())
680                     sLabel = model->getAddressTableModel()->labelForAddress(sAddress);
681                 if (sLabel.length() == 0)
682                     sLabel = tr("(no label)");
683                 itemOutput->setText(COLUMN_LABEL, sLabel); 
684             }
685
686             // amount
687             itemOutput->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->vout[out.i].nValue));
688             itemOutput->setText(COLUMN_AMOUNT_INT64, strPad(QString::number(out.tx->vout[out.i].nValue), 15, " ")); // padding so that sorting works correctly
689
690             // date
691             itemOutput->setText(COLUMN_DATE, QDateTime::fromTime_t(out.tx->GetTxTime()).toUTC().toString("yy-MM-dd hh:mm"));
692
693             // immature PoS reward
694             if (out.tx->IsCoinStake() && out.tx->GetBlocksToMaturity() > 0 && out.tx->GetDepthInMainChain() > 0) {
695               itemOutput->setBackground(COLUMN_CONFIRMATIONS, Qt::red);
696               itemOutput->setDisabled(true);
697             }
698
699             // confirmations
700             itemOutput->setText(COLUMN_CONFIRMATIONS, strPad(QString::number(out.nDepth), 8, " "));
701
702             // priority
703             double dPriority = ((double)out.tx->vout[out.i].nValue  / (nInputSize + 78)) * (out.nDepth+1); // 78 = 2 * 34 + 10
704             itemOutput->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPriority));
705             itemOutput->setText(COLUMN_PRIORITY_INT64, strPad(QString::number((int64)dPriority), 20, " "));
706             dPrioritySum += (double)out.tx->vout[out.i].nValue  * (out.nDepth+1);
707             nInputSum    += nInputSize;
708
709             // List Mode Weight
710             itemOutput->setText(COLUMN_WEIGHT, strPad(QString::number(nTxWeight), 8, " "));
711
712             // transaction hash
713             uint256 txhash = out.tx->GetHash();
714             itemOutput->setText(COLUMN_TXHASH, txhash.GetHex().c_str());
715
716             // vout index
717             itemOutput->setText(COLUMN_VOUT_INDEX, QString::number(out.i));
718
719             // disable locked coins
720             /*if (model->isLockedCoin(txhash, out.i))
721             {
722                 COutPoint outpt(txhash, out.i);
723                 coinControl->UnSelect(outpt); // just to be sure
724                 itemOutput->setDisabled(true);
725                 itemOutput->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed"));
726             }*/
727
728             // set checkbox
729             if (coinControl->IsSelected(txhash, out.i))
730                 itemOutput->setCheckState(COLUMN_CHECKBOX,Qt::Checked);
731         }
732
733         // amount
734         if (treeMode)
735         {
736             dPrioritySum = dPrioritySum / (nInputSum + 78);
737             itemWalletAddress->setText(COLUMN_CHECKBOX, "(" + QString::number(nChildren) + ")");
738             itemWalletAddress->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum));
739             itemWalletAddress->setText(COLUMN_AMOUNT_INT64, strPad(QString::number(nSum), 15, " "));
740             itemWalletAddress->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPrioritySum));
741             itemWalletAddress->setText(COLUMN_PRIORITY_INT64, strPad(QString::number((int64)dPrioritySum), 20, " "));
742             itemWalletAddress->setText(COLUMN_WEIGHT, strPad(QString::number((uint64)nTxWeightSum),8," "));
743
744         }
745     }
746
747     // expand all partially selected
748     if (treeMode)
749     {
750         for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
751             if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked)
752                 ui->treeWidget->topLevelItem(i)->setExpanded(true);
753     }
754
755     // sort view
756     sortView(sortColumn, sortOrder);
757     ui->treeWidget->setEnabled(true);
758 }