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