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