33 #include <QAbstractButton> 34 #include <QAbstractItemView> 35 #include <QApplication> 38 #include <QDesktopServices> 39 #include <QDoubleValidator> 40 #include <QFileDialog> 42 #include <QFontDatabase> 43 #include <QFontMetrics> 44 #include <QGuiApplication> 45 #include <QJsonObject> 47 #include <QLatin1String> 52 #include <QMouseEvent> 53 #include <QPluginLoader> 54 #include <QProgressDialog> 60 #include <QTextDocument> 79 return QLocale::system().toString(date.date(), QLocale::ShortFormat) + QString(
" ") + date.toString(
"hh:mm");
84 return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
89 if (use_embedded_font) {
90 return {
"Roboto Mono"};
92 return QFontDatabase::systemFont(QFontDatabase::FixedFont);
96 static const uint8_t
dummydata[] = {0xeb,0x15,0x23,0x1d,0xfc,0xeb,0x60,0x92,0x58,0x86,0xb6,0x7d,0x06,0x52,0x99,0x92,0x59,0x15,0xae,0xb1,0x72,0xc0,0x66,0x47};
103 for(
int i=0; i<256; ++i) {
108 sourcedata[sourcedata.size()-1] += 1;
115 parent->setFocusProxy(widget);
120 widget->setPlaceholderText(QObject::tr(
"Enter a Bitcoin address (e.g. %1)").arg(
128 QObject::connect(
new QShortcut(shortcut, button), &QShortcut::activated, [button]() { button->animateClick(); });
134 if(!uri.isValid() || uri.scheme() != QString(
"bitcoin"))
140 if (rv.
address.endsWith(
"/")) {
145 QUrlQuery uriQuery(uri);
146 QList<QPair<QString, QString> > items = uriQuery.queryItems();
147 for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
149 bool fShouldReturnFalse =
false;
150 if (i->first.startsWith(
"req-"))
152 i->first.remove(0, 4);
153 fShouldReturnFalse =
true;
156 if (i->first ==
"label")
158 rv.
label = i->second;
159 fShouldReturnFalse =
false;
161 if (i->first ==
"message")
164 fShouldReturnFalse =
false;
166 else if (i->first ==
"amount")
168 if(!i->second.isEmpty())
175 fShouldReturnFalse =
false;
178 if (fShouldReturnFalse)
190 QUrl uriInstance(uri);
196 bool bech_32 = info.
address.startsWith(QString::fromStdString(
Params().Bech32HRP() +
"1"));
198 QString ret = QString(
"bitcoin:%1").arg(bech_32 ? info.
address.toUpper() : info.
address);
207 if (!info.
label.isEmpty())
209 QString lbl(QUrl::toPercentEncoding(info.
label));
210 ret += QString(
"%1label=%2").arg(paramCount == 0 ?
"?" :
"&").arg(lbl);
216 QString msg(QUrl::toPercentEncoding(info.
message));
217 ret += QString(
"%1message=%2").arg(paramCount == 0 ?
"?" :
"&").arg(msg);
228 CTxOut txOut(amount, script);
234 QString escaped = str.toHtmlEscaped();
237 escaped = escaped.replace(
"\n",
"<br>\n");
244 return HtmlEscape(QString::fromStdString(str), fMultiLine);
249 if(!view || !view->selectionModel())
251 QModelIndexList selection = view->selectionModel()->selectedRows(column);
253 if(!selection.isEmpty())
260 QList<QModelIndex>
getEntryData(
const QAbstractItemView *view,
int column)
262 if(!view || !view->selectionModel())
263 return QList<QModelIndex>();
264 return view->selectionModel()->selectedRows(column);
270 if (selection.isEmpty())
return false;
271 return !selection.at(0).data(role).toString().isEmpty();
280 const QString &filter,
281 QString *selectedSuffixOut)
283 QString selectedFilter;
287 myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
297 QRegExp filter_re(
".* \\(\\*\\.(.*)[ \\)]");
298 QString selectedSuffix;
299 if(filter_re.exactMatch(selectedFilter))
301 selectedSuffix = filter_re.cap(1);
305 QFileInfo info(result);
306 if(!result.isEmpty())
308 if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
311 if(!result.endsWith(
"."))
313 result.append(selectedSuffix);
318 if(selectedSuffixOut)
320 *selectedSuffixOut = selectedSuffix;
326 const QString &filter,
327 QString *selectedSuffixOut)
329 QString selectedFilter;
333 myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
342 if(selectedSuffixOut)
345 QRegExp filter_re(
".* \\(\\*\\.(.*)[ \\)]");
346 QString selectedSuffix;
347 if(filter_re.exactMatch(selectedFilter))
349 selectedSuffix = filter_re.cap(1);
351 *selectedSuffixOut = selectedSuffix;
358 if(QThread::currentThread() != qApp->thread())
360 return Qt::BlockingQueuedConnection;
364 return Qt::DirectConnection;
370 QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p));
371 if (!atW)
return false;
372 return atW->window() == w;
380 &&
checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
381 &&
checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
392 if (w->isMinimized()) {
404 QObject::connect(
new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_W), w), &QShortcut::activated, w, &QWidget::close);
412 if (fs::exists(pathDebug))
423 if (!configFile.good())
429 bool res = QDesktopServices::openUrl(QUrl::fromLocalFile(
boostPathToQString(pathConfig)));
433 res = QProcess::startDetached(
"/usr/bin/open", QStringList{
"-t",
boostPathToQString(pathConfig)});
442 size_threshold(_size_threshold)
449 if(evt->type() == QEvent::ToolTipChange)
451 QWidget *widget =
static_cast<QWidget*
>(obj);
452 QString tooltip = widget->toolTip();
453 if(tooltip.size() >
size_threshold && !tooltip.startsWith(
"<qt") && !Qt::mightBeRichText(tooltip))
457 tooltip =
"<qt>" +
HtmlEscape(tooltip,
true) +
"</qt>";
458 widget->setToolTip(tooltip);
462 return QObject::eventFilter(obj, evt);
472 if (event->type() == QEvent::FocusOut) {
473 auto focus_out =
static_cast<QFocusEvent*
>(event);
474 if (focus_out->reason() != Qt::PopupFocusReason) {
475 auto label = qobject_cast<QLabel*>(watched);
477 auto flags = label->textInteractionFlags();
478 label->setTextInteractionFlags(Qt::NoTextInteraction);
479 label->setTextInteractionFlags(
flags);
484 return QObject::eventFilter(watched, event);
488 fs::path
static StartupShortcutPath()
492 return GetSpecialFolderPath(CSIDL_STARTUP) /
"Bitcoin.lnk";
494 return GetSpecialFolderPath(CSIDL_STARTUP) /
"Bitcoin (testnet).lnk";
495 return GetSpecialFolderPath(CSIDL_STARTUP) /
strprintf(
"Bitcoin (%s).lnk", chain);
501 return fs::exists(StartupShortcutPath());
507 fs::remove(StartupShortcutPath());
511 CoInitialize(
nullptr);
514 IShellLinkW* psl =
nullptr;
515 HRESULT hres = CoCreateInstance(CLSID_ShellLink,
nullptr,
516 CLSCTX_INPROC_SERVER, IID_IShellLinkW,
517 reinterpret_cast<void**>(&psl));
523 GetModuleFileNameW(
nullptr, pszExePath, ARRAYSIZE(pszExePath));
526 QString strArgs =
"-min";
531 psl->SetPath(pszExePath);
532 PathRemoveFileSpecW(pszExePath);
533 psl->SetWorkingDirectory(pszExePath);
534 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
535 psl->SetArguments(strArgs.toStdWString().c_str());
539 IPersistFile* ppf =
nullptr;
540 hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf));
544 hres = ppf->Save(StartupShortcutPath().wstring().c_str(), TRUE);
557 #elif defined(Q_OS_LINUX) 562 fs::path
static GetAutostartDir()
564 char* pszConfigHome = getenv(
"XDG_CONFIG_HOME");
565 if (pszConfigHome)
return fs::path(pszConfigHome) /
"autostart";
566 char* pszHome = getenv(
"HOME");
567 if (pszHome)
return fs::path(pszHome) /
".config" /
"autostart";
571 fs::path
static GetAutostartFilePath()
575 return GetAutostartDir() /
"bitcoin.desktop";
576 return GetAutostartDir() /
strprintf(
"bitcoin-%s.desktop", chain);
582 if (!optionFile.good())
586 while (!optionFile.eof())
588 getline(optionFile, line);
589 if (line.find(
"Hidden") != std::string::npos &&
590 line.find(
"true") != std::string::npos)
601 fs::remove(GetAutostartFilePath());
605 ssize_t r = readlink(
"/proc/self/exe", pszExePath,
sizeof(pszExePath) - 1);
608 pszExePath[r] =
'\0';
610 fs::create_directories(GetAutostartDir());
612 fsbridge::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out | std::ios_base::trunc);
613 if (!optionFile.good())
617 optionFile <<
"[Desktop Entry]\n";
618 optionFile <<
"Type=Application\n";
620 optionFile <<
"Name=Bitcoin\n";
622 optionFile <<
strprintf(
"Name=Bitcoin (%s)\n", chain);
623 optionFile <<
"Exec=" << pszExePath <<
strprintf(
" -min -chain=%s\n", chain);
624 optionFile <<
"Terminal=false\n";
625 optionFile <<
"Hidden=false\n";
640 QClipboard* clipboard = QApplication::clipboard();
641 clipboard->setText(str, QClipboard::Clipboard);
642 if (clipboard->supportsSelection()) {
643 clipboard->setText(str, QClipboard::Selection);
649 return fs::path(path.toStdString());
654 return QString::fromStdString(path.string());
675 if (prepend_direction) {
692 int days = secs / 86400;
693 int hours = (secs % 86400) / 3600;
694 int mins = (secs % 3600) / 60;
695 int seconds = secs % 60;
698 strList.append(QObject::tr(
"%1 d").arg(days));
700 strList.append(QObject::tr(
"%1 h").arg(hours));
702 strList.append(QObject::tr(
"%1 m").arg(mins));
703 if (seconds || (!days && !hours && !mins))
704 strList.append(QObject::tr(
"%1 s").arg(seconds));
706 return strList.join(
" ");
714 strList.append(QString::fromStdString(flag));
718 return strList.join(
", ");
720 return QObject::tr(
"None");
725 return (ping_time == std::chrono::microseconds::max() || ping_time == 0us) ?
727 QObject::tr(
"%1 ms").arg(QString::number((
int)(
count_microseconds(ping_time) / 1000), 10));
732 return QObject::tr(
"%1 s").arg(QString::number((
int)nTimeOffset, 10));
738 QString timeBehindText;
739 const int HOUR_IN_SECONDS = 60*60;
740 const int DAY_IN_SECONDS = 24*60*60;
741 const int WEEK_IN_SECONDS = 7*24*60*60;
742 const int YEAR_IN_SECONDS = 31556952;
745 timeBehindText = QObject::tr(
"%n second(s)",
"",secs);
747 else if(secs < 2*HOUR_IN_SECONDS)
749 timeBehindText = QObject::tr(
"%n minute(s)",
"",secs/60);
751 else if(secs < 2*DAY_IN_SECONDS)
753 timeBehindText = QObject::tr(
"%n hour(s)",
"",secs/HOUR_IN_SECONDS);
755 else if(secs < 2*WEEK_IN_SECONDS)
757 timeBehindText = QObject::tr(
"%n day(s)",
"",secs/DAY_IN_SECONDS);
759 else if(secs < YEAR_IN_SECONDS)
761 timeBehindText = QObject::tr(
"%n week(s)",
"",secs/WEEK_IN_SECONDS);
765 qint64 years = secs / YEAR_IN_SECONDS;
766 qint64 remainder = secs % YEAR_IN_SECONDS;
767 timeBehindText = QObject::tr(
"%1 and %2").arg(QObject::tr(
"%n year(s)",
"", years)).arg(QObject::tr(
"%n week(s)",
"", remainder/WEEK_IN_SECONDS));
769 return timeBehindText;
775 return QObject::tr("%1 B").arg(bytes); 776 if (bytes < 1'000
'000) 777 return QObject::tr("%1 kB").arg(bytes / 1'000);
778 if (bytes < 1
'000'000
'000) 779 return QObject::tr("%1 MB").arg(bytes / 1'000
'000); 781 return QObject::tr("%1 GB").arg(bytes / 1'000
'000'000);
785 while(font_size >= minPointSize) {
786 font.setPointSizeF(font_size);
787 QFontMetrics fm(font);
797 : QLabel{parent}, m_platform_style{platform_style}
812 if (e->type() == QEvent::PaletteChange) {
816 QLabel::changeEvent(e);
841 if (event->type() == QEvent::KeyPress) {
842 if (static_cast<QKeyEvent*>(event)->key() == Qt::Key_Escape) {
846 return QItemDelegate::eventFilter(
object, event);
853 const int margin =
TextWidth(dialog->fontMetrics(), (
"X"));
854 dialog->resize(dialog->width() + 2 * margin, dialog->height());
860 dialog->setMinimumDuration(0);
863 int TextWidth(
const QFontMetrics& fm,
const QString& text)
865 #if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)) 866 return fm.horizontalAdvance(text);
868 return fm.width(text);
875 const std::string qt_link{
"static"};
877 const std::string qt_link{
"dynamic"};
879 #ifdef QT_STATICPLUGIN 880 const std::string plugin_link{
"static"};
882 const std::string plugin_link{
"dynamic"};
884 LogPrintf(
"Qt %s (%s), plugin=%s (%s)\n", qVersion(), qt_link, QGuiApplication::platformName().toStdString(), plugin_link);
885 const auto static_plugins = QPluginLoader::staticPlugins();
886 if (static_plugins.empty()) {
890 for (
const QStaticPlugin& p : static_plugins) {
891 QJsonObject meta_data = p.metaData();
892 const std::string plugin_class = meta_data.take(QString(
"className")).toString().toStdString();
893 const int plugin_version = meta_data.take(QString(
"version")).toInt();
894 LogPrintf(
" %s, version %d\n", plugin_class, plugin_version);
898 LogPrintf(
"Style: %s / %s\n", QApplication::style()->objectName().toStdString(), QApplication::style()->metaObject()->className());
899 LogPrintf(
"System: %s, %s\n", QSysInfo::prettyProductName().toStdString(), QSysInfo::buildAbi().toStdString());
900 for (
const QScreen* s : QGuiApplication::screens()) {
901 LogPrintf(
"Screen: %s %dx%d, pixel ratio=%.1f\n", s->name().toStdString(), s->size().width(), s->size().height(), s->devicePixelRatio());
905 void PopupMenu(QMenu* menu,
const QPoint& point, QAction* at_action)
908 if (QApplication::platformName() ==
"minimal")
return;
909 menu->popup(point, at_action);
914 #if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)) 915 return date.startOfDay();
917 return QDateTime(date);
923 #if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)) 924 return !label->pixmap(Qt::ReturnByValue).isNull();
926 return label->pixmap() !=
nullptr;
936 #if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)) 937 return label->pixmap(Qt::ReturnByValue).toImage();
939 return label->pixmap()->toImage();
945 return QString(
source).replace(
947 QLatin1String(
"<a href=\"") + link + QLatin1String(
"\">") + link + QLatin1String(
"</a>"));
951 const std::exception* exception,
952 const QObject* sender,
953 const QObject* receiver)
955 std::string description = sender->metaObject()->className();
957 description += receiver->metaObject()->className();
QString formatPingTime(std::chrono::microseconds ping_time)
Format a CNodeStats.m_last_ping_time into a user-readable string or display N/A, if 0...
QDateTime StartOfDay(const QDate &date)
Returns the start-moment of the day in local time.
ToolTipToRichTextFilter(int size_threshold, QObject *parent=nullptr)
bool eventFilter(QObject *obj, QEvent *evt) override
void setThemedPixmap(const QString &image_filename, int width, int height)
Utility functions used by the Bitcoin Qt UI.
void LogQtInfo()
Writes to debug.log short info about the used Qt and the host system.
QString getOpenFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut)
Get open filename, convenience wrapper for QFileDialog::getOpenFileName.
A set of addresses that represent the hash of a string or FQDN.
fs::path GetDefaultDataDir()
void mouseReleaseEvent(QMouseEvent *event) override
We open manual connections to addresses that users explicitly requested via the addnode RPC or the -a...
Dummy value to indicate the number of NET_* constants.
bool IsValidDestinationString(const std::string &str, const CChainParams ¶ms)
void PopupMenu(QMenu *menu, const QPoint &point, QAction *at_action)
Call QMenu::popup() only on supported QT_QPA_PLATFORM.
int TextWidth(const QFontMetrics &fm, const QString &text)
Returns the distance in pixels appropriate for drawing a subsequent character after text...
bool isDust(interfaces::Node &node, const QString &address, const CAmount &amount)
static QString format(int unit, const CAmount &amount, bool plussign=false, SeparatorStyle separators=SeparatorStyle::STANDARD, bool justify=false)
Format as string.
QString dateTimeStr(const QDateTime &date)
Qt::ConnectionType blockingGUIThreadConnection()
Get connection type to call object slot in GUI thread with invokeMethod.
QString formatBytes(uint64_t bytes)
QString formatTimeOffset(int64_t nTimeOffset)
Format a CNodeCombinedStats.nTimeOffset into a user-readable string.
bool GetStartOnSystemStartup()
std::string EncodeBase58(Span< const unsigned char > input)
Why base-58 instead of standard base-64 encoding?
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
QString HtmlEscape(const QString &str, bool fMultiLine)
std::vector< std::string > serviceFlagsToStr(uint64_t flags)
Convert service flags (a bitmask of NODE_*) to human readable strings.
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg)
QFont fixedPitchFont(bool use_embedded_font)
Line edit that can be marked as "invalid" to show input validation feedback.
const char *const BITCOIN_CONF_FILENAME
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
QString formatBitcoinURI(const SendCoinsRecipient &info)
static bool parse(int unit, const QString &value, CAmount *val_out)
Parse string to coin amount.
void bringToFront(QWidget *w)
static const std::string MAIN
Chain name strings.
bool eventFilter(QObject *object, QEvent *event) override
int64_t CAmount
Amount in satoshis (Can be negative)
void mouseReleaseEvent(QMouseEvent *event) override
QString NetworkToQString(Network net)
Convert enum Network to QString.
void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent)
void changeEvent(QEvent *e) override
bool isObscured(QWidget *w)
qreal calculateIdealFontSize(int width, const QString &text, QFont font, qreal minPointSize, qreal font_size)
QString formatDurationStr(int secs)
Convert seconds into a QString with days, hours, mins, secs.
void setClipboard(const QString &str)
bool HasPixmap(const QLabel *label)
Returns true if pixmap has been set.
void handleCloseWindowShortcut(QWidget *w)
constexpr int64_t count_microseconds(std::chrono::microseconds t)
QString ConnectionTypeToQString(ConnectionType conn_type, bool prepend_direction)
Convert enum ConnectionType to QString.
bool eventFilter(QObject *watched, QEvent *event) override
bool hasEntryData(const QAbstractItemView *view, int column, int role)
Returns true if the specified field of the currently selected view entry is not empty.
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
void clicked(const QPoint &point)
Emitted when the label is clicked.
Base58 entry widget validator, checks for valid characters and removes some whitespace.
An output of a transaction.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
void copyEntryData(const QAbstractItemView *view, int column, int role)
Copy a field of the currently selected entry of a view to the clipboard.
void PolishProgressDialog(QProgressDialog *dialog)
void PrintSlotException(const std::exception *exception, const QObject *sender, const QObject *receiver)
Inbound connections are those initiated by a peer.
QImage GetImage(const QLabel *label)
fs::path GetConfigFile(const std::string &confPath)
fs::path qstringToBoostPath(const QString &path)
Convert QString to OS specific boost path through UTF-8.
ConnectionType
Different types of connections to a peer.
LabelOutOfFocusEventFilter(QObject *parent)
const CChainParams & Params()
Return the currently selected parameters.
Serialized script, used inside transaction inputs and outputs.
Feeler connections are short-lived connections made to check that a node is alive.
QString formatServicesStr(quint64 mask)
Format CNodeStats.nServices bitmask into a user-readable string.
QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut)
Get save filename, mimics QFileDialog::getSaveFileName, except that it appends a default suffix when ...
static std::string DummyAddress(const CChainParams ¶ms)
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
void ForceActivation()
Force application activation on macOS.
bool checkPoint(const QPoint &p, const QWidget *w)
void setCheckValidator(const QValidator *v)
These are the default connections that we use to connect with the network.
ThemedLabel(const PlatformStyle *platform_style, QWidget *parent=nullptr)
ClickableLabel(const PlatformStyle *platform_style, QWidget *parent=nullptr)
QString MakeHtmlLink(const QString &source, const QString &link)
Replaces a plain text link with an HTML tagged one.
static const std::string TESTNET
bool IsDust(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
bool SetStartOnSystemStartup(bool fAutoStart)
void clicked(const QPoint &point)
Emitted when the progressbar is clicked.
QString formatNiceTimeOffset(qint64 secs)
We use block-relay-only connections to help prevent against partition attacks.
QString getDefaultDataDirectory()
Determine default data directory for operating system.
QString boostPathToQString(const fs::path &path)
Convert OS specific boost path to QString through UTF-8.
AddrFetch connections are short lived connections used to solicit addresses from peers.
void updateThemedPixmap()
Bitcoin address widget validator, checks for a valid bitcoin address.
void AddButtonShortcut(QAbstractButton *button, const QKeySequence &shortcut)
Connects an additional shortcut to a QAbstractButton.
Top-level interface for a bitcoin node (bitcoind process).
const PlatformStyle * m_platform_style
static const uint8_t dummydata[]
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
const std::vector< unsigned char > & Base58Prefix(Base58Type type) const
QList< QModelIndex > getEntryData(const QAbstractItemView *view, int column)
Return a field of the currently selected entry as a QString.
Addresses from these networks are not publicly routable on the global Internet.