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 #if defined(HAVE_CONFIG_H)
7 #endif
8 
9 #include <qt/guiutil.h>
10 
12 #include <qt/bitcoinunits.h>
13 #include <qt/platformstyle.h>
14 #include <qt/qvalidatedlineedit.h>
15 #include <qt/sendcoinsrecipient.h>
16 
17 #include <addresstype.h>
18 #include <base58.h>
19 #include <chainparams.h>
20 #include <common/args.h>
21 #include <interfaces/node.h>
22 #include <key_io.h>
23 #include <logging.h>
24 #include <policy/policy.h>
25 #include <primitives/transaction.h>
26 #include <protocol.h>
27 #include <script/script.h>
28 #include <util/chaintype.h>
29 #include <util/exception.h>
30 #include <util/fs.h>
31 #include <util/fs_helpers.h>
32 #include <util/time.h>
33 
34 #ifdef WIN32
35 #include <shellapi.h>
36 #include <shlobj.h>
37 #include <shlwapi.h>
38 #endif
39 
40 #include <QAbstractButton>
41 #include <QAbstractItemView>
42 #include <QApplication>
43 #include <QClipboard>
44 #include <QDateTime>
45 #include <QDesktopServices>
46 #include <QDialog>
47 #include <QDoubleValidator>
48 #include <QFileDialog>
49 #include <QFont>
50 #include <QFontDatabase>
51 #include <QFontMetrics>
52 #include <QGuiApplication>
53 #include <QJsonObject>
54 #include <QKeyEvent>
55 #include <QKeySequence>
56 #include <QLatin1String>
57 #include <QLineEdit>
58 #include <QList>
59 #include <QLocale>
60 #include <QMenu>
61 #include <QMouseEvent>
62 #include <QPluginLoader>
63 #include <QProgressDialog>
64 #include <QRegularExpression>
65 #include <QScreen>
66 #include <QSettings>
67 #include <QShortcut>
68 #include <QSize>
69 #include <QStandardPaths>
70 #include <QString>
71 #include <QTextDocument> // for Qt::mightBeRichText
72 #include <QThread>
73 #include <QUrlQuery>
74 #include <QtGlobal>
75 
76 #include <cassert>
77 #include <chrono>
78 #include <exception>
79 #include <fstream>
80 #include <string>
81 #include <vector>
82 
83 #if defined(Q_OS_MACOS)
84 
85 #include <QProcess>
86 
87 void ForceActivation();
88 #endif
89 
90 using namespace std::chrono_literals;
91 
92 namespace GUIUtil {
93 
94 QString dateTimeStr(const QDateTime &date)
95 {
96  return QLocale::system().toString(date.date(), QLocale::ShortFormat) + QString(" ") + date.toString("hh:mm");
97 }
98 
99 QString dateTimeStr(qint64 nTime)
100 {
101  return dateTimeStr(QDateTime::fromSecsSinceEpoch(nTime));
102 }
103 
104 QFont fixedPitchFont(bool use_embedded_font)
105 {
106  if (use_embedded_font) {
107  return {"Roboto Mono"};
108  }
109  return QFontDatabase::systemFont(QFontDatabase::FixedFont);
110 }
111 
112 // Return a pre-generated dummy bech32m address (P2TR) with invalid checksum.
113 static std::string DummyAddress(const CChainParams &params)
114 {
115  std::string addr;
116  switch (params.GetChainType()) {
117  case ChainType::MAIN:
118  addr = "bc1p35yvjel7srp783ztf8v6jdra7dhfzk5jaun8xz2qp6ws7z80n4tq2jku9f";
119  break;
120  case ChainType::SIGNET:
121  case ChainType::TESTNET:
122  addr = "tb1p35yvjel7srp783ztf8v6jdra7dhfzk5jaun8xz2qp6ws7z80n4tqa6qnlg";
123  break;
124  case ChainType::REGTEST:
125  addr = "bcrt1p35yvjel7srp783ztf8v6jdra7dhfzk5jaun8xz2qp6ws7z80n4tqsr2427";
126  break;
127  } // no default case, so the compiler can warn about missing cases
128  assert(!addr.empty());
129 
130  if (Assume(!IsValidDestinationString(addr))) return addr;
131  return {};
132 }
133 
134 void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent)
135 {
136  parent->setFocusProxy(widget);
137 
138  widget->setFont(fixedPitchFont());
139  // We don't want translators to use own addresses in translations
140  // and this is the only place, where this address is supplied.
141  widget->setPlaceholderText(QObject::tr("Enter a Bitcoin address (e.g. %1)").arg(
142  QString::fromStdString(DummyAddress(Params()))));
143  widget->setValidator(new BitcoinAddressEntryValidator(parent));
144  widget->setCheckValidator(new BitcoinAddressCheckValidator(parent));
145 }
146 
147 void AddButtonShortcut(QAbstractButton* button, const QKeySequence& shortcut)
148 {
149  QObject::connect(new QShortcut(shortcut, button), &QShortcut::activated, [button]() { button->animateClick(); });
150 }
151 
152 bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
153 {
154  // return if URI is not valid or is no bitcoin: URI
155  if(!uri.isValid() || uri.scheme() != QString("bitcoin"))
156  return false;
157 
159  rv.address = uri.path();
160  // Trim any following forward slash which may have been added by the OS
161  if (rv.address.endsWith("/")) {
162  rv.address.truncate(rv.address.length() - 1);
163  }
164  rv.amount = 0;
165 
166  QUrlQuery uriQuery(uri);
167  QList<QPair<QString, QString> > items = uriQuery.queryItems();
168  for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
169  {
170  bool fShouldReturnFalse = false;
171  if (i->first.startsWith("req-"))
172  {
173  i->first.remove(0, 4);
174  fShouldReturnFalse = true;
175  }
176 
177  if (i->first == "label")
178  {
179  rv.label = i->second;
180  fShouldReturnFalse = false;
181  }
182  if (i->first == "message")
183  {
184  rv.message = i->second;
185  fShouldReturnFalse = false;
186  }
187  else if (i->first == "amount")
188  {
189  if(!i->second.isEmpty())
190  {
191  if (!BitcoinUnits::parse(BitcoinUnit::BTC, i->second, &rv.amount)) {
192  return false;
193  }
194  }
195  fShouldReturnFalse = false;
196  }
197 
198  if (fShouldReturnFalse)
199  return false;
200  }
201  if(out)
202  {
203  *out = rv;
204  }
205  return true;
206 }
207 
209 {
210  QUrl uriInstance(uri);
211  return parseBitcoinURI(uriInstance, out);
212 }
213 
215 {
216  bool bech_32 = info.address.startsWith(QString::fromStdString(Params().Bech32HRP() + "1"));
217 
218  QString ret = QString("bitcoin:%1").arg(bech_32 ? info.address.toUpper() : info.address);
219  int paramCount = 0;
220 
221  if (info.amount)
222  {
223  ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnit::BTC, info.amount, false, BitcoinUnits::SeparatorStyle::NEVER));
224  paramCount++;
225  }
226 
227  if (!info.label.isEmpty())
228  {
229  QString lbl(QUrl::toPercentEncoding(info.label));
230  ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl);
231  paramCount++;
232  }
233 
234  if (!info.message.isEmpty())
235  {
236  QString msg(QUrl::toPercentEncoding(info.message));
237  ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg);
238  paramCount++;
239  }
240 
241  return ret;
242 }
243 
244 bool isDust(interfaces::Node& node, const QString& address, const CAmount& amount)
245 {
246  CTxDestination dest = DecodeDestination(address.toStdString());
247  CScript script = GetScriptForDestination(dest);
248  CTxOut txOut(amount, script);
249  return IsDust(txOut, node.getDustRelayFee());
250 }
251 
252 QString HtmlEscape(const QString& str, bool fMultiLine)
253 {
254  QString escaped = str.toHtmlEscaped();
255  if(fMultiLine)
256  {
257  escaped = escaped.replace("\n", "<br>\n");
258  }
259  return escaped;
260 }
261 
262 QString HtmlEscape(const std::string& str, bool fMultiLine)
263 {
264  return HtmlEscape(QString::fromStdString(str), fMultiLine);
265 }
266 
267 void copyEntryData(const QAbstractItemView *view, int column, int role)
268 {
269  if(!view || !view->selectionModel())
270  return;
271  QModelIndexList selection = view->selectionModel()->selectedRows(column);
272 
273  if(!selection.isEmpty())
274  {
275  // Copy first item
276  setClipboard(selection.at(0).data(role).toString());
277  }
278 }
279 
280 QList<QModelIndex> getEntryData(const QAbstractItemView *view, int column)
281 {
282  if(!view || !view->selectionModel())
283  return QList<QModelIndex>();
284  return view->selectionModel()->selectedRows(column);
285 }
286 
287 bool hasEntryData(const QAbstractItemView *view, int column, int role)
288 {
289  QModelIndexList selection = getEntryData(view, column);
290  if (selection.isEmpty()) return false;
291  return !selection.at(0).data(role).toString().isEmpty();
292 }
293 
294 void LoadFont(const QString& file_name)
295 {
296  const int id = QFontDatabase::addApplicationFont(file_name);
297  assert(id != -1);
298 }
299 
301 {
303 }
304 
305 QString ExtractFirstSuffixFromFilter(const QString& filter)
306 {
307  QRegularExpression filter_re(QStringLiteral(".* \\(\\*\\.(.*)[ \\)]"), QRegularExpression::InvertedGreedinessOption);
308  QString suffix;
309  QRegularExpressionMatch m = filter_re.match(filter);
310  if (m.hasMatch()) {
311  suffix = m.captured(1);
312  }
313  return suffix;
314 }
315 
316 QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir,
317  const QString &filter,
318  QString *selectedSuffixOut)
319 {
320  QString selectedFilter;
321  QString myDir;
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 
333  QString selectedSuffix = ExtractFirstSuffixFromFilter(selectedFilter);
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 */
349  if(selectedSuffixOut)
350  {
351  *selectedSuffixOut = selectedSuffix;
352  }
353  return result;
354 }
355 
356 QString getOpenFileName(QWidget *parent, const QString &caption, const QString &dir,
357  const QString &filter,
358  QString *selectedSuffixOut)
359 {
360  QString selectedFilter;
361  QString myDir;
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 
373  if(selectedSuffixOut)
374  {
375  *selectedSuffixOut = ExtractFirstSuffixFromFilter(selectedFilter);
376  ;
377  }
378  return result;
379 }
380 
382 {
383  if(QThread::currentThread() != qApp->thread())
384  {
385  return Qt::BlockingQueuedConnection;
386  }
387  else
388  {
389  return Qt::DirectConnection;
390  }
391 }
392 
393 bool 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 
400 bool 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 
409 void bringToFront(QWidget* w)
410 {
411 #ifdef Q_OS_MACOS
412  ForceActivation();
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 = gArgs.GetDataDirNet() / "debug.log";
435 
436  /* Open debug.log with the associated application */
437  if (fs::exists(pathDebug))
438  QDesktopServices::openUrl(QUrl::fromLocalFile(PathToQString(pathDebug)));
439 }
440 
442 {
443  fs::path pathConfig = gArgs.GetConfigFilePath();
444 
445  /* Create the file */
446  std::ofstream configFile{pathConfig, 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 
465 ToolTipToRichTextFilter::ToolTipToRichTextFilter(int _size_threshold, QObject *parent) :
466  QObject(parent),
467  size_threshold(_size_threshold)
468 {
469 
470 }
471 
472 bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
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 
495 bool LabelOutOfFocusEventFilter::eventFilter(QObject* watched, QEvent* event)
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
513 fs::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
526  return fs::exists(StartupShortcutPath());
527 }
528 
529 bool SetStartOnSystemStartup(bool fAutoStart)
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;
540  HRESULT hres = CoCreateInstance(CLSID_ShellLink, nullptr,
541  CLSCTX_INPROC_SERVER, IID_IShellLinkW,
542  reinterpret_cast<void**>(&psl));
543 
544  if (SUCCEEDED(hres))
545  {
546  // Get the current executable path
547  WCHAR pszExePath[MAX_PATH];
548  GetModuleFileNameW(nullptr, pszExePath, ARRAYSIZE(pszExePath));
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);
557  PathRemoveFileSpecW(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.
569  hres = ppf->Save(StartupShortcutPath().wstring().c_str(), TRUE);
570  ppf->Release();
571  psl->Release();
572  CoUninitialize();
573  return true;
574  }
575  psl->Release();
576  }
577  CoUninitialize();
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 
587 fs::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 
596 fs::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()};
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 
623 bool SetStartOnSystemStartup(bool fAutoStart)
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::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 
659 bool GetStartOnSystemStartup() { return false; }
660 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
661 
662 #endif
663 
664 void 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 
673 fs::path QStringToPath(const QString &path)
674 {
675  return fs::u8path(path.toStdString());
676 }
677 
678 QString 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 
703 QString ConnectionTypeToQString(ConnectionType conn_type, bool prepend_direction)
704 {
705  QString prefix;
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  } // no default case, so the compiler can warn about missing cases
729  assert(false);
730 }
731 
732 QString formatDurationStr(std::chrono::seconds dur)
733 {
734  const auto d{std::chrono::duration_cast<std::chrono::days>(dur)};
735  const auto h{std::chrono::duration_cast<std::chrono::hours>(dur - d)};
736  const auto m{std::chrono::duration_cast<std::chrono::minutes>(dur - d - h)};
737  const auto s{std::chrono::duration_cast<std::chrono::seconds>(dur - d - h - m)};
738  QStringList str_list;
739  if (auto d2{d.count()}) str_list.append(QObject::tr("%1 d").arg(d2));
740  if (auto h2{h.count()}) str_list.append(QObject::tr("%1 h").arg(h2));
741  if (auto m2{m.count()}) str_list.append(QObject::tr("%1 m").arg(m2));
742  const auto s2{s.count()};
743  if (s2 || str_list.empty()) str_list.append(QObject::tr("%1 s").arg(s2));
744  return str_list.join(" ");
745 }
746 
747 QString FormatPeerAge(std::chrono::seconds time_connected)
748 {
749  const auto time_now{GetTime<std::chrono::seconds>()};
750  const auto age{time_now - time_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 
757 QString 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 
771 QString formatPingTime(std::chrono::microseconds ping_time)
772 {
773  return (ping_time == std::chrono::microseconds::max() || ping_time == 0us) ?
774  QObject::tr("N/A") :
775  QObject::tr("%1 ms").arg(QString::number((int)(count_microseconds(ping_time) / 1000), 10));
776 }
777 
778 QString formatTimeOffset(int64_t nTimeOffset)
779 {
780  return QObject::tr("%1 s").arg(QString::number((int)nTimeOffset, 10));
781 }
782 
783 QString 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 
820 QString 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 
832 qreal 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 
844 ThemedLabel::ThemedLabel(const PlatformStyle* platform_style, QWidget* parent)
845  : QLabel{parent}, m_platform_style{platform_style}
846 {
848 }
849 
850 void 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 
872 ClickableLabel::ClickableLabel(const PlatformStyle* platform_style, QWidget* parent)
873  : ThemedLabel{platform_style, parent}
874 {
875 }
876 
877 void ClickableLabel::mouseReleaseEvent(QMouseEvent *event)
878 {
879  Q_EMIT clicked(event->pos());
880 }
881 
883 {
884  Q_EMIT clicked(event->pos());
885 }
886 
887 bool 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 
897 void 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 
911 int TextWidth(const QFontMetrics& fm, const QString& text)
912 {
913  return fm.horizontalAdvance(text);
914 }
915 
916 void LogQtInfo()
917 {
918 #ifdef QT_STATIC
919  const std::string qt_link{"static"};
920 #else
921  const std::string qt_link{"dynamic"};
922 #endif
923 #ifdef QT_STATICPLUGIN
924  const std::string plugin_link{"static"};
925 #else
926  const std::string plugin_link{"dynamic"};
927 #endif
928  LogPrintf("Qt %s (%s), plugin=%s (%s)\n", qVersion(), qt_link, QGuiApplication::platformName().toStdString(), plugin_link);
929  const auto static_plugins = QPluginLoader::staticPlugins();
930  if (static_plugins.empty()) {
931  LogPrintf("No static plugins.\n");
932  } else {
933  LogPrintf("Static plugins:\n");
934  for (const QStaticPlugin& p : static_plugins) {
935  QJsonObject meta_data = p.metaData();
936  const std::string plugin_class = meta_data.take(QString("className")).toString().toStdString();
937  const int plugin_version = meta_data.take(QString("version")).toInt();
938  LogPrintf(" %s, version %d\n", plugin_class, plugin_version);
939  }
940  }
941 
942  LogPrintf("Style: %s / %s\n", QApplication::style()->objectName().toStdString(), QApplication::style()->metaObject()->className());
943  LogPrintf("System: %s, %s\n", QSysInfo::prettyProductName().toStdString(), QSysInfo::buildAbi().toStdString());
944  for (const QScreen* s : QGuiApplication::screens()) {
945  LogPrintf("Screen: %s %dx%d, pixel ratio=%.1f\n", s->name().toStdString(), s->size().width(), s->size().height(), s->devicePixelRatio());
946  }
947 }
948 
949 void PopupMenu(QMenu* menu, const QPoint& point, QAction* at_action)
950 {
951  // The qminimal plugin does not provide window system integration.
952  if (QApplication::platformName() == "minimal") return;
953  menu->popup(point, at_action);
954 }
955 
956 QDateTime StartOfDay(const QDate& date)
957 {
958 #if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
959  return date.startOfDay();
960 #else
961  return QDateTime(date);
962 #endif
963 }
964 
965 bool HasPixmap(const QLabel* label)
966 {
967 #if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
968  return !label->pixmap(Qt::ReturnByValue).isNull();
969 #else
970  return label->pixmap() != nullptr;
971 #endif
972 }
973 
974 QImage GetImage(const QLabel* label)
975 {
976  if (!HasPixmap(label)) {
977  return QImage();
978  }
979 
980 #if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
981  return label->pixmap(Qt::ReturnByValue).toImage();
982 #else
983  return label->pixmap()->toImage();
984 #endif
985 }
986 
987 QString MakeHtmlLink(const QString& source, const QString& link)
988 {
989  return QString(source).replace(
990  link,
991  QLatin1String("<a href=\"") + link + QLatin1String("\">") + link + QLatin1String("</a>"));
992 }
993 
995  const std::exception* exception,
996  const QObject* sender,
997  const QObject* receiver)
998 {
999  std::string description = sender->metaObject()->className();
1000  description += "->";
1001  description += receiver->metaObject()->className();
1002  PrintExceptionContinue(exception, description);
1003 }
1004 
1005 void ShowModalDialogAsynchronously(QDialog* dialog)
1006 {
1007  dialog->setAttribute(Qt::WA_DeleteOnClose);
1008  dialog->setWindowModality(Qt::ApplicationModal);
1009  dialog->show();
1010 }
1011 
1012 } // 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:530
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:741
std::string GetChainTypeString() const
Returns the appropriate chain type string from the program arguments.
Definition: args.cpp:748
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:728
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:114
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: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: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: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:472
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:244
void ForceActivation()
Force application activation on macOS.
Utility functions used by the Bitcoin Qt UI.
Definition: bitcoingui.h:60
QString NetworkToQString(Network net)
Convert enum Network to QString.
Definition: guiutil.cpp:683
bool isObscured(QWidget *w)
Definition: guiutil.cpp:400
QImage GetImage(const QLabel *label)
Definition: guiutil.cpp:974
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 HtmlEscape(const QString &str, bool fMultiLine)
Definition: guiutil.cpp:252
void PopupMenu(QMenu *menu, const QPoint &point, QAction *at_action)
Call QMenu::popup() only on supported QT_QPA_PLATFORM.
Definition: guiutil.cpp:949
QList< QModelIndex > getEntryData(const QAbstractItemView *view, int column)
Return a field of the currently selected entry as a QString.
Definition: guiutil.cpp:280
QFont fixedPitchFont(bool use_embedded_font)
Definition: guiutil.cpp:104
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:1005
QString formatDurationStr(std::chrono::seconds dur)
Convert seconds into a QString with days, hours, mins, secs.
Definition: guiutil.cpp:732
void AddButtonShortcut(QAbstractButton *button, const QKeySequence &shortcut)
Connects an additional shortcut to a QAbstractButton.
Definition: guiutil.cpp:147
QString MakeHtmlLink(const QString &source, const QString &link)
Replaces a plain text link with an HTML tagged one.
Definition: guiutil.cpp:987
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:897
bool isDust(interfaces::Node &node, const QString &address, const CAmount &amount)
Definition: guiutil.cpp:244
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
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:267
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:956
bool SetStartOnSystemStartup(bool fAutoStart)
Definition: guiutil.cpp:660
static std::string DummyAddress(const CChainParams &params)
Definition: guiutil.cpp:113
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
Definition: guiutil.cpp:208
void bringToFront(QWidget *w)
Definition: guiutil.cpp:409
bool HasPixmap(const QLabel *label)
Returns true if pixmap has been set.
Definition: guiutil.cpp:965
void LogQtInfo()
Writes to debug.log short info about the used Qt and the host system.
Definition: guiutil.cpp:916
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:771
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
void LoadFont(const QString &file_name)
Loads the font from the file specified by file_name, aborts if it fails.
Definition: guiutil.cpp:294
void PrintSlotException(const std::exception *exception, const QObject *sender, const QObject *receiver)
Definition: guiutil.cpp:994
bool checkPoint(const QPoint &p, const QWidget *w)
Definition: guiutil.cpp:393
QString formatBitcoinURI(const SendCoinsRecipient &info)
Definition: guiutil.cpp:214
QString formatTimeOffset(int64_t nTimeOffset)
Format a CNodeCombinedStats.nTimeOffset into a user-readable string.
Definition: guiutil.cpp:778
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:757
QString formatNiceTimeOffset(qint64 secs)
Definition: guiutil.cpp:783
QString FormatPeerAge(std::chrono::seconds time_connected)
Convert peer connection time to a QString denominated in the most relevant unit.
Definition: guiutil.cpp:747
QString dateTimeStr(qint64 nTime)
Definition: guiutil.cpp:99
QString HtmlEscape(const std::string &str, bool fMultiLine)
Definition: guiutil.cpp:262
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:911
void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent)
Definition: guiutil.cpp:134
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:287
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:832
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: init.h:25
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:260
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:194
const char * prefix
Definition: rest.cpp:1007
const char * source
Definition: rpcconsole.cpp:59
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:1162
assert(!tx.IsCoinBase())