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