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