Bitcoin Core 31.99.0
P2P Digital Currency
guiutil.cpp
Go to the documentation of this file.
1// Copyright (c) 2011-present The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <qt/guiutil.h>
6
8#include <qt/bitcoinunits.h>
9#include <qt/platformstyle.h>
12
13#include <addresstype.h>
14#include <base58.h>
15#include <chainparams.h>
16#include <common/args.h>
17#include <interfaces/node.h>
18#include <key_io.h>
19#include <logging.h>
20#include <policy/policy.h>
22#include <protocol.h>
23#include <script/script.h>
24#include <util/chaintype.h>
25#include <util/exception.h>
26#include <util/fs.h>
27#include <util/fs_helpers.h>
28#include <util/time.h>
29
30#ifdef WIN32
31#include <shellapi.h>
32#include <shlobj.h>
33#include <shlwapi.h>
34#endif
35
36#include <QAbstractButton>
37#include <QAbstractItemView>
38#include <QApplication>
39#include <QClipboard>
40#include <QDateTime>
41#include <QDesktopServices>
42#include <QDialog>
43#include <QDoubleValidator>
44#include <QFileDialog>
45#include <QFont>
46#include <QFontDatabase>
47#include <QFontMetrics>
48#include <QGuiApplication>
49#include <QJsonObject>
50#include <QKeyEvent>
51#include <QKeySequence>
52#include <QLatin1String>
53#include <QLineEdit>
54#include <QList>
55#include <QLocale>
56#include <QMenu>
57#include <QMouseEvent>
58#include <QPluginLoader>
59#include <QProgressDialog>
60#include <QRegularExpression>
61#include <QScreen>
62#include <QSettings>
63#include <QShortcut>
64#include <QSize>
65#include <QStandardPaths>
66#include <QString>
67#include <QTextDocument>
68#include <QThread>
69#include <QUrlQuery>
70#include <QtGlobal>
71
72#include <cassert>
73#include <chrono>
74#include <exception>
75#include <fstream>
76#include <string>
77#include <vector>
78
79#if defined(Q_OS_MACOS)
80
81#include <QProcess>
82
83void ForceActivation();
84#endif
85
86using namespace std::chrono_literals;
87
88namespace GUIUtil {
89
90QString dateTimeStr(const QDateTime &date)
91{
92 return QLocale::system().toString(date.date(), QLocale::ShortFormat) + QString(" ") + date.toString("hh:mm");
93}
94
95QString dateTimeStr(qint64 nTime)
96{
97 return dateTimeStr(QDateTime::fromSecsSinceEpoch(nTime));
98}
99
100QFont fixedPitchFont(bool use_embedded_font)
101{
102 if (use_embedded_font) {
103 return {"Roboto Mono"};
104 }
105 return QFontDatabase::systemFont(QFontDatabase::FixedFont);
106}
107
108// Return a pre-generated dummy bech32m address (P2TR) with invalid checksum.
109static std::string DummyAddress(const CChainParams &params)
110{
111 std::string addr;
112 switch (params.GetChainType()) {
113 case ChainType::MAIN:
114 addr = "bc1p35yvjel7srp783ztf8v6jdra7dhfzk5jaun8xz2qp6ws7z80n4tq2jku9f";
115 break;
119 addr = "tb1p35yvjel7srp783ztf8v6jdra7dhfzk5jaun8xz2qp6ws7z80n4tqa6qnlg";
120 break;
122 addr = "bcrt1p35yvjel7srp783ztf8v6jdra7dhfzk5jaun8xz2qp6ws7z80n4tqsr2427";
123 break;
124 } // no default case, so the compiler can warn about missing cases
125 assert(!addr.empty());
126
127 if (Assume(!IsValidDestinationString(addr))) return addr;
128 return {};
129}
130
131void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent)
132{
133 parent->setFocusProxy(widget);
134
135 widget->setFont(fixedPitchFont());
136 // We don't want translators to use own addresses in translations
137 // and this is the only place, where this address is supplied.
138 widget->setPlaceholderText(QObject::tr("Enter a Bitcoin address (e.g. %1)").arg(
139 QString::fromStdString(DummyAddress(Params()))));
140 widget->setValidator(new BitcoinAddressEntryValidator(parent));
142}
143
144void AddButtonShortcut(QAbstractButton* button, const QKeySequence& shortcut)
145{
146 QObject::connect(new QShortcut(shortcut, button), &QShortcut::activated, [button]() { button->animateClick(); });
147}
148
150{
151 // return if URI is not valid or is no bitcoin: URI
152 if(!uri.isValid() || uri.scheme() != QString("bitcoin"))
153 return false;
154
156 rv.address = uri.path();
157 // Trim any following forward slash which may have been added by the OS
158 if (rv.address.endsWith("/")) {
159 rv.address.truncate(rv.address.length() - 1);
160 }
161 rv.amount = 0;
162
163 QUrlQuery uriQuery(uri);
164 QList<QPair<QString, QString> > items = uriQuery.queryItems();
165 for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
166 {
167 bool fShouldReturnFalse = false;
168 if (i->first.startsWith("req-"))
169 {
170 i->first.remove(0, 4);
171 fShouldReturnFalse = true;
172 }
173
174 if (i->first == "label")
175 {
176 rv.label = i->second;
177 fShouldReturnFalse = false;
178 }
179 if (i->first == "message")
180 {
181 rv.message = i->second;
182 fShouldReturnFalse = false;
183 }
184 else if (i->first == "amount")
185 {
186 if(!i->second.isEmpty())
187 {
188 if (!BitcoinUnits::parse(BitcoinUnit::BTC, i->second, &rv.amount)) {
189 return false;
190 }
191 }
192 fShouldReturnFalse = false;
193 }
194
195 if (fShouldReturnFalse)
196 return false;
197 }
198 if(out)
199 {
200 *out = rv;
201 }
202 return true;
203}
204
206{
207 QUrl uriInstance(uri);
208 return parseBitcoinURI(uriInstance, out);
209}
210
212{
213 bool bech_32 = info.address.startsWith(QString::fromStdString(Params().Bech32HRP() + "1"));
214
215 QString ret = QString("bitcoin:%1").arg(bech_32 ? info.address.toUpper() : info.address);
216 int paramCount = 0;
217
218 if (info.amount)
219 {
220 ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnit::BTC, info.amount, false, BitcoinUnits::SeparatorStyle::NEVER));
221 paramCount++;
222 }
223
224 if (!info.label.isEmpty())
225 {
226 QString lbl(QUrl::toPercentEncoding(info.label));
227 ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl);
228 paramCount++;
229 }
230
231 if (!info.message.isEmpty())
232 {
233 QString msg(QUrl::toPercentEncoding(info.message));
234 ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg);
235 paramCount++;
236 }
237
238 return ret;
239}
240
241bool isDust(interfaces::Node& node, const QString& address, const CAmount& amount)
242{
243 CTxDestination dest = DecodeDestination(address.toStdString());
245 CTxOut txOut(amount, script);
246 return IsDust(txOut, node.getDustRelayFee());
247}
248
249QString HtmlEscape(const QString& str, bool fMultiLine)
250{
251 QString escaped = str.toHtmlEscaped();
252 if(fMultiLine)
253 {
254 escaped = escaped.replace("\n", "<br>\n");
255 }
256 return escaped;
257}
258
259QString HtmlEscape(const std::string& str, bool fMultiLine)
260{
261 return HtmlEscape(QString::fromStdString(str), fMultiLine);
262}
263
264void copyEntryData(const QAbstractItemView *view, int column, int role)
265{
266 if(!view || !view->selectionModel())
267 return;
268 QModelIndexList selection = view->selectionModel()->selectedRows(column);
269
270 if(!selection.isEmpty())
271 {
272 // Copy first item
273 setClipboard(selection.at(0).data(role).toString());
274 }
275}
276
277QList<QModelIndex> getEntryData(const QAbstractItemView *view, int column)
278{
279 if(!view || !view->selectionModel())
280 return QList<QModelIndex>();
281 return view->selectionModel()->selectedRows(column);
282}
283
284bool hasEntryData(const QAbstractItemView *view, int column, int role)
285{
286 QModelIndexList selection = getEntryData(view, column);
287 if (selection.isEmpty()) return false;
288 return !selection.at(0).data(role).toString().isEmpty();
289}
290
291void LoadFont(const QString& file_name)
292{
293 // The qminimal plugin does not provide font loading support.
294 if (QApplication::platformName() == "minimal") return;
295 const int id = QFontDatabase::addApplicationFont(file_name);
296 assert(id != -1);
297}
298
300{
302}
303
304QString ExtractFirstSuffixFromFilter(const QString& filter)
305{
306 QRegularExpression filter_re(QStringLiteral(".* \\(\\*\\.(.*)[ \\)]"), QRegularExpression::InvertedGreedinessOption);
307 QString suffix;
308 QRegularExpressionMatch m = filter_re.match(filter);
309 if (m.hasMatch()) {
310 suffix = m.captured(1);
311 }
312 return suffix;
313}
314
315QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir,
316 const QString &filter,
317 QString *selectedSuffixOut)
318{
319 QString selectedFilter;
320 QString myDir;
321 if(dir.isEmpty()) // Default to user documents location
322 {
323 myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
324 }
325 else
326 {
327 myDir = dir;
328 }
329 /* Directly convert path to native OS path separators */
330 QString result = QDir::toNativeSeparators(QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter));
331
332 QString selectedSuffix = ExtractFirstSuffixFromFilter(selectedFilter);
333
334 /* Add suffix if needed */
335 QFileInfo info(result);
336 if(!result.isEmpty())
337 {
338 if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
339 {
340 /* No suffix specified, add selected suffix */
341 if(!result.endsWith("."))
342 result.append(".");
343 result.append(selectedSuffix);
344 }
345 }
346
347 /* Return selected suffix if asked to */
348 if(selectedSuffixOut)
349 {
350 *selectedSuffixOut = selectedSuffix;
351 }
352 return result;
353}
354
355QString getOpenFileName(QWidget *parent, const QString &caption, const QString &dir,
356 const QString &filter,
357 QString *selectedSuffixOut)
358{
359 QString selectedFilter;
360 QString myDir;
361 if(dir.isEmpty()) // Default to user documents location
362 {
363 myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
364 }
365 else
366 {
367 myDir = dir;
368 }
369 /* Directly convert path to native OS path separators */
370 QString result = QDir::toNativeSeparators(QFileDialog::getOpenFileName(parent, caption, myDir, filter, &selectedFilter));
371
372 if(selectedSuffixOut)
373 {
374 *selectedSuffixOut = ExtractFirstSuffixFromFilter(selectedFilter);
375 ;
376 }
377 return result;
378}
379
381{
382 if(QThread::currentThread() != qApp->thread())
383 {
384 return Qt::BlockingQueuedConnection;
385 }
386 else
387 {
388 return Qt::DirectConnection;
389 }
390}
391
392bool checkPoint(const QPoint &p, const QWidget *w)
393{
394 QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p));
395 if (!atW) return false;
396 return atW->window() == w;
397}
398
399bool isObscured(QWidget *w)
400{
401 return !(checkPoint(QPoint(0, 0), w)
402 && checkPoint(QPoint(w->width() - 1, 0), w)
403 && checkPoint(QPoint(0, w->height() - 1), w)
404 && checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
405 && checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
406}
407
408void bringToFront(QWidget* w)
409{
410#ifdef Q_OS_MACOS
412#endif
413
414 if (w) {
415 // activateWindow() (sometimes) helps with keyboard focus on Windows
416 if (w->isMinimized()) {
417 w->showNormal();
418 } else {
419 w->show();
420 }
421 w->activateWindow();
422 w->raise();
423 }
424}
425
427{
428 QObject::connect(new QShortcut(QKeySequence(QObject::tr("Ctrl+W")), w), &QShortcut::activated, w, &QWidget::close);
429}
430
432{
433 fs::path pathDebug = LogInstance().m_file_path;
434
435 /* Open debug.log with the associated application */
436 if (fs::exists(pathDebug))
437 QDesktopServices::openUrl(QUrl::fromLocalFile(PathToQString(pathDebug)));
438}
439
441{
442 fs::path pathConfig = gArgs.GetConfigFilePath();
443
444 /* Create the file */
445 std::ofstream configFile{pathConfig.std_path(), std::ios_base::app};
446
447 if (!configFile.good())
448 return false;
449
450 configFile.close();
451
452 /* Open bitcoin.conf with the associated application */
453 bool res = QDesktopServices::openUrl(QUrl::fromLocalFile(PathToQString(pathConfig)));
454#ifdef Q_OS_MACOS
455 // Workaround for macOS-specific behavior; see #15409.
456 if (!res) {
457 res = QProcess::startDetached("/usr/bin/open", QStringList{"-t", PathToQString(pathConfig)});
458 }
459#endif
460
461 return res;
462}
463
464ToolTipToRichTextFilter::ToolTipToRichTextFilter(int _size_threshold, QObject *parent) :
465 QObject(parent),
466 size_threshold(_size_threshold)
467{
468
469}
470
471bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
472{
473 if(evt->type() == QEvent::ToolTipChange)
474 {
475 QWidget *widget = static_cast<QWidget*>(obj);
476 QString tooltip = widget->toolTip();
477 if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt") && !Qt::mightBeRichText(tooltip))
478 {
479 // Envelop with <qt></qt> to make sure Qt detects this as rich text
480 // Escape the current message as HTML and replace \n by <br>
481 tooltip = "<qt>" + HtmlEscape(tooltip, true) + "</qt>";
482 widget->setToolTip(tooltip);
483 return true;
484 }
485 }
486 return QObject::eventFilter(obj, evt);
487}
488
490 : QObject(parent)
491{
492}
493
494bool LabelOutOfFocusEventFilter::eventFilter(QObject* watched, QEvent* event)
495{
496 if (event->type() == QEvent::FocusOut) {
497 auto focus_out = static_cast<QFocusEvent*>(event);
498 if (focus_out->reason() != Qt::PopupFocusReason) {
499 auto label = qobject_cast<QLabel*>(watched);
500 if (label) {
501 auto flags = label->textInteractionFlags();
502 label->setTextInteractionFlags(Qt::NoTextInteraction);
503 label->setTextInteractionFlags(flags);
504 }
505 }
506 }
507
508 return QObject::eventFilter(watched, event);
509}
510
511#ifdef WIN32
512fs::path static StartupShortcutPath()
513{
514 ChainType chain = gArgs.GetChainType();
515 if (chain == ChainType::MAIN)
516 return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin.lnk";
517 if (chain == ChainType::TESTNET) // Remove this special case when testnet CBaseChainParams::DataDir() is incremented to "testnet4"
518 return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin (testnet).lnk";
519 return GetSpecialFolderPath(CSIDL_STARTUP) / fs::u8path(strprintf("Bitcoin (%s).lnk", ChainTypeToString(chain)));
520}
521
523{
524 // check for Bitcoin*.lnk
525 return fs::exists(StartupShortcutPath());
526}
527
528bool SetStartOnSystemStartup(bool fAutoStart)
529{
530 // If the shortcut exists already, remove it for updating
531 fs::remove(StartupShortcutPath());
532
533 if (fAutoStart)
534 {
535 CoInitialize(nullptr);
536
537 // Get a pointer to the IShellLink interface.
538 IShellLinkW* psl = nullptr;
539 HRESULT hres = CoCreateInstance(CLSID_ShellLink, nullptr,
540 CLSCTX_INPROC_SERVER, IID_IShellLinkW,
541 reinterpret_cast<void**>(&psl));
542
543 if (SUCCEEDED(hres))
544 {
545 // Get the current executable path
546 WCHAR pszExePath[MAX_PATH];
547 GetModuleFileNameW(nullptr, pszExePath, ARRAYSIZE(pszExePath));
548
549 // Start client minimized
550 QString strArgs = "-min";
551 // Set -testnet /-regtest options
552 strArgs += QString::fromStdString(strprintf(" -chain=%s", gArgs.GetChainTypeString()));
553
554 // Set the path to the shortcut target
555 psl->SetPath(pszExePath);
556 PathRemoveFileSpecW(pszExePath);
557 psl->SetWorkingDirectory(pszExePath);
558 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
559 psl->SetArguments(strArgs.toStdWString().c_str());
560
561 // Query IShellLink for the IPersistFile interface for
562 // saving the shortcut in persistent storage.
563 IPersistFile* ppf = nullptr;
564 hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf));
565 if (SUCCEEDED(hres))
566 {
567 // Save the link by calling IPersistFile::Save.
568 hres = ppf->Save(StartupShortcutPath().wstring().c_str(), TRUE);
569 ppf->Release();
570 psl->Release();
571 CoUninitialize();
572 return true;
573 }
574 psl->Release();
575 }
576 CoUninitialize();
577 return false;
578 }
579 return true;
580}
581#elif defined(Q_OS_LINUX)
582
583// Follow the Desktop Application Autostart Spec:
584// https://specifications.freedesktop.org/autostart-spec/autostart-spec-latest.html
585
586fs::path static GetAutostartDir()
587{
588 char* pszConfigHome = getenv("XDG_CONFIG_HOME");
589 if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
590 char* pszHome = getenv("HOME");
591 if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
592 return fs::path();
593}
594
595fs::path static GetAutostartFilePath()
596{
597 ChainType chain = gArgs.GetChainType();
598 if (chain == ChainType::MAIN)
599 return GetAutostartDir() / "bitcoin.desktop";
600 return GetAutostartDir() / fs::u8path(strprintf("bitcoin-%s.desktop", ChainTypeToString(chain)));
601}
602
604{
605 std::ifstream optionFile{GetAutostartFilePath().std_path()};
606 if (!optionFile.good())
607 return false;
608 // Scan through file for "Hidden=true":
609 std::string line;
610 while (!optionFile.eof())
611 {
612 getline(optionFile, line);
613 if (line.find("Hidden") != std::string::npos &&
614 line.find("true") != std::string::npos)
615 return false;
616 }
617 optionFile.close();
618
619 return true;
620}
621
622bool SetStartOnSystemStartup(bool fAutoStart)
623{
624 if (!fAutoStart)
625 fs::remove(GetAutostartFilePath());
626 else
627 {
628 char pszExePath[MAX_PATH+1];
629 ssize_t r = readlink("/proc/self/exe", pszExePath, sizeof(pszExePath));
630 if (r == -1 || r > MAX_PATH) {
631 return false;
632 }
633 pszExePath[r] = '\0';
634
635 fs::create_directories(GetAutostartDir());
636
637 std::ofstream optionFile{GetAutostartFilePath().std_path(), std::ios_base::out | std::ios_base::trunc};
638 if (!optionFile.good())
639 return false;
640 ChainType chain = gArgs.GetChainType();
641 // Write a bitcoin.desktop file to the autostart directory:
642 optionFile << "[Desktop Entry]\n";
643 optionFile << "Type=Application\n";
644 if (chain == ChainType::MAIN)
645 optionFile << "Name=Bitcoin\n";
646 else
647 optionFile << strprintf("Name=Bitcoin (%s)\n", ChainTypeToString(chain));
648 optionFile << "Exec=" << pszExePath << strprintf(" -min -chain=%s\n", ChainTypeToString(chain));
649 optionFile << "Terminal=false\n";
650 optionFile << "Hidden=false\n";
651 optionFile.close();
652 }
653 return true;
654}
655
656#else
657
658bool GetStartOnSystemStartup() { return false; }
659bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
660
661#endif
662
663void setClipboard(const QString& str)
664{
665 QClipboard* clipboard = QApplication::clipboard();
666 clipboard->setText(str, QClipboard::Clipboard);
667 if (clipboard->supportsSelection()) {
668 clipboard->setText(str, QClipboard::Selection);
669 }
670}
671
672fs::path QStringToPath(const QString &path)
673{
674 return fs::u8path(path.toStdString());
675}
676
677QString PathToQString(const fs::path &path)
678{
679 return QString::fromStdString(path.utf8string());
680}
681
683{
684 switch (net) {
685 case NET_UNROUTABLE: return QObject::tr("Unroutable");
686 //: Name of IPv4 network in peer info
687 case NET_IPV4: return QObject::tr("IPv4", "network name");
688 //: Name of IPv6 network in peer info
689 case NET_IPV6: return QObject::tr("IPv6", "network name");
690 //: Name of Tor network in peer info
691 case NET_ONION: return QObject::tr("Onion", "network name");
692 //: Name of I2P network in peer info
693 case NET_I2P: return QObject::tr("I2P", "network name");
694 //: Name of CJDNS network in peer info
695 case NET_CJDNS: return QObject::tr("CJDNS", "network name");
696 case NET_INTERNAL: return "Internal"; // should never actually happen
697 case NET_MAX: assert(false);
698 } // no default case, so the compiler can warn about missing cases
699 assert(false);
700}
701
702QString ConnectionTypeToQString(ConnectionType conn_type, bool prepend_direction)
703{
704 QString prefix;
705 if (prepend_direction) {
706 prefix = (conn_type == ConnectionType::INBOUND) ?
707 /*: An inbound connection from a peer. An inbound connection
708 is a connection initiated by a peer. */
709 QObject::tr("Inbound") :
710 /*: An outbound connection to a peer. An outbound connection
711 is a connection initiated by us. */
712 QObject::tr("Outbound") + " ";
713 }
714 switch (conn_type) {
715 case ConnectionType::INBOUND: return prefix;
716 //: Peer connection type that relays all network information.
717 case ConnectionType::OUTBOUND_FULL_RELAY: return prefix + QObject::tr("Full Relay");
718 /*: Peer connection type that relays network information about
719 blocks and not transactions or addresses. */
720 case ConnectionType::BLOCK_RELAY: return prefix + QObject::tr("Block Relay");
721 //: Peer connection type established manually through one of several methods.
722 case ConnectionType::MANUAL: return prefix + QObject::tr("Manual");
723 //: Short-lived peer connection type that tests the aliveness of known addresses.
724 case ConnectionType::FEELER: return prefix + QObject::tr("Feeler");
725 //: Short-lived peer connection type that solicits known addresses from a peer.
726 case ConnectionType::ADDR_FETCH: return prefix + QObject::tr("Address Fetch");
727 //: Short-lived peer connection type that is used for broadcasting privacy-sensitive data.
728 case ConnectionType::PRIVATE_BROADCAST: return prefix + QObject::tr("Private Broadcast");
729 } // no default case, so the compiler can warn about missing cases
730 assert(false);
731}
732
733QString formatDurationStr(std::chrono::nanoseconds dur)
734{
735 const auto d{std::chrono::duration_cast<std::chrono::days>(dur)};
736 const auto h{std::chrono::duration_cast<std::chrono::hours>(dur - d)};
737 const auto m{std::chrono::duration_cast<std::chrono::minutes>(dur - d - h)};
738 const auto s{std::chrono::duration_cast<std::chrono::seconds>(dur - d - h - m)};
739 QStringList str_list;
740 if (auto d2{d.count()}) str_list.append(QObject::tr("%1 d").arg(d2));
741 if (auto h2{h.count()}) str_list.append(QObject::tr("%1 h").arg(h2));
742 if (auto m2{m.count()}) str_list.append(QObject::tr("%1 m").arg(m2));
743 const auto s2{s.count()};
744 if (s2 || str_list.empty()) str_list.append(QObject::tr("%1 s").arg(s2));
745 return str_list.join(" ");
746}
747
749{
750 const auto age{NodeClock::now() - connected};
751 if (age >= 24h) return QObject::tr("%1 d").arg(age / 24h);
752 if (age >= 1h) return QObject::tr("%1 h").arg(age / 1h);
753 if (age >= 1min) return QObject::tr("%1 m").arg(age / 1min);
754 return QObject::tr("%1 s").arg(age / 1s);
755}
756
757QString formatServicesStr(quint64 mask)
758{
759 QStringList strList;
760
761 for (const auto& flag : serviceFlagsToStr(mask)) {
762 strList.append(QString::fromStdString(flag));
763 }
764
765 if (strList.size())
766 return strList.join(", ");
767 else
768 return QObject::tr("None");
769}
770
771QString formatPingTime(NodeClock::duration ping_time)
772{
773 return (ping_time == decltype(CNode::m_min_ping_time.load())::max() || ping_time == 0us) ?
774 QObject::tr("N/A") :
775 QObject::tr("%1 ms").arg(QString::number(Ticks<std::chrono::milliseconds>(ping_time)));
776}
777
778QString formatTimeOffset(int64_t time_offset)
779{
780 return QObject::tr("%1 s").arg(QString::number((int)time_offset, 10));
781}
782
783QString formatNiceTimeOffset(qint64 secs)
784{
785 // Represent time from last generated block in human readable text
786 QString timeBehindText;
787 const int HOUR_IN_SECONDS = 60*60;
788 const int DAY_IN_SECONDS = 24*60*60;
789 const int WEEK_IN_SECONDS = 7*24*60*60;
790 const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar
791 if(secs < 60)
792 {
793 timeBehindText = QObject::tr("%n second(s)","",secs);
794 }
795 else if(secs < 2*HOUR_IN_SECONDS)
796 {
797 timeBehindText = QObject::tr("%n minute(s)","",secs/60);
798 }
799 else if(secs < 2*DAY_IN_SECONDS)
800 {
801 timeBehindText = QObject::tr("%n hour(s)","",secs/HOUR_IN_SECONDS);
802 }
803 else if(secs < 2*WEEK_IN_SECONDS)
804 {
805 timeBehindText = QObject::tr("%n day(s)","",secs/DAY_IN_SECONDS);
806 }
807 else if(secs < YEAR_IN_SECONDS)
808 {
809 timeBehindText = QObject::tr("%n week(s)","",secs/WEEK_IN_SECONDS);
810 }
811 else
812 {
813 qint64 years = secs / YEAR_IN_SECONDS;
814 qint64 remainder = secs % YEAR_IN_SECONDS;
815 timeBehindText = QObject::tr("%1 and %2").arg(QObject::tr("%n year(s)", "", years)).arg(QObject::tr("%n week(s)","", remainder/WEEK_IN_SECONDS));
816 }
817 return timeBehindText;
818}
819
820QString formatBytes(uint64_t bytes)
821{
822 if (bytes < 1'000)
823 return QObject::tr("%1 B").arg(bytes);
824 if (bytes < 1'000'000)
825 return QObject::tr("%1 kB").arg(bytes / 1'000);
826 if (bytes < 1'000'000'000)
827 return QObject::tr("%1 MB").arg(bytes / 1'000'000);
828
829 return QObject::tr("%1 GB").arg(bytes / 1'000'000'000);
830}
831
832qreal calculateIdealFontSize(int width, const QString& text, QFont font, qreal minPointSize, qreal font_size) {
833 while(font_size >= minPointSize) {
834 font.setPointSizeF(font_size);
835 QFontMetrics fm(font);
836 if (TextWidth(fm, text) < width) {
837 break;
838 }
839 font_size -= 0.5;
840 }
841 return font_size;
842}
843
844ThemedLabel::ThemedLabel(const PlatformStyle* platform_style, QWidget* parent)
845 : QLabel{parent}, m_platform_style{platform_style}
846{
848}
849
850void ThemedLabel::setThemedPixmap(const QString& image_filename, int width, int height)
851{
852 m_image_filename = image_filename;
853 m_pixmap_width = width;
854 m_pixmap_height = height;
856}
857
859{
860 if (e->type() == QEvent::PaletteChange) {
862 }
863
864 QLabel::changeEvent(e);
865}
866
868{
870}
871
872ClickableLabel::ClickableLabel(const PlatformStyle* platform_style, QWidget* parent)
873 : ThemedLabel{platform_style, parent}
874{
875}
876
877void ClickableLabel::mouseReleaseEvent(QMouseEvent *event)
878{
879 Q_EMIT clicked(event->pos());
880}
881
883{
884 Q_EMIT clicked(event->pos());
885}
886
887bool ItemDelegate::eventFilter(QObject *object, QEvent *event)
888{
889 if (event->type() == QEvent::KeyPress) {
890 if (static_cast<QKeyEvent*>(event)->key() == Qt::Key_Escape) {
891 Q_EMIT keyEscapePressed();
892 }
893 }
894 return QItemDelegate::eventFilter(object, event);
895}
896
897void PolishProgressDialog(QProgressDialog* dialog)
898{
899#ifdef Q_OS_MACOS
900 // Workaround for macOS-only Qt bug; see: QTBUG-65750, QTBUG-70357.
901 const int margin = TextWidth(dialog->fontMetrics(), ("X"));
902 dialog->resize(dialog->width() + 2 * margin, dialog->height());
903#endif
904 // QProgressDialog estimates the time the operation will take (based on time
905 // for steps), and only shows itself if that estimate is beyond minimumDuration.
906 // The default minimumDuration value is 4 seconds, and it could make users
907 // think that the GUI is frozen.
908 dialog->setMinimumDuration(0);
909}
910
911int TextWidth(const QFontMetrics& fm, const QString& text)
912{
913 return fm.horizontalAdvance(text);
914}
915
917{
918#ifdef QT_STATIC
919 const std::string qt_link{"static"};
920#else
921 const std::string qt_link{"dynamic"};
922#endif
923 LogInfo("Qt %s (%s), plugin=%s\n", qVersion(), qt_link, QGuiApplication::platformName().toStdString());
924 const auto static_plugins = QPluginLoader::staticPlugins();
925 if (static_plugins.empty()) {
926 LogInfo("No static plugins.\n");
927 } else {
928 LogInfo("Static plugins:\n");
929 for (const QStaticPlugin& p : static_plugins) {
930 QJsonObject meta_data = p.metaData();
931 const std::string plugin_class = meta_data.take(QString("className")).toString().toStdString();
932 const int plugin_version = meta_data.take(QString("version")).toInt();
933 LogInfo(" %s, version %d\n", plugin_class, plugin_version);
934 }
935 }
936
937 LogInfo("Style: %s / %s\n", QApplication::style()->objectName().toStdString(), QApplication::style()->metaObject()->className());
938 LogInfo("System: %s, %s\n", QSysInfo::prettyProductName().toStdString(), QSysInfo::buildAbi().toStdString());
939 for (const QScreen* s : QGuiApplication::screens()) {
940 LogInfo("Screen: %s %dx%d, pixel ratio=%.1f\n", s->name().toStdString(), s->size().width(), s->size().height(), s->devicePixelRatio());
941 }
942}
943
944void PopupMenu(QMenu* menu, const QPoint& point, QAction* at_action)
945{
946 // The qminimal plugin does not provide window system integration.
947 if (QApplication::platformName() == "minimal") return;
948 menu->popup(point, at_action);
949}
950
951QDateTime StartOfDay(const QDate& date)
952{
953 return date.startOfDay();
954}
955
956bool HasPixmap(const QLabel* label)
957{
958 return !label->pixmap(Qt::ReturnByValue).isNull();
959}
960
961QString MakeHtmlLink(const QString& source, const QString& link)
962{
963 return QString(source).replace(
964 link,
965 QLatin1String("<a href=\"") + link + QLatin1String("\">") + link + QLatin1String("</a>"));
966}
967
969 const std::exception* exception,
970 const QObject* sender,
971 const QObject* receiver)
972{
973 std::string description = sender->metaObject()->className();
974 description += "->";
975 if (receiver) {
976 description += receiver->metaObject()->className();
977 } else {
978 description += "anonymous function";
979 }
980 PrintExceptionContinue(exception, description);
981}
982
983void ShowModalDialogAsynchronously(QDialog* dialog)
984{
985 dialog->setAttribute(Qt::WA_DeleteOnClose);
986 dialog->setWindowModality(Qt::ApplicationModal);
987 dialog->show();
988}
989
990QString WalletDisplayName(const QString& name)
991{
992 return name.isEmpty() ? "[" + QObject::tr("default wallet") + "]" : name;
993}
994
995QString WalletDisplayName(const std::string& name)
996{
997 return WalletDisplayName(QString::fromStdString(name));
998}
999} // namespace GUIUtil
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:143
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
fs::path GetDefaultDataDir()
Definition: args.cpp:859
ArgsManager gArgs
Definition: args.cpp:38
int ret
int flags
Definition: bitcoin-tx.cpp:530
const CChainParams & Params()
Return the currently selected parameters.
std::string ChainTypeToString(ChainType chain)
Definition: chaintype.cpp:12
ChainType
Definition: chaintype.h:12
#define Assume(val)
Assume is the identity function.
Definition: check.h:128
ChainType GetChainType() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Returns the appropriate chain type from the program arguments.
Definition: args.cpp:910
fs::path GetConfigFilePath() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return config file path (read-only)
Definition: args.cpp:897
std::string GetChainTypeString() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Returns the appropriate chain type string from the program arguments.
Definition: args.cpp:917
fs::path m_file_path
Definition: logging.h:177
Bitcoin address widget validator, checks for a valid bitcoin address.
Base58 entry widget validator, checks for valid characters and removes some whitespace.
static QString format(Unit unit, const CAmount &amount, bool plussign=false, SeparatorStyle separators=SeparatorStyle::STANDARD, bool justify=false)
Format as string.
static bool parse(Unit unit, const QString &value, CAmount *val_out)
Parse string to coin amount.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:77
ChainType GetChainType() const
Return the chain type.
Definition: chainparams.h:111
std::atomic< NodeClock::duration > m_min_ping_time
Lowest measured round-trip duration.
Definition: net.h:912
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
An output of a transaction.
Definition: transaction.h:140
void mouseReleaseEvent(QMouseEvent *event) override
Definition: guiutil.cpp:877
ClickableLabel(const PlatformStyle *platform_style, QWidget *parent=nullptr)
Definition: guiutil.cpp:872
void clicked(const QPoint &point)
Emitted when the label is clicked.
void mouseReleaseEvent(QMouseEvent *event) override
Definition: guiutil.cpp:882
void clicked(const QPoint &point)
Emitted when the progressbar is clicked.
bool eventFilter(QObject *object, QEvent *event) override
Definition: guiutil.cpp:887
bool eventFilter(QObject *watched, QEvent *event) override
Definition: guiutil.cpp:494
LabelOutOfFocusEventFilter(QObject *parent)
Definition: guiutil.cpp:489
QString m_image_filename
Definition: guiutil.h:265
const PlatformStyle * m_platform_style
Definition: guiutil.h:264
void changeEvent(QEvent *e) override
Definition: guiutil.cpp:858
ThemedLabel(const PlatformStyle *platform_style, QWidget *parent=nullptr)
Definition: guiutil.cpp:844
void setThemedPixmap(const QString &image_filename, int width, int height)
Definition: guiutil.cpp:850
void updateThemedPixmap()
Definition: guiutil.cpp:867
bool eventFilter(QObject *obj, QEvent *evt) override
Definition: guiutil.cpp:471
ToolTipToRichTextFilter(int size_threshold, QObject *parent=nullptr)
Definition: guiutil.cpp:464
QIcon SingleColorIcon(const QString &filename) const
Colorize an icon (given filename) with the icon color.
Line edit that can be marked as "invalid" to show input validation feedback.
void setCheckValidator(const QValidator *v)
Top-level interface for a bitcoin node (bitcoind process).
Definition: node.h:71
#define MAX_PATH
Definition: compat.h:81
ConnectionType
Different types of connections to a peer.
@ PRIVATE_BROADCAST
Private broadcast connections are short-lived and only opened to privacy networks (Tor,...
@ BLOCK_RELAY
We use block-relay-only connections to help prevent against partition attacks.
@ MANUAL
We open manual connections to addresses that users explicitly requested via the addnode RPC or the -a...
@ OUTBOUND_FULL_RELAY
These are the default connections that we use to connect with the network.
@ FEELER
Feeler connections are short-lived connections made to check that a node is alive.
@ INBOUND
Inbound connections are those initiated by a peer.
@ ADDR_FETCH
AddrFetch connections are short lived connections used to solicit addresses from peers.
void PrintExceptionContinue(const std::exception *pex, std::string_view thread_name)
Definition: exception.cpp:36
static path u8path(std::string_view utf8_str)
Definition: fs.h:82
static bool exists(const path &p)
Definition: fs.h:96
bool IsValidDestinationString(const std::string &str, const CChainParams &params)
Definition: key_io.cpp:311
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg, std::vector< int > *error_locations)
Definition: key_io.cpp:300
#define LogInfo(...)
Definition: log.h:125
BCLog::Logger & LogInstance()
Definition: logging.cpp:26
void ForceActivation()
Force application activation on macOS.
Utility functions used by the Bitcoin Qt UI.
Definition: bitcoingui.h:58
QString NetworkToQString(Network net)
Convert enum Network to QString.
Definition: guiutil.cpp:682
bool isObscured(QWidget *w)
Definition: guiutil.cpp:399
bool openBitcoinConf()
Definition: guiutil.cpp:440
Qt::ConnectionType blockingGUIThreadConnection()
Get connection type to call object slot in GUI thread with invokeMethod.
Definition: guiutil.cpp:380
QString WalletDisplayName(const QString &name)
Definition: guiutil.cpp:990
QString HtmlEscape(const QString &str, bool fMultiLine)
Definition: guiutil.cpp:249
void PopupMenu(QMenu *menu, const QPoint &point, QAction *at_action)
Call QMenu::popup() only on supported QT_QPA_PLATFORM.
Definition: guiutil.cpp:944
QList< QModelIndex > getEntryData(const QAbstractItemView *view, int column)
Return a field of the currently selected entry as a QString.
Definition: guiutil.cpp:277
QFont fixedPitchFont(bool use_embedded_font)
Definition: guiutil.cpp:100
QString formatPingTime(NodeClock::duration ping_time)
Format a CNodeStats.m_last_ping_time/m_min_ping_time/m_ping_wait into a user-readable string if it ex...
Definition: guiutil.cpp:771
QString formatBytes(uint64_t bytes)
Definition: guiutil.cpp:820
void ShowModalDialogAsynchronously(QDialog *dialog)
Shows a QDialog instance asynchronously, and deletes it on close.
Definition: guiutil.cpp:983
void AddButtonShortcut(QAbstractButton *button, const QKeySequence &shortcut)
Connects an additional shortcut to a QAbstractButton.
Definition: guiutil.cpp:144
QString MakeHtmlLink(const QString &source, const QString &link)
Replaces a plain text link with an HTML tagged one.
Definition: guiutil.cpp:961
void handleCloseWindowShortcut(QWidget *w)
Definition: guiutil.cpp:426
QString ExtractFirstSuffixFromFilter(const QString &filter)
Extract first suffix from filter pattern "Description (*.foo)" or "Description (*....
Definition: guiutil.cpp:304
void PolishProgressDialog(QProgressDialog *dialog)
Definition: guiutil.cpp:897
bool isDust(interfaces::Node &node, const QString &address, const CAmount &amount)
Definition: guiutil.cpp:241
QString getOpenFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut)
Get open filename, convenience wrapper for QFileDialog::getOpenFileName.
Definition: guiutil.cpp:355
QString getDefaultDataDirectory()
Determine default data directory for operating system.
Definition: guiutil.cpp:299
QString formatDurationStr(std::chrono::nanoseconds dur)
Convert a duration into a QString with days, hours, mins, secs. This ignores sub-seconds.
Definition: guiutil.cpp:733
void copyEntryData(const QAbstractItemView *view, int column, int role)
Copy a field of the currently selected entry of a view to the clipboard.
Definition: guiutil.cpp:264
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 ...
Definition: guiutil.cpp:315
QDateTime StartOfDay(const QDate &date)
Returns the start-moment of the day in local time.
Definition: guiutil.cpp:951
bool SetStartOnSystemStartup(bool fAutoStart)
Definition: guiutil.cpp:659
static std::string DummyAddress(const CChainParams &params)
Definition: guiutil.cpp:109
void bringToFront(QWidget *w)
Definition: guiutil.cpp:408
bool HasPixmap(const QLabel *label)
Returns true if pixmap has been set.
Definition: guiutil.cpp:956
void LogQtInfo()
Writes to debug.log short info about the used Qt and the host system.
Definition: guiutil.cpp:916
QString PathToQString(const fs::path &path)
Convert OS specific boost path to QString through UTF-8.
Definition: guiutil.cpp:677
void openDebugLogfile()
Definition: guiutil.cpp:431
QString dateTimeStr(const QDateTime &date)
Definition: guiutil.cpp:90
void LoadFont(const QString &file_name)
Loads the font from the file specified by file_name, aborts if it fails.
Definition: guiutil.cpp:291
void PrintSlotException(const std::exception *exception, const QObject *sender, const QObject *receiver)
Definition: guiutil.cpp:968
bool checkPoint(const QPoint &p, const QWidget *w)
Definition: guiutil.cpp:392
QString formatBitcoinURI(const SendCoinsRecipient &info)
Definition: guiutil.cpp:211
QString ConnectionTypeToQString(ConnectionType conn_type, bool prepend_direction)
Convert enum ConnectionType to QString.
Definition: guiutil.cpp:702
QString formatServicesStr(quint64 mask)
Format CNodeStats.nServices bitmask into a user-readable string.
Definition: guiutil.cpp:757
QString formatNiceTimeOffset(qint64 secs)
Definition: guiutil.cpp:783
QString formatTimeOffset(int64_t time_offset)
Format a CNodeStateStats.time_offset into a user-readable string.
Definition: guiutil.cpp:778
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
Definition: guiutil.cpp:149
QString FormatPeerAge(NodeClock::time_point connected)
Convert peer connection time to a QString denominated in the most relevant unit.
Definition: guiutil.cpp:748
bool GetStartOnSystemStartup()
Definition: guiutil.cpp:658
int TextWidth(const QFontMetrics &fm, const QString &text)
Returns the distance in pixels appropriate for drawing a subsequent character after text.
Definition: guiutil.cpp:911
void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent)
Definition: guiutil.cpp:131
void setClipboard(const QString &str)
Definition: guiutil.cpp:663
bool hasEntryData(const QAbstractItemView *view, int column, int role)
Returns true if the specified field of the currently selected view entry is not empty.
Definition: guiutil.cpp:284
fs::path QStringToPath(const QString &path)
Convert QString to OS specific boost path through UTF-8.
Definition: guiutil.cpp:672
qreal calculateIdealFontSize(int width, const QString &text, QFont font, qreal minPointSize, qreal font_size)
Definition: guiutil.cpp:832
Definition: messages.h:22
Network
A network type.
Definition: netaddress.h:33
@ NET_I2P
I2P.
Definition: netaddress.h:47
@ NET_CJDNS
CJDNS.
Definition: netaddress.h:50
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
Definition: netaddress.h:57
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:44
@ NET_IPV6
IPv6.
Definition: netaddress.h:41
@ NET_IPV4
IPv4.
Definition: netaddress.h:38
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:35
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
Definition: netaddress.h:54
@ SUCCEEDED
RFC1928: Succeeded.
Definition: netbase.cpp:267
bool IsDust(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:66
std::vector< std::string > serviceFlagsToStr(uint64_t flags)
Convert service flags (a bitmask of NODE_*) to human readable strings.
Definition: protocol.cpp:108
const char * prefix
Definition: rest.cpp:1180
const char * name
Definition: rest.cpp:56
const char * source
Definition: rpcconsole.cpp:63
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition: time.cpp:38
std::chrono::time_point< NodeClock > time_point
Definition: time.h:28
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
assert(!tx.IsCoinBase())