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