diff --git a/src/qt/bitcoinamountfield.cpp b/src/qt/bitcoinamountfield.cpp index 6ab27a2c6..6065d6734 100644 --- a/src/qt/bitcoinamountfield.cpp +++ b/src/qt/bitcoinamountfield.cpp @@ -1,329 +1,329 @@ // Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include #include #include #include #include #include #include #include #include #include /** * QSpinBox that uses fixed-point numbers internally and uses our own * formatting/parsing functions. */ class AmountSpinBox : public QAbstractSpinBox { Q_OBJECT public: explicit AmountSpinBox(QWidget *parent) { setAlignment(Qt::AlignRight); connect(lineEdit(), &QLineEdit::textEdited, this, &AmountSpinBox::valueChanged); } QValidator::State validate(QString &text, int &pos) const override { if (text.isEmpty()) { return QValidator::Intermediate; } bool valid = false; parse(text, &valid); // Make sure we return Intermediate so that fixup() is called on // defocus. return valid ? QValidator::Intermediate : QValidator::Invalid; } void fixup(QString &input) const override { bool valid; Amount val; if (input.isEmpty() && !m_allow_empty) { valid = true; val = m_min_amount; } else { valid = false; val = parse(input, &valid); } if (valid) { val = qBound(m_min_amount, val, m_max_amount); input = BitcoinUnits::format(currentUnit, val, false, BitcoinUnits::separatorAlways); lineEdit()->setText(input); } } Amount value(bool *valid_out = nullptr) const { return parse(text(), valid_out); } void setValue(const Amount value) { lineEdit()->setText(BitcoinUnits::format( currentUnit, value, false, BitcoinUnits::separatorAlways)); Q_EMIT valueChanged(); } void SetAllowEmpty(bool allow) { m_allow_empty = allow; } void SetMinValue(const Amount &value) { m_min_amount = value; } void SetMaxValue(const Amount &value) { m_max_amount = value; } void stepBy(int steps) override { bool valid = false; Amount val = value(&valid); val = val + steps * singleStep; val = qBound(m_min_amount, val, m_max_amount); setValue(val); } void setDisplayUnit(int unit) { bool valid = false; Amount val(value(&valid)); currentUnit = unit; lineEdit()->setPlaceholderText(BitcoinUnits::format( currentUnit, m_min_amount, false, BitcoinUnits::separatorAlways)); if (valid) { setValue(val); } else { clear(); } } void setSingleStep(const Amount step) { singleStep = step; } QSize minimumSizeHint() const override { if (cachedMinimumSizeHint.isEmpty()) { ensurePolished(); const QFontMetrics fm(fontMetrics()); int h = lineEdit()->minimumSizeHint().height(); int w = GUIUtil::TextWidth( - fm, BitcoinUnits::format(BitcoinUnits::BCH, + fm, BitcoinUnits::format(BitcoinUnits::base, BitcoinUnits::maxMoney(), false, BitcoinUnits::separatorAlways)); // Cursor blinking space. w += 2; QStyleOptionSpinBox opt; initStyleOption(&opt); QSize hint(w, h); QSize extra(35, 6); opt.rect.setSize(hint + extra); extra += hint - style() ->subControlRect(QStyle::CC_SpinBox, &opt, QStyle::SC_SpinBoxEditField, this) .size(); // Get closer to final result by repeating the calculation. opt.rect.setSize(hint + extra); extra += hint - style() ->subControlRect(QStyle::CC_SpinBox, &opt, QStyle::SC_SpinBoxEditField, this) .size(); hint += extra; hint.setHeight(h); opt.rect = rect(); cachedMinimumSizeHint = style() ->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, this) .expandedTo(QApplication::globalStrut()); } return cachedMinimumSizeHint; } private: - int currentUnit{BitcoinUnits::BCH}; + int currentUnit{BitcoinUnits::base}; Amount singleStep{100000 * SATOSHI}; mutable QSize cachedMinimumSizeHint; bool m_allow_empty{true}; Amount m_min_amount{Amount::zero()}; Amount m_max_amount{BitcoinUnits::maxMoney()}; /** * Parse a string into a number of base monetary units and * return validity. * @note Must return 0 if !valid. */ Amount parse(const QString &text, bool *valid_out = nullptr) const { Amount val = Amount::zero(); bool valid = BitcoinUnits::parse(currentUnit, text, &val); if (valid) { if (val < Amount::zero() || val > BitcoinUnits::maxMoney()) { valid = false; } } if (valid_out) { *valid_out = valid; } return valid ? val : Amount::zero(); } protected: bool event(QEvent *event) override { if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { QKeyEvent *keyEvent = static_cast(event); if (keyEvent->key() == Qt::Key_Comma) { // Translate a comma into a period. QKeyEvent periodKeyEvent( event->type(), Qt::Key_Period, keyEvent->modifiers(), ".", keyEvent->isAutoRepeat(), keyEvent->count()); return QAbstractSpinBox::event(&periodKeyEvent); } } return QAbstractSpinBox::event(event); } StepEnabled stepEnabled() const override { if (isReadOnly()) { // Disable steps when AmountSpinBox is read-only. return StepNone; } if (text().isEmpty()) { // Allow step-up with empty field. return StepUpEnabled; } StepEnabled rv = StepNone; bool valid = false; Amount val = value(&valid); if (valid) { if (val > m_min_amount) { rv |= StepDownEnabled; } if (val < m_max_amount) { rv |= StepUpEnabled; } } return rv; } Q_SIGNALS: void valueChanged(); }; #include BitcoinAmountField::BitcoinAmountField(QWidget *parent) : QWidget(parent), amount(nullptr) { amount = new AmountSpinBox(this); amount->setLocale(QLocale::c()); amount->installEventFilter(this); amount->setMaximumWidth(240); QHBoxLayout *layout = new QHBoxLayout(this); layout->addWidget(amount); unit = new QValueComboBox(this); unit->setModel(new BitcoinUnits(this)); layout->addWidget(unit); layout->addStretch(1); layout->setContentsMargins(0, 0, 0, 0); setLayout(layout); setFocusPolicy(Qt::TabFocus); setFocusProxy(amount); // If one if the widgets changes, the combined content changes as well connect(amount, &AmountSpinBox::valueChanged, this, &BitcoinAmountField::valueChanged); connect( unit, static_cast(&QComboBox::currentIndexChanged), this, &BitcoinAmountField::unitChanged); // Set default based on configuration unitChanged(unit->currentIndex()); } void BitcoinAmountField::clear() { amount->clear(); unit->setCurrentIndex(0); } void BitcoinAmountField::setEnabled(bool fEnabled) { amount->setEnabled(fEnabled); unit->setEnabled(fEnabled); } bool BitcoinAmountField::validate() { bool valid = false; value(&valid); setValid(valid); return valid; } void BitcoinAmountField::setValid(bool valid) { if (valid) { amount->setStyleSheet(""); } else { amount->setStyleSheet(STYLE_INVALID); } } bool BitcoinAmountField::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::FocusIn) { // Clear invalid flag on focus setValid(true); } return QWidget::eventFilter(object, event); } QWidget *BitcoinAmountField::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, amount); QWidget::setTabOrder(amount, unit); return unit; } Amount BitcoinAmountField::value(bool *valid_out) const { return amount->value(valid_out); } void BitcoinAmountField::setValue(const Amount value) { amount->setValue(value); } void BitcoinAmountField::SetAllowEmpty(bool allow) { amount->SetAllowEmpty(allow); } void BitcoinAmountField::SetMinValue(const Amount &value) { amount->SetMinValue(value); } void BitcoinAmountField::SetMaxValue(const Amount &value) { amount->SetMaxValue(value); } void BitcoinAmountField::setReadOnly(bool fReadOnly) { amount->setReadOnly(fReadOnly); } void BitcoinAmountField::unitChanged(int idx) { // Use description tooltip for current unit for the combobox unit->setToolTip(unit->itemData(idx, Qt::ToolTipRole).toString()); // Determine new unit ID int newUnit = unit->itemData(idx, BitcoinUnits::UnitRole).toInt(); amount->setDisplayUnit(newUnit); } void BitcoinAmountField::setDisplayUnit(int newUnit) { unit->setValue(newUnit); } void BitcoinAmountField::setSingleStep(const Amount step) { amount->setSingleStep(step); } diff --git a/src/qt/bitcoinunits.cpp b/src/qt/bitcoinunits.cpp index 87fd0fe45..725a1ae64 100644 --- a/src/qt/bitcoinunits.cpp +++ b/src/qt/bitcoinunits.cpp @@ -1,241 +1,221 @@ // Copyright (c) 2011-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include #include #include BitcoinUnits::BitcoinUnits(QObject *parent) : QAbstractListModel(parent), unitlist(availableUnits()) {} QList BitcoinUnits::availableUnits() { QList unitlist; - unitlist.append(BCH); - unitlist.append(mBCH); - unitlist.append(uBCH); - unitlist.append(SAT); + unitlist.append(base); + unitlist.append(sub); return unitlist; } bool BitcoinUnits::valid(int unit) { switch (unit) { - case BCH: - case mBCH: - case uBCH: - case SAT: + case base: + case sub: return true; default: return false; } } QString BitcoinUnits::longName(int unit) { const auto &ticker = Currency::get().ticker; switch (unit) { - case BCH: + case base: return QString(ticker.c_str()); - case mBCH: - return QString("m") + QString(ticker.c_str()); - case uBCH: - return QString::fromUtf8("μ") + QString(ticker.c_str()); - case SAT: + case sub: return QString("Satoshi (sat)"); default: return QString("???"); } } QString BitcoinUnits::shortName(int unit) { switch (unit) { - case SAT: + case sub: return QString("sat"); default: return longName(unit); } } QString BitcoinUnits::description(int unit) { switch (unit) { - case BCH: + case base: return QString("Bitcoins"); - case mBCH: - return QString("Milli-Bitcoins (1 / 1" THIN_SP_UTF8 "000)"); - case uBCH: - return QString("Micro-Bitcoins (1 / 1" THIN_SP_UTF8 - "000" THIN_SP_UTF8 "000)"); - case SAT: + case sub: return QString("Satoshi (sat) (1 / 100" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)"); default: return QString("???"); } } -qint64 BitcoinUnits::factor(int unit) { +Amount BitcoinUnits::factor(int unit) { + const auto ¤cy = Currency::get(); switch (unit) { - case BCH: - return 100000000; - case mBCH: - return 100000; - case uBCH: - return 100; - case SAT: - return 1; + case base: + return currency.baseunit; + case sub: + return currency.subunit; default: - return 100000000; + return currency.baseunit; } } int BitcoinUnits::decimals(int unit) { switch (unit) { - case BCH: - return 8; - case mBCH: - return 5; - case uBCH: - return 2; - case SAT: + case base: + return Currency::get().decimals; + case sub: return 0; default: return 0; } } QString BitcoinUnits::format(int unit, const Amount nIn, bool fPlus, SeparatorStyle separators) { // Note: not using straight sprintf here because we do NOT want // localized number formatting. if (!valid(unit)) { // Refuse to format invalid unit return QString(); } qint64 n = qint64(nIn / SATOSHI); - qint64 coin = factor(unit); + qint64 coin = factor(unit) / SATOSHI; int num_decimals = decimals(unit); qint64 n_abs = (n > 0 ? n : -n); qint64 quotient = n_abs / coin; QString quotient_str = QString::number(quotient); // Use SI-style thin space separators as these are locale independent and // can't be confused with the decimal marker. QChar thin_sp(THIN_SP_CP); int q_size = quotient_str.size(); if (separators == separatorAlways || (separators == separatorStandard && q_size > 4)) { for (int i = 3; i < q_size; i += 3) { quotient_str.insert(q_size - i, thin_sp); } } if (n < 0) { quotient_str.insert(0, '-'); } else if (fPlus && n > 0) { quotient_str.insert(0, '+'); } if (num_decimals > 0) { qint64 remainder = n_abs % coin; QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0'); return quotient_str + QString(".") + remainder_str; } else { return quotient_str; } } // NOTE: Using formatWithUnit in an HTML context risks wrapping // quantities at the thousands separator. More subtly, it also results // in a standard space rather than a thin space, due to a bug in Qt's // XML whitespace canonicalisation // // Please take care to use formatHtmlWithUnit instead, when // appropriate. QString BitcoinUnits::formatWithUnit(int unit, const Amount amount, bool plussign, SeparatorStyle separators) { return format(unit, amount, plussign, separators) + QString(" ") + shortName(unit); } QString BitcoinUnits::formatHtmlWithUnit(int unit, const Amount amount, bool plussign, SeparatorStyle separators) { QString str(formatWithUnit(unit, amount, plussign, separators)); str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML)); return QString("%1").arg(str); } bool BitcoinUnits::parse(int unit, const QString &value, Amount *val_out) { if (!valid(unit) || value.isEmpty()) { // Refuse to parse invalid unit or empty string return false; } int num_decimals = decimals(unit); // Ignore spaces and thin spaces when parsing QStringList parts = removeSpaces(value).split("."); if (parts.size() > 2) { // More than one dot return false; } QString whole = parts[0]; QString decimals; if (parts.size() > 1) { decimals = parts[1]; } if (decimals.size() > num_decimals) { // Exceeds max precision return false; } bool ok = false; QString str = whole + decimals.leftJustified(num_decimals, '0'); if (str.size() > 18) { // Longer numbers will exceed 63 bits return false; } Amount retvalue(int64_t(str.toLongLong(&ok)) * SATOSHI); if (val_out) { *val_out = retvalue; } return ok; } QString BitcoinUnits::getAmountColumnTitle(int unit) { QString amountTitle = QObject::tr("Amount"); if (BitcoinUnits::valid(unit)) { amountTitle += " (" + BitcoinUnits::shortName(unit) + ")"; } return amountTitle; } int BitcoinUnits::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return unitlist.size(); } QVariant BitcoinUnits::data(const QModelIndex &index, int role) const { int row = index.row(); if (row >= 0 && row < unitlist.size()) { Unit unit = unitlist.at(row); switch (role) { case Qt::EditRole: case Qt::DisplayRole: return QVariant(longName(unit)); case Qt::ToolTipRole: return QVariant(description(unit)); case UnitRole: return QVariant(static_cast(unit)); } } return QVariant(); } Amount BitcoinUnits::maxMoney() { return MAX_MONEY; } diff --git a/src/qt/bitcoinunits.h b/src/qt/bitcoinunits.h index a06d08fc1..e9e09cb4a 100644 --- a/src/qt/bitcoinunits.h +++ b/src/qt/bitcoinunits.h @@ -1,109 +1,107 @@ // Copyright (c) 2011-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_BITCOINUNITS_H #define BITCOIN_QT_BITCOINUNITS_H #include #include #include // U+2009 THIN SPACE = UTF-8 E2 80 89 #define REAL_THIN_SP_CP 0x2009 #define REAL_THIN_SP_UTF8 "\xE2\x80\x89" // QMessageBox seems to have a bug whereby it doesn't display thin/hair spaces // correctly. Workaround is to display a space in a small font. If you change // this, please test that it doesn't cause the parent span to start wrapping. #define HTML_HACK_SP \ " " // Define THIN_SP_* variables to be our preferred type of thin space #define THIN_SP_CP REAL_THIN_SP_CP #define THIN_SP_UTF8 REAL_THIN_SP_UTF8 #define THIN_SP_HTML HTML_HACK_SP /** * Bitcoin unit definitions. Encapsulates parsing and formatting and serves as * list model for drop-down selection boxes. */ class BitcoinUnits : public QAbstractListModel { Q_OBJECT public: explicit BitcoinUnits(QObject *parent); /** * Bitcoin units (Bitcoin Cash unit work the same as Bitoin). * @note Source: https://en.bitcoin.it/wiki/Units. * Please add only sensible ones. */ - enum Unit { BCH, mBCH, uBCH, SAT }; + enum Unit { base, sub }; enum SeparatorStyle { separatorNever, separatorStandard, separatorAlways }; //! @name Static API //! Unit conversion and formatting ///@{ //! Get list of units, for drop-down box static QList availableUnits(); //! Is unit ID valid? static bool valid(int unit); //! Long name static QString longName(int unit); //! Short name static QString shortName(int unit); //! Longer description static QString description(int unit); //! Number of Satoshis (1e-8) per unit - static qint64 factor(int unit); + static Amount factor(int unit); //! Number of decimals left static int decimals(int unit); //! Format as string static QString format(int unit, const Amount amount, bool plussign = false, SeparatorStyle separators = separatorStandard); //! Format as string (with unit) static QString formatWithUnit(int unit, const Amount amount, bool plussign = false, SeparatorStyle separators = separatorStandard); //! Format as HTML string (with unit) static QString formatHtmlWithUnit(int unit, const Amount amount, bool plussign = false, SeparatorStyle separators = separatorStandard); //! Parse string to coin amount static bool parse(int unit, const QString &value, Amount *val_out); //! Gets title for amount column including current display unit if //! optionsModel reference available */ static QString getAmountColumnTitle(int unit); ///@} //! @name AbstractListModel implementation //! List model for unit drop-down selection box. ///@{ enum RoleIndex { /** Unit identifier */ UnitRole = Qt::UserRole }; int rowCount(const QModelIndex &parent) const override; QVariant data(const QModelIndex &index, int role) const override; ///@} static QString removeSpaces(QString text) { text.remove(' '); text.remove(QChar(THIN_SP_CP)); return text; } //! Return maximum number of base units (Satoshis) static Amount maxMoney(); private: QList unitlist; }; -typedef BitcoinUnits::Unit BitcoinUnit; - #endif // BITCOIN_QT_BITCOINUNITS_H diff --git a/src/qt/coincontroldialog.cpp b/src/qt/coincontroldialog.cpp index ad41b7f67..d2716895e 100644 --- a/src/qt/coincontroldialog.cpp +++ b/src/qt/coincontroldialog.cpp @@ -1,812 +1,812 @@ // Copyright (c) 2011-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include QList CoinControlDialog::payAmounts; bool CoinControlDialog::fSubtractFeeFromAmount = false; bool CCoinControlWidgetItem::operator<(const QTreeWidgetItem &other) const { int column = treeWidget()->sortColumn(); if (column == CoinControlDialog::COLUMN_AMOUNT || column == CoinControlDialog::COLUMN_DATE || column == CoinControlDialog::COLUMN_CONFIRMATIONS) { return data(column, Qt::UserRole).toLongLong() < other.data(column, Qt::UserRole).toLongLong(); } return QTreeWidgetItem::operator<(other); } CoinControlDialog::CoinControlDialog(CCoinControl &coin_control, WalletModel *_model, const PlatformStyle *_platformStyle, QWidget *parent) : QDialog(parent), ui(new Ui::CoinControlDialog), m_coin_control(coin_control), model(_model), platformStyle(_platformStyle) { ui->setupUi(this); // context menu actions QAction *copyAddressAction = new QAction(tr("Copy address"), this); QAction *copyLabelAction = new QAction(tr("Copy label"), this); QAction *copyAmountAction = new QAction(tr("Copy amount"), this); // we need to enable/disable this copyTransactionHashAction = new QAction(tr("Copy transaction ID"), this); // we need to enable/disable this lockAction = new QAction(tr("Lock unspent"), this); // we need to enable/disable this unlockAction = new QAction(tr("Unlock unspent"), this); // context menu contextMenu = new QMenu(this); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(copyAmountAction); contextMenu->addAction(copyTransactionHashAction); contextMenu->addSeparator(); contextMenu->addAction(lockAction); contextMenu->addAction(unlockAction); // context menu signals connect(ui->treeWidget, &QWidget::customContextMenuRequested, this, &CoinControlDialog::showMenu); connect(copyAddressAction, &QAction::triggered, this, &CoinControlDialog::copyAddress); connect(copyLabelAction, &QAction::triggered, this, &CoinControlDialog::copyLabel); connect(copyAmountAction, &QAction::triggered, this, &CoinControlDialog::copyAmount); connect(copyTransactionHashAction, &QAction::triggered, this, &CoinControlDialog::copyTransactionHash); connect(lockAction, &QAction::triggered, this, &CoinControlDialog::lockCoin); connect(unlockAction, &QAction::triggered, this, &CoinControlDialog::unlockCoin); // clipboard actions QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction *clipboardLowOutputAction = new QAction(tr("Copy dust"), this); QAction *clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, &QAction::triggered, this, &CoinControlDialog::clipboardQuantity); connect(clipboardAmountAction, &QAction::triggered, this, &CoinControlDialog::clipboardAmount); connect(clipboardFeeAction, &QAction::triggered, this, &CoinControlDialog::clipboardFee); connect(clipboardAfterFeeAction, &QAction::triggered, this, &CoinControlDialog::clipboardAfterFee); connect(clipboardBytesAction, &QAction::triggered, this, &CoinControlDialog::clipboardBytes); connect(clipboardLowOutputAction, &QAction::triggered, this, &CoinControlDialog::clipboardLowOutput); connect(clipboardChangeAction, &QAction::triggered, this, &CoinControlDialog::clipboardChange); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); // toggle tree/list mode connect(ui->radioTreeMode, &QRadioButton::toggled, this, &CoinControlDialog::radioTreeMode); connect(ui->radioListMode, &QRadioButton::toggled, this, &CoinControlDialog::radioListMode); // click on checkbox connect(ui->treeWidget, &QTreeWidget::itemChanged, this, &CoinControlDialog::viewItemChanged); // click on header ui->treeWidget->header()->setSectionsClickable(true); connect(ui->treeWidget->header(), &QHeaderView::sectionClicked, this, &CoinControlDialog::headerSectionClicked); // ok button connect(ui->buttonBox, &QDialogButtonBox::clicked, this, &CoinControlDialog::buttonBoxClicked); // (un)select all connect(ui->pushButtonSelectAll, &QPushButton::clicked, this, &CoinControlDialog::buttonSelectAllClicked); ui->treeWidget->setColumnWidth(COLUMN_CHECKBOX, 84); ui->treeWidget->setColumnWidth(COLUMN_AMOUNT, 110); ui->treeWidget->setColumnWidth(COLUMN_LABEL, 190); ui->treeWidget->setColumnWidth(COLUMN_ADDRESS, 320); ui->treeWidget->setColumnWidth(COLUMN_DATE, 130); ui->treeWidget->setColumnWidth(COLUMN_CONFIRMATIONS, 110); // default view is sorted by amount desc sortView(COLUMN_AMOUNT, Qt::DescendingOrder); // restore list mode and sortorder as a convenience feature QSettings settings; if (settings.contains("nCoinControlMode") && !settings.value("nCoinControlMode").toBool()) { ui->radioTreeMode->click(); } if (settings.contains("nCoinControlSortColumn") && settings.contains("nCoinControlSortOrder")) { sortView(settings.value("nCoinControlSortColumn").toInt(), (static_cast( settings.value("nCoinControlSortOrder").toInt()))); } GUIUtil::handleCloseWindowShortcut(this); if (_model->getOptionsModel() && _model->getAddressTableModel()) { updateView(); updateLabelLocked(); CoinControlDialog::updateLabels(m_coin_control, _model, this); } } CoinControlDialog::~CoinControlDialog() { QSettings settings; settings.setValue("nCoinControlMode", ui->radioListMode->isChecked()); settings.setValue("nCoinControlSortColumn", sortColumn); settings.setValue("nCoinControlSortOrder", (int)sortOrder); delete ui; } // ok button void CoinControlDialog::buttonBoxClicked(QAbstractButton *button) { if (ui->buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole) { // closes the dialog done(QDialog::Accepted); } } // (un)select all void CoinControlDialog::buttonSelectAllClicked() { Qt::CheckState state = Qt::Checked; for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) { if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != Qt::Unchecked) { state = Qt::Unchecked; break; } } ui->treeWidget->setEnabled(false); for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) { if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != state) { ui->treeWidget->topLevelItem(i)->setCheckState(COLUMN_CHECKBOX, state); } } ui->treeWidget->setEnabled(true); if (state == Qt::Unchecked) { // just to be sure m_coin_control.UnSelectAll(); } CoinControlDialog::updateLabels(m_coin_control, model, this); } // context menu void CoinControlDialog::showMenu(const QPoint &point) { QTreeWidgetItem *item = ui->treeWidget->itemAt(point); if (item) { contextMenuItem = item; // disable some items (like Copy Transaction ID, lock, unlock) for tree // roots in context menu if (item->data(COLUMN_ADDRESS, TxIdRole).toString().length() == 64) { COutPoint outpoint = buildOutPoint(item); // transaction hash is 64 characters (this means it is a child node, // so it is not a parent node in tree mode) copyTransactionHashAction->setEnabled(true); if (model->wallet().isLockedCoin(outpoint)) { lockAction->setEnabled(false); unlockAction->setEnabled(true); } else { lockAction->setEnabled(true); unlockAction->setEnabled(false); } } else { // this means click on parent node in tree mode -> disable all copyTransactionHashAction->setEnabled(false); lockAction->setEnabled(false); unlockAction->setEnabled(false); } // show context menu contextMenu->exec(QCursor::pos()); } } // context menu action: copy amount void CoinControlDialog::copyAmount() { GUIUtil::setClipboard( BitcoinUnits::removeSpaces(contextMenuItem->text(COLUMN_AMOUNT))); } // context menu action: copy label void CoinControlDialog::copyLabel() { if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_LABEL).length() == 0 && contextMenuItem->parent()) { GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_LABEL)); } else { GUIUtil::setClipboard(contextMenuItem->text(COLUMN_LABEL)); } } // context menu action: copy address void CoinControlDialog::copyAddress() { if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_ADDRESS).length() == 0 && contextMenuItem->parent()) { GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_ADDRESS)); } else { GUIUtil::setClipboard(contextMenuItem->text(COLUMN_ADDRESS)); } } // context menu action: copy transaction id void CoinControlDialog::copyTransactionHash() { GUIUtil::setClipboard( contextMenuItem->data(COLUMN_ADDRESS, TxIdRole).toString()); } // context menu action: lock coin void CoinControlDialog::lockCoin() { if (contextMenuItem->checkState(COLUMN_CHECKBOX) == Qt::Checked) { contextMenuItem->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); } COutPoint outpoint = buildOutPoint(contextMenuItem); model->wallet().lockCoin(outpoint); contextMenuItem->setDisabled(true); contextMenuItem->setIcon( COLUMN_CHECKBOX, platformStyle->SingleColorIcon(":/icons/lock_closed")); updateLabelLocked(); } // context menu action: unlock coin void CoinControlDialog::unlockCoin() { COutPoint outpoint = buildOutPoint(contextMenuItem); model->wallet().unlockCoin(outpoint); contextMenuItem->setDisabled(false); contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon()); updateLabelLocked(); } // copy label "Quantity" to clipboard void CoinControlDialog::clipboardQuantity() { GUIUtil::setClipboard(ui->labelCoinControlQuantity->text()); } // copy label "Amount" to clipboard void CoinControlDialog::clipboardAmount() { GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left( ui->labelCoinControlAmount->text().indexOf(" "))); } // copy label "Fee" to clipboard void CoinControlDialog::clipboardFee() { GUIUtil::setClipboard( ui->labelCoinControlFee->text() .left(ui->labelCoinControlFee->text().indexOf(" ")) .replace(ASYMP_UTF8, "")); } // copy label "After fee" to clipboard void CoinControlDialog::clipboardAfterFee() { GUIUtil::setClipboard( ui->labelCoinControlAfterFee->text() .left(ui->labelCoinControlAfterFee->text().indexOf(" ")) .replace(ASYMP_UTF8, "")); } // copy label "Bytes" to clipboard void CoinControlDialog::clipboardBytes() { GUIUtil::setClipboard( ui->labelCoinControlBytes->text().replace(ASYMP_UTF8, "")); } // copy label "Dust" to clipboard void CoinControlDialog::clipboardLowOutput() { GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text()); } // copy label "Change" to clipboard void CoinControlDialog::clipboardChange() { GUIUtil::setClipboard( ui->labelCoinControlChange->text() .left(ui->labelCoinControlChange->text().indexOf(" ")) .replace(ASYMP_UTF8, "")); } // treeview: sort void CoinControlDialog::sortView(int column, Qt::SortOrder order) { sortColumn = column; sortOrder = order; ui->treeWidget->sortItems(column, order); ui->treeWidget->header()->setSortIndicator(sortColumn, sortOrder); } // treeview: clicked on header void CoinControlDialog::headerSectionClicked(int logicalIndex) { // click on most left column -> do nothing if (logicalIndex == COLUMN_CHECKBOX) { ui->treeWidget->header()->setSortIndicator(sortColumn, sortOrder); } else { if (sortColumn == logicalIndex) { sortOrder = ((sortOrder == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder); } else { sortColumn = logicalIndex; // if label or address then default => asc, else default => desc sortOrder = ((sortColumn == COLUMN_LABEL || sortColumn == COLUMN_ADDRESS) ? Qt::AscendingOrder : Qt::DescendingOrder); } sortView(sortColumn, sortOrder); } } // toggle tree mode void CoinControlDialog::radioTreeMode(bool checked) { if (checked && model) { updateView(); } } // toggle list mode void CoinControlDialog::radioListMode(bool checked) { if (checked && model) { updateView(); } } // checkbox clicked by user void CoinControlDialog::viewItemChanged(QTreeWidgetItem *item, int column) { // transaction hash is 64 characters (this means it is a child node, so it // is not a parent node in tree mode) if (column == COLUMN_CHECKBOX && item->data(COLUMN_ADDRESS, TxIdRole).toString().length() == 64) { COutPoint outpoint = buildOutPoint(item); if (item->checkState(COLUMN_CHECKBOX) == Qt::Unchecked) { m_coin_control.UnSelect(outpoint); } else if (item->isDisabled()) { // locked (this happens if "check all" through parent node) item->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); } else { m_coin_control.Select(outpoint); } // selection changed -> update labels if (ui->treeWidget->isEnabled()) { // do not update on every click for (un)select all CoinControlDialog::updateLabels(m_coin_control, model, this); } } } // shows count of locked unspent outputs void CoinControlDialog::updateLabelLocked() { std::vector vOutpts; model->wallet().listLockedCoins(vOutpts); if (vOutpts.size() > 0) { ui->labelLocked->setText(tr("(%1 locked)").arg(vOutpts.size())); ui->labelLocked->setVisible(true); } else { ui->labelLocked->setVisible(false); } } void CoinControlDialog::updateLabels(CCoinControl &m_coin_control, WalletModel *model, QDialog *dialog) { if (!model) { return; } // nPayAmount Amount nPayAmount = Amount::zero(); bool fDust = false; for (const Amount &amount : CoinControlDialog::payAmounts) { nPayAmount += amount; if (amount > Amount::zero()) { // Assumes a p2pkh script size CTxOut txout(amount, CScript() << std::vector(24, 0)); fDust |= IsDust(txout, model->node().getDustRelayFee()); } } Amount nAmount = Amount::zero(); Amount nPayFee = Amount::zero(); Amount nAfterFee = Amount::zero(); Amount nChange = Amount::zero(); unsigned int nBytes = 0; unsigned int nBytesInputs = 0; unsigned int nQuantity = 0; std::vector vCoinControl; m_coin_control.ListSelected(vCoinControl); size_t i = 0; for (const auto &out : model->wallet().getCoins(vCoinControl)) { if (out.depth_in_main_chain < 0) { continue; } // unselect already spent, very unlikely scenario, this could happen // when selected are spent elsewhere, like rpc or another computer const COutPoint &output = vCoinControl[i++]; if (out.is_spent) { m_coin_control.UnSelect(output); continue; } // Quantity nQuantity++; // Amount nAmount += out.txout.nValue; // Bytes CTxDestination address; if (ExtractDestination(out.txout.scriptPubKey, address)) { CPubKey pubkey; PKHash *pkhash = boost::get(&address); if (pkhash && model->wallet().getPubKey(out.txout.scriptPubKey, ToKeyID(*pkhash), pubkey)) { nBytesInputs += (pubkey.IsCompressed() ? 148 : 180); } else { // in all error cases, simply assume 148 here nBytesInputs += 148; } } else { nBytesInputs += 148; } } // calculation if (nQuantity > 0) { // Bytes // always assume +1 output for change here nBytes = nBytesInputs + ((CoinControlDialog::payAmounts.size() > 0 ? CoinControlDialog::payAmounts.size() + 1 : 2) * 34) + 10; // in the subtract fee from amount case, we can tell if zero change // already and subtract the bytes, so that fee calculation afterwards is // accurate if (CoinControlDialog::fSubtractFeeFromAmount) { if (nAmount - nPayAmount == Amount::zero()) { nBytes -= 34; } } // Fee nPayFee = model->wallet().getMinimumFee(nBytes, m_coin_control); if (nPayAmount > Amount::zero()) { nChange = nAmount - nPayAmount; if (!CoinControlDialog::fSubtractFeeFromAmount) { nChange -= nPayFee; } // Never create dust outputs; if we would, just add the dust to the // fee. if (nChange > Amount::zero() && nChange < MIN_CHANGE) { // Assumes a p2pkh script size CTxOut txout(nChange, CScript() << std::vector(24, 0)); if (IsDust(txout, model->node().getDustRelayFee())) { nPayFee += nChange; nChange = Amount::zero(); if (CoinControlDialog::fSubtractFeeFromAmount) { // we didn't detect lack of change above nBytes -= 34; } } } if (nChange == Amount::zero() && !CoinControlDialog::fSubtractFeeFromAmount) { nBytes -= 34; } } // after fee nAfterFee = std::max(nAmount - nPayFee, Amount::zero()); } // actually update labels - int nDisplayUnit = BitcoinUnits::BCH; + int nDisplayUnit = BitcoinUnits::base; if (model && model->getOptionsModel()) { nDisplayUnit = model->getOptionsModel()->getDisplayUnit(); } QLabel *l1 = dialog->findChild("labelCoinControlQuantity"); QLabel *l2 = dialog->findChild("labelCoinControlAmount"); QLabel *l3 = dialog->findChild("labelCoinControlFee"); QLabel *l4 = dialog->findChild("labelCoinControlAfterFee"); QLabel *l5 = dialog->findChild("labelCoinControlBytes"); QLabel *l7 = dialog->findChild("labelCoinControlLowOutput"); QLabel *l8 = dialog->findChild("labelCoinControlChange"); // enable/disable "dust" and "change" dialog->findChild("labelCoinControlLowOutputText") ->setEnabled(nPayAmount > Amount::zero()); dialog->findChild("labelCoinControlLowOutput") ->setEnabled(nPayAmount > Amount::zero()); dialog->findChild("labelCoinControlChangeText") ->setEnabled(nPayAmount > Amount::zero()); dialog->findChild("labelCoinControlChange") ->setEnabled(nPayAmount > Amount::zero()); // stats // Quantity l1->setText(QString::number(nQuantity)); // Amount l2->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAmount)); // Fee l3->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nPayFee)); // After Fee l4->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAfterFee)); // Bytes l5->setText(((nBytes > 0) ? ASYMP_UTF8 : "") + QString::number(nBytes)); // Dust l7->setText(fDust ? tr("yes") : tr("no")); // Change l8->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nChange)); if (nPayFee > Amount::zero()) { l3->setText(ASYMP_UTF8 + l3->text()); l4->setText(ASYMP_UTF8 + l4->text()); if (nChange > Amount::zero() && !CoinControlDialog::fSubtractFeeFromAmount) { l8->setText(ASYMP_UTF8 + l8->text()); } } // turn label red when dust l7->setStyleSheet((fDust) ? "color:red;" : ""); // tool tips QString toolTipDust = tr("This label turns red if any recipient receives an amount smaller " "than the current dust threshold."); // how many satoshis the estimated fee can vary per byte we guess wrong double dFeeVary = (nBytes != 0) ? double(nPayFee / SATOSHI) / nBytes : 0; QString toolTip4 = tr("Can vary +/- %1 satoshi(s) per input.").arg(dFeeVary); l3->setToolTip(toolTip4); l4->setToolTip(toolTip4); l7->setToolTip(toolTipDust); l8->setToolTip(toolTip4); dialog->findChild("labelCoinControlFeeText") ->setToolTip(l3->toolTip()); dialog->findChild("labelCoinControlAfterFeeText") ->setToolTip(l4->toolTip()); dialog->findChild("labelCoinControlBytesText") ->setToolTip(l5->toolTip()); dialog->findChild("labelCoinControlLowOutputText") ->setToolTip(l7->toolTip()); dialog->findChild("labelCoinControlChangeText") ->setToolTip(l8->toolTip()); // Insufficient funds QLabel *label = dialog->findChild("labelCoinControlInsuffFunds"); if (label) { label->setVisible(nChange < Amount::zero()); } } COutPoint CoinControlDialog::buildOutPoint(const QTreeWidgetItem *item) { TxId txid; txid.SetHex(item->data(COLUMN_ADDRESS, TxIdRole).toString().toStdString()); return COutPoint(txid, item->data(COLUMN_ADDRESS, VOutRole).toUInt()); } void CoinControlDialog::updateView() { if (!model || !model->getOptionsModel() || !model->getAddressTableModel()) { return; } bool treeMode = ui->radioTreeMode->isChecked(); ui->treeWidget->clear(); // performance, otherwise updateLabels would be called for every checked // checkbox ui->treeWidget->setEnabled(false); ui->treeWidget->setAlternatingRowColors(!treeMode); QFlags flgCheckbox = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable; QFlags flgTristate = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsTristate; int nDisplayUnit = model->getOptionsModel()->getDisplayUnit(); for (const auto &coins : model->wallet().listCoins()) { CCoinControlWidgetItem *itemWalletAddress{nullptr}; QString sWalletAddress = QString::fromStdString( EncodeCashAddr(coins.first, model->getChainParams())); QString sWalletLabel = model->getAddressTableModel()->labelForAddress(sWalletAddress); if (sWalletLabel.isEmpty()) { sWalletLabel = tr("(no label)"); } if (treeMode) { // wallet address itemWalletAddress = new CCoinControlWidgetItem(ui->treeWidget); itemWalletAddress->setFlags(flgTristate); itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); // label itemWalletAddress->setText(COLUMN_LABEL, sWalletLabel); // address itemWalletAddress->setText(COLUMN_ADDRESS, sWalletAddress); } Amount nSum = Amount::zero(); int nChildren = 0; for (const auto &outpair : coins.second) { const COutPoint &output = std::get<0>(outpair); const interfaces::WalletTxOut &out = std::get<1>(outpair); nSum += out.txout.nValue; nChildren++; CCoinControlWidgetItem *itemOutput; if (treeMode) { itemOutput = new CCoinControlWidgetItem(itemWalletAddress); } else { itemOutput = new CCoinControlWidgetItem(ui->treeWidget); } itemOutput->setFlags(flgCheckbox); itemOutput->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); // address CTxDestination outputAddress; QString sAddress = ""; if (ExtractDestination(out.txout.scriptPubKey, outputAddress)) { sAddress = QString::fromStdString( EncodeCashAddr(outputAddress, model->getChainParams())); // if listMode or change => show bitcoin address. In tree mode, // address is not shown again for direct wallet address outputs if (!treeMode || (!(sAddress == sWalletAddress))) { itemOutput->setText(COLUMN_ADDRESS, sAddress); } } // label if (!(sAddress == sWalletAddress)) { // change tooltip from where the change comes from itemOutput->setToolTip(COLUMN_LABEL, tr("change from %1 (%2)") .arg(sWalletLabel) .arg(sWalletAddress)); itemOutput->setText(COLUMN_LABEL, tr("(change)")); } else if (!treeMode) { QString sLabel = model->getAddressTableModel()->labelForAddress(sAddress); if (sLabel.isEmpty()) { sLabel = tr("(no label)"); } itemOutput->setText(COLUMN_LABEL, sLabel); } // amount itemOutput->setText( COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.txout.nValue)); // padding so that sorting works correctly itemOutput->setData( COLUMN_AMOUNT, Qt::UserRole, QVariant(qlonglong(out.txout.nValue / SATOSHI))); // date itemOutput->setText(COLUMN_DATE, GUIUtil::dateTimeStr(out.time)); itemOutput->setData(COLUMN_DATE, Qt::UserRole, QVariant((qlonglong)out.time)); // confirmations itemOutput->setText(COLUMN_CONFIRMATIONS, QString::number(out.depth_in_main_chain)); itemOutput->setData(COLUMN_CONFIRMATIONS, Qt::UserRole, QVariant((qlonglong)out.depth_in_main_chain)); // transaction id itemOutput->setData( COLUMN_ADDRESS, TxIdRole, QString::fromStdString(output.GetTxId().GetHex())); // vout index itemOutput->setData(COLUMN_ADDRESS, VOutRole, output.GetN()); // disable locked coins if (model->wallet().isLockedCoin(output)) { // just to be sure m_coin_control.UnSelect(output); itemOutput->setDisabled(true); itemOutput->setIcon( COLUMN_CHECKBOX, platformStyle->SingleColorIcon(":/icons/lock_closed")); } // set checkbox if (m_coin_control.IsSelected(output)) { itemOutput->setCheckState(COLUMN_CHECKBOX, Qt::Checked); } } // amount if (treeMode) { itemWalletAddress->setText(COLUMN_CHECKBOX, "(" + QString::number(nChildren) + ")"); itemWalletAddress->setText( COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum)); itemWalletAddress->setData(COLUMN_AMOUNT, Qt::UserRole, QVariant(qlonglong(nSum / SATOSHI))); } } // expand all partially selected if (treeMode) { for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) { if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked) { ui->treeWidget->topLevelItem(i)->setExpanded(true); } } } // sort view sortView(sortColumn, sortOrder); ui->treeWidget->setEnabled(true); } diff --git a/src/qt/guiutil.cpp b/src/qt/guiutil.cpp index 7ad5f9dcc..5f0b09476 100644 --- a/src/qt/guiutil.cpp +++ b/src/qt/guiutil.cpp @@ -1,924 +1,924 @@ // Copyright (c) 2011-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include #include #include #include #include #include #include #include #include #include #include #include #include