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