Bitcoin Core  0.19.99
P2P Digital Currency
guiutil.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-2019 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 #ifdef _WIN32_IE
25 #undef _WIN32_IE
26 #endif
27 #define _WIN32_IE 0x0501
28 #define WIN32_LEAN_AND_MEAN 1
29 #ifndef NOMINMAX
30 #define NOMINMAX
31 #endif
32 #include <shellapi.h>
33 #include <shlobj.h>
34 #include <shlwapi.h>
35 #endif
36 
37 #include <QAbstractItemView>
38 #include <QApplication>
39 #include <QClipboard>
40 #include <QDateTime>
41 #include <QDesktopServices>
42 #include <QDoubleValidator>
43 #include <QFileDialog>
44 #include <QFont>
45 #include <QFontDatabase>
46 #include <QFontMetrics>
47 #include <QGuiApplication>
48 #include <QKeyEvent>
49 #include <QLineEdit>
50 #include <QList>
51 #include <QMouseEvent>
52 #include <QProgressDialog>
53 #include <QScreen>
54 #include <QSettings>
55 #include <QSize>
56 #include <QString>
57 #include <QTextDocument> // for Qt::mightBeRichText
58 #include <QThread>
59 #include <QUrlQuery>
60 #include <QtGlobal>
61 
62 #if defined(Q_OS_MAC)
63 
64 #include <QProcess>
65 
66 void ForceActivation();
67 #endif
68 
69 namespace GUIUtil {
70 
71 QString dateTimeStr(const QDateTime &date)
72 {
73  return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
74 }
75 
76 QString dateTimeStr(qint64 nTime)
77 {
78  return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
79 }
80 
82 {
83  return QFontDatabase::systemFont(QFontDatabase::FixedFont);
84 }
85 
86 // Just some dummy data to generate a convincing random-looking (but consistent) address
87 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};
88 
89 // Generate a dummy address with invalid CRC, starting with the network prefix.
90 static std::string DummyAddress(const CChainParams &params)
91 {
92  std::vector<unsigned char> sourcedata = params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);
93  sourcedata.insert(sourcedata.end(), dummydata, dummydata + sizeof(dummydata));
94  for(int i=0; i<256; ++i) { // Try every trailing byte
95  std::string s = EncodeBase58(sourcedata.data(), sourcedata.data() + sourcedata.size());
96  if (!IsValidDestinationString(s)) {
97  return s;
98  }
99  sourcedata[sourcedata.size()-1] += 1;
100  }
101  return "";
102 }
103 
104 void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent)
105 {
106  parent->setFocusProxy(widget);
107 
108  widget->setFont(fixedPitchFont());
109  // We don't want translators to use own addresses in translations
110  // and this is the only place, where this address is supplied.
111  widget->setPlaceholderText(QObject::tr("Enter a Bitcoin address (e.g. %1)").arg(
112  QString::fromStdString(DummyAddress(Params()))));
113  widget->setValidator(new BitcoinAddressEntryValidator(parent));
114  widget->setCheckValidator(new BitcoinAddressCheckValidator(parent));
115 }
116 
117 bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
118 {
119  // return if URI is not valid or is no bitcoin: URI
120  if(!uri.isValid() || uri.scheme() != QString("bitcoin"))
121  return false;
122 
124  rv.address = uri.path();
125  // Trim any following forward slash which may have been added by the OS
126  if (rv.address.endsWith("/")) {
127  rv.address.truncate(rv.address.length() - 1);
128  }
129  rv.amount = 0;
130 
131  QUrlQuery uriQuery(uri);
132  QList<QPair<QString, QString> > items = uriQuery.queryItems();
133  for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
134  {
135  bool fShouldReturnFalse = false;
136  if (i->first.startsWith("req-"))
137  {
138  i->first.remove(0, 4);
139  fShouldReturnFalse = true;
140  }
141 
142  if (i->first == "label")
143  {
144  rv.label = i->second;
145  fShouldReturnFalse = false;
146  }
147  if (i->first == "message")
148  {
149  rv.message = i->second;
150  fShouldReturnFalse = false;
151  }
152  else if (i->first == "amount")
153  {
154  if(!i->second.isEmpty())
155  {
156  if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
157  {
158  return false;
159  }
160  }
161  fShouldReturnFalse = false;
162  }
163 
164  if (fShouldReturnFalse)
165  return false;
166  }
167  if(out)
168  {
169  *out = rv;
170  }
171  return true;
172 }
173 
174 bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
175 {
176  QUrl uriInstance(uri);
177  return parseBitcoinURI(uriInstance, out);
178 }
179 
181 {
182  bool bech_32 = info.address.startsWith(QString::fromStdString(Params().Bech32HRP() + "1"));
183 
184  QString ret = QString("bitcoin:%1").arg(bech_32 ? info.address.toUpper() : info.address);
185  int paramCount = 0;
186 
187  if (info.amount)
188  {
189  ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, info.amount, false, BitcoinUnits::separatorNever));
190  paramCount++;
191  }
192 
193  if (!info.label.isEmpty())
194  {
195  QString lbl(QUrl::toPercentEncoding(info.label));
196  ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl);
197  paramCount++;
198  }
199 
200  if (!info.message.isEmpty())
201  {
202  QString msg(QUrl::toPercentEncoding(info.message));
203  ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg);
204  paramCount++;
205  }
206 
207  return ret;
208 }
209 
210 bool isDust(interfaces::Node& node, const QString& address, const CAmount& amount)
211 {
212  CTxDestination dest = DecodeDestination(address.toStdString());
213  CScript script = GetScriptForDestination(dest);
214  CTxOut txOut(amount, script);
215  return IsDust(txOut, node.getDustRelayFee());
216 }
217 
218 QString HtmlEscape(const QString& str, bool fMultiLine)
219 {
220  QString escaped = str.toHtmlEscaped();
221  if(fMultiLine)
222  {
223  escaped = escaped.replace("\n", "<br>\n");
224  }
225  return escaped;
226 }
227 
228 QString HtmlEscape(const std::string& str, bool fMultiLine)
229 {
230  return HtmlEscape(QString::fromStdString(str), fMultiLine);
231 }
232 
233 void copyEntryData(QAbstractItemView *view, int column, int role)
234 {
235  if(!view || !view->selectionModel())
236  return;
237  QModelIndexList selection = view->selectionModel()->selectedRows(column);
238 
239  if(!selection.isEmpty())
240  {
241  // Copy first item
242  setClipboard(selection.at(0).data(role).toString());
243  }
244 }
245 
246 QList<QModelIndex> getEntryData(QAbstractItemView *view, int column)
247 {
248  if(!view || !view->selectionModel())
249  return QList<QModelIndex>();
250  return view->selectionModel()->selectedRows(column);
251 }
252 
254 {
256 }
257 
258 QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir,
259  const QString &filter,
260  QString *selectedSuffixOut)
261 {
262  QString selectedFilter;
263  QString myDir;
264  if(dir.isEmpty()) // Default to user documents location
265  {
266  myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
267  }
268  else
269  {
270  myDir = dir;
271  }
272  /* Directly convert path to native OS path separators */
273  QString result = QDir::toNativeSeparators(QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter));
274 
275  /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
276  QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
277  QString selectedSuffix;
278  if(filter_re.exactMatch(selectedFilter))
279  {
280  selectedSuffix = filter_re.cap(1);
281  }
282 
283  /* Add suffix if needed */
284  QFileInfo info(result);
285  if(!result.isEmpty())
286  {
287  if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
288  {
289  /* No suffix specified, add selected suffix */
290  if(!result.endsWith("."))
291  result.append(".");
292  result.append(selectedSuffix);
293  }
294  }
295 
296  /* Return selected suffix if asked to */
297  if(selectedSuffixOut)
298  {
299  *selectedSuffixOut = selectedSuffix;
300  }
301  return result;
302 }
303 
304 QString getOpenFileName(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::getOpenFileName(parent, caption, myDir, filter, &selectedFilter));
320 
321  if(selectedSuffixOut)
322  {
323  /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
324  QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
325  QString selectedSuffix;
326  if(filter_re.exactMatch(selectedFilter))
327  {
328  selectedSuffix = filter_re.cap(1);
329  }
330  *selectedSuffixOut = selectedSuffix;
331  }
332  return result;
333 }
334 
335 Qt::ConnectionType blockingGUIThreadConnection()
336 {
337  if(QThread::currentThread() != qApp->thread())
338  {
339  return Qt::BlockingQueuedConnection;
340  }
341  else
342  {
343  return Qt::DirectConnection;
344  }
345 }
346 
347 bool checkPoint(const QPoint &p, const QWidget *w)
348 {
349  QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p));
350  if (!atW) return false;
351  return atW->window() == w;
352 }
353 
354 bool isObscured(QWidget *w)
355 {
356  return !(checkPoint(QPoint(0, 0), w)
357  && checkPoint(QPoint(w->width() - 1, 0), w)
358  && checkPoint(QPoint(0, w->height() - 1), w)
359  && checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
360  && checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
361 }
362 
363 void bringToFront(QWidget* w)
364 {
365 #ifdef Q_OS_MAC
366  ForceActivation();
367 #endif
368 
369  if (w) {
370  // activateWindow() (sometimes) helps with keyboard focus on Windows
371  if (w->isMinimized()) {
372  w->showNormal();
373  } else {
374  w->show();
375  }
376  w->activateWindow();
377  w->raise();
378  }
379 }
380 
382 {
383  fs::path pathDebug = GetDataDir() / "debug.log";
384 
385  /* Open debug.log with the associated application */
386  if (fs::exists(pathDebug))
387  QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathDebug)));
388 }
389 
391 {
392  fs::path pathConfig = GetConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME));
393 
394  /* Create the file */
395  fsbridge::ofstream configFile(pathConfig, std::ios_base::app);
396 
397  if (!configFile.good())
398  return false;
399 
400  configFile.close();
401 
402  /* Open bitcoin.conf with the associated application */
403  bool res = QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathConfig)));
404 #ifdef Q_OS_MAC
405  // Workaround for macOS-specific behavior; see #15409.
406  if (!res) {
407  res = QProcess::startDetached("/usr/bin/open", QStringList{"-t", boostPathToQString(pathConfig)});
408  }
409 #endif
410 
411  return res;
412 }
413 
414 ToolTipToRichTextFilter::ToolTipToRichTextFilter(int _size_threshold, QObject *parent) :
415  QObject(parent),
416  size_threshold(_size_threshold)
417 {
418 
419 }
420 
421 bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
422 {
423  if(evt->type() == QEvent::ToolTipChange)
424  {
425  QWidget *widget = static_cast<QWidget*>(obj);
426  QString tooltip = widget->toolTip();
427  if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt") && !Qt::mightBeRichText(tooltip))
428  {
429  // Envelop with <qt></qt> to make sure Qt detects this as rich text
430  // Escape the current message as HTML and replace \n by <br>
431  tooltip = "<qt>" + HtmlEscape(tooltip, true) + "</qt>";
432  widget->setToolTip(tooltip);
433  return true;
434  }
435  }
436  return QObject::eventFilter(obj, evt);
437 }
438 
440 {
441  connect(tableView->horizontalHeader(), &QHeaderView::sectionResized, this, &TableViewLastColumnResizingFixer::on_sectionResized);
442  connect(tableView->horizontalHeader(), &QHeaderView::geometriesChanged, this, &TableViewLastColumnResizingFixer::on_geometriesChanged);
443 }
444 
445 // We need to disconnect these while handling the resize events, otherwise we can enter infinite loops.
447 {
448  disconnect(tableView->horizontalHeader(), &QHeaderView::sectionResized, this, &TableViewLastColumnResizingFixer::on_sectionResized);
449  disconnect(tableView->horizontalHeader(), &QHeaderView::geometriesChanged, this, &TableViewLastColumnResizingFixer::on_geometriesChanged);
450 }
451 
452 // Setup the resize mode, handles compatibility for Qt5 and below as the method signatures changed.
453 // Refactored here for readability.
454 void TableViewLastColumnResizingFixer::setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode)
455 {
456  tableView->horizontalHeader()->setSectionResizeMode(logicalIndex, resizeMode);
457 }
458 
459 void TableViewLastColumnResizingFixer::resizeColumn(int nColumnIndex, int width)
460 {
461  tableView->setColumnWidth(nColumnIndex, width);
462  tableView->horizontalHeader()->resizeSection(nColumnIndex, width);
463 }
464 
466 {
467  int nColumnsWidthSum = 0;
468  for (int i = 0; i < columnCount; i++)
469  {
470  nColumnsWidthSum += tableView->horizontalHeader()->sectionSize(i);
471  }
472  return nColumnsWidthSum;
473 }
474 
476 {
477  int nResult = lastColumnMinimumWidth;
478  int nTableWidth = tableView->horizontalHeader()->width();
479 
480  if (nTableWidth > 0)
481  {
482  int nOtherColsWidth = getColumnsWidth() - tableView->horizontalHeader()->sectionSize(column);
483  nResult = std::max(nResult, nTableWidth - nOtherColsWidth);
484  }
485 
486  return nResult;
487 }
488 
489 // Make sure we don't make the columns wider than the table's viewport width.
491 {
492  disconnectViewHeadersSignals();
493  resizeColumn(lastColumnIndex, getAvailableWidthForColumn(lastColumnIndex));
494  connectViewHeadersSignals();
495 
496  int nTableWidth = tableView->horizontalHeader()->width();
497  int nColsWidth = getColumnsWidth();
498  if (nColsWidth > nTableWidth)
499  {
500  resizeColumn(secondToLastColumnIndex,getAvailableWidthForColumn(secondToLastColumnIndex));
501  }
502 }
503 
504 // Make column use all the space available, useful during window resizing.
506 {
507  disconnectViewHeadersSignals();
508  resizeColumn(column, getAvailableWidthForColumn(column));
509  connectViewHeadersSignals();
510 }
511 
512 // When a section is resized this is a slot-proxy for ajustAmountColumnWidth().
513 void TableViewLastColumnResizingFixer::on_sectionResized(int logicalIndex, int oldSize, int newSize)
514 {
515  adjustTableColumnsWidth();
516  int remainingWidth = getAvailableWidthForColumn(logicalIndex);
517  if (newSize > remainingWidth)
518  {
519  resizeColumn(logicalIndex, remainingWidth);
520  }
521 }
522 
523 // When the table's geometry is ready, we manually perform the stretch of the "Message" column,
524 // as the "Stretch" resize mode does not allow for interactive resizing.
526 {
527  if ((getColumnsWidth() - this->tableView->horizontalHeader()->width()) != 0)
528  {
529  disconnectViewHeadersSignals();
530  resizeColumn(secondToLastColumnIndex, getAvailableWidthForColumn(secondToLastColumnIndex));
531  connectViewHeadersSignals();
532  }
533 }
534 
539 TableViewLastColumnResizingFixer::TableViewLastColumnResizingFixer(QTableView* table, int lastColMinimumWidth, int allColsMinimumWidth, QObject *parent) :
540  QObject(parent),
541  tableView(table),
542  lastColumnMinimumWidth(lastColMinimumWidth),
543  allColumnsMinimumWidth(allColsMinimumWidth)
544 {
545  columnCount = tableView->horizontalHeader()->count();
548  tableView->horizontalHeader()->setMinimumSectionSize(allColumnsMinimumWidth);
549  setViewHeaderResizeMode(secondToLastColumnIndex, QHeaderView::Interactive);
550  setViewHeaderResizeMode(lastColumnIndex, QHeaderView::Interactive);
551 }
552 
553 #ifdef WIN32
554 fs::path static StartupShortcutPath()
555 {
556  std::string chain = gArgs.GetChainName();
557  if (chain == CBaseChainParams::MAIN)
558  return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin.lnk";
559  if (chain == CBaseChainParams::TESTNET) // Remove this special case when CBaseChainParams::TESTNET = "testnet4"
560  return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin (testnet).lnk";
561  return GetSpecialFolderPath(CSIDL_STARTUP) / strprintf("Bitcoin (%s).lnk", chain);
562 }
563 
565 {
566  // check for Bitcoin*.lnk
567  return fs::exists(StartupShortcutPath());
568 }
569 
570 bool SetStartOnSystemStartup(bool fAutoStart)
571 {
572  // If the shortcut exists already, remove it for updating
573  fs::remove(StartupShortcutPath());
574 
575  if (fAutoStart)
576  {
577  CoInitialize(nullptr);
578 
579  // Get a pointer to the IShellLink interface.
580  IShellLinkW* psl = nullptr;
581  HRESULT hres = CoCreateInstance(CLSID_ShellLink, nullptr,
582  CLSCTX_INPROC_SERVER, IID_IShellLinkW,
583  reinterpret_cast<void**>(&psl));
584 
585  if (SUCCEEDED(hres))
586  {
587  // Get the current executable path
588  WCHAR pszExePath[MAX_PATH];
589  GetModuleFileNameW(nullptr, pszExePath, ARRAYSIZE(pszExePath));
590 
591  // Start client minimized
592  QString strArgs = "-min";
593  // Set -testnet /-regtest options
594  strArgs += QString::fromStdString(strprintf(" -chain=%s", gArgs.GetChainName()));
595 
596  // Set the path to the shortcut target
597  psl->SetPath(pszExePath);
598  PathRemoveFileSpecW(pszExePath);
599  psl->SetWorkingDirectory(pszExePath);
600  psl->SetShowCmd(SW_SHOWMINNOACTIVE);
601  psl->SetArguments(strArgs.toStdWString().c_str());
602 
603  // Query IShellLink for the IPersistFile interface for
604  // saving the shortcut in persistent storage.
605  IPersistFile* ppf = nullptr;
606  hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf));
607  if (SUCCEEDED(hres))
608  {
609  // Save the link by calling IPersistFile::Save.
610  hres = ppf->Save(StartupShortcutPath().wstring().c_str(), TRUE);
611  ppf->Release();
612  psl->Release();
613  CoUninitialize();
614  return true;
615  }
616  psl->Release();
617  }
618  CoUninitialize();
619  return false;
620  }
621  return true;
622 }
623 #elif defined(Q_OS_LINUX)
624 
625 // Follow the Desktop Application Autostart Spec:
626 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
627 
628 fs::path static GetAutostartDir()
629 {
630  char* pszConfigHome = getenv("XDG_CONFIG_HOME");
631  if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
632  char* pszHome = getenv("HOME");
633  if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
634  return fs::path();
635 }
636 
637 fs::path static GetAutostartFilePath()
638 {
639  std::string chain = gArgs.GetChainName();
640  if (chain == CBaseChainParams::MAIN)
641  return GetAutostartDir() / "bitcoin.desktop";
642  return GetAutostartDir() / strprintf("bitcoin-%s.desktop", chain);
643 }
644 
646 {
647  fsbridge::ifstream optionFile(GetAutostartFilePath());
648  if (!optionFile.good())
649  return false;
650  // Scan through file for "Hidden=true":
651  std::string line;
652  while (!optionFile.eof())
653  {
654  getline(optionFile, line);
655  if (line.find("Hidden") != std::string::npos &&
656  line.find("true") != std::string::npos)
657  return false;
658  }
659  optionFile.close();
660 
661  return true;
662 }
663 
664 bool SetStartOnSystemStartup(bool fAutoStart)
665 {
666  if (!fAutoStart)
667  fs::remove(GetAutostartFilePath());
668  else
669  {
670  char pszExePath[MAX_PATH+1];
671  ssize_t r = readlink("/proc/self/exe", pszExePath, sizeof(pszExePath) - 1);
672  if (r == -1)
673  return false;
674  pszExePath[r] = '\0';
675 
676  fs::create_directories(GetAutostartDir());
677 
678  fsbridge::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out | std::ios_base::trunc);
679  if (!optionFile.good())
680  return false;
681  std::string chain = gArgs.GetChainName();
682  // Write a bitcoin.desktop file to the autostart directory:
683  optionFile << "[Desktop Entry]\n";
684  optionFile << "Type=Application\n";
685  if (chain == CBaseChainParams::MAIN)
686  optionFile << "Name=Bitcoin\n";
687  else
688  optionFile << strprintf("Name=Bitcoin (%s)\n", chain);
689  optionFile << "Exec=" << pszExePath << strprintf(" -min -chain=%s\n", chain);
690  optionFile << "Terminal=false\n";
691  optionFile << "Hidden=false\n";
692  optionFile.close();
693  }
694  return true;
695 }
696 
697 #else
698 
699 bool GetStartOnSystemStartup() { return false; }
700 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
701 
702 #endif
703 
704 void setClipboard(const QString& str)
705 {
706  QApplication::clipboard()->setText(str, QClipboard::Clipboard);
707  QApplication::clipboard()->setText(str, QClipboard::Selection);
708 }
709 
710 fs::path qstringToBoostPath(const QString &path)
711 {
712  return fs::path(path.toStdString());
713 }
714 
715 QString boostPathToQString(const fs::path &path)
716 {
717  return QString::fromStdString(path.string());
718 }
719 
720 QString formatDurationStr(int secs)
721 {
722  QStringList strList;
723  int days = secs / 86400;
724  int hours = (secs % 86400) / 3600;
725  int mins = (secs % 3600) / 60;
726  int seconds = secs % 60;
727 
728  if (days)
729  strList.append(QString(QObject::tr("%1 d")).arg(days));
730  if (hours)
731  strList.append(QString(QObject::tr("%1 h")).arg(hours));
732  if (mins)
733  strList.append(QString(QObject::tr("%1 m")).arg(mins));
734  if (seconds || (!days && !hours && !mins))
735  strList.append(QString(QObject::tr("%1 s")).arg(seconds));
736 
737  return strList.join(" ");
738 }
739 
740 QString serviceFlagToStr(const quint64 mask, const int bit)
741 {
742  switch (ServiceFlags(mask)) {
743  case NODE_NONE: abort(); // impossible
744  case NODE_NETWORK: return "NETWORK";
745  case NODE_GETUTXO: return "GETUTXO";
746  case NODE_BLOOM: return "BLOOM";
747  case NODE_WITNESS: return "WITNESS";
748  case NODE_NETWORK_LIMITED: return "NETWORK_LIMITED";
749  // Not using default, so we get warned when a case is missing
750  }
751  if (bit < 8) {
752  return QString("%1[%2]").arg("UNKNOWN").arg(mask);
753  } else {
754  return QString("%1[2^%2]").arg("UNKNOWN").arg(bit);
755  }
756 }
757 
758 QString formatServicesStr(quint64 mask)
759 {
760  QStringList strList;
761 
762  for (int i = 0; i < 64; i++) {
763  uint64_t check = 1LL << i;
764  if (mask & check)
765  {
766  strList.append(serviceFlagToStr(check, i));
767  }
768  }
769 
770  if (strList.size())
771  return strList.join(" & ");
772  else
773  return QObject::tr("None");
774 }
775 
776 QString formatPingTime(double dPingTime)
777 {
778  return (dPingTime == std::numeric_limits<int64_t>::max()/1e6 || dPingTime == 0) ? QObject::tr("N/A") : QString(QObject::tr("%1 ms")).arg(QString::number((int)(dPingTime * 1000), 10));
779 }
780 
781 QString formatTimeOffset(int64_t nTimeOffset)
782 {
783  return QString(QObject::tr("%1 s")).arg(QString::number((int)nTimeOffset, 10));
784 }
785 
786 QString formatNiceTimeOffset(qint64 secs)
787 {
788  // Represent time from last generated block in human readable text
789  QString timeBehindText;
790  const int HOUR_IN_SECONDS = 60*60;
791  const int DAY_IN_SECONDS = 24*60*60;
792  const int WEEK_IN_SECONDS = 7*24*60*60;
793  const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar
794  if(secs < 60)
795  {
796  timeBehindText = QObject::tr("%n second(s)","",secs);
797  }
798  else if(secs < 2*HOUR_IN_SECONDS)
799  {
800  timeBehindText = QObject::tr("%n minute(s)","",secs/60);
801  }
802  else if(secs < 2*DAY_IN_SECONDS)
803  {
804  timeBehindText = QObject::tr("%n hour(s)","",secs/HOUR_IN_SECONDS);
805  }
806  else if(secs < 2*WEEK_IN_SECONDS)
807  {
808  timeBehindText = QObject::tr("%n day(s)","",secs/DAY_IN_SECONDS);
809  }
810  else if(secs < YEAR_IN_SECONDS)
811  {
812  timeBehindText = QObject::tr("%n week(s)","",secs/WEEK_IN_SECONDS);
813  }
814  else
815  {
816  qint64 years = secs / YEAR_IN_SECONDS;
817  qint64 remainder = secs % YEAR_IN_SECONDS;
818  timeBehindText = QObject::tr("%1 and %2").arg(QObject::tr("%n year(s)", "", years)).arg(QObject::tr("%n week(s)","", remainder/WEEK_IN_SECONDS));
819  }
820  return timeBehindText;
821 }
822 
823 QString formatBytes(uint64_t bytes)
824 {
825  if(bytes < 1024)
826  return QString(QObject::tr("%1 B")).arg(bytes);
827  if(bytes < 1024 * 1024)
828  return QString(QObject::tr("%1 KB")).arg(bytes / 1024);
829  if(bytes < 1024 * 1024 * 1024)
830  return QString(QObject::tr("%1 MB")).arg(bytes / 1024 / 1024);
831 
832  return QString(QObject::tr("%1 GB")).arg(bytes / 1024 / 1024 / 1024);
833 }
834 
835 qreal calculateIdealFontSize(int width, const QString& text, QFont font, qreal minPointSize, qreal font_size) {
836  while(font_size >= minPointSize) {
837  font.setPointSizeF(font_size);
838  QFontMetrics fm(font);
839  if (TextWidth(fm, text) < width) {
840  break;
841  }
842  font_size -= 0.5;
843  }
844  return font_size;
845 }
846 
847 void ClickableLabel::mouseReleaseEvent(QMouseEvent *event)
848 {
849  Q_EMIT clicked(event->pos());
850 }
851 
853 {
854  Q_EMIT clicked(event->pos());
855 }
856 
857 bool ItemDelegate::eventFilter(QObject *object, QEvent *event)
858 {
859  if (event->type() == QEvent::KeyPress) {
860  if (static_cast<QKeyEvent*>(event)->key() == Qt::Key_Escape) {
861  Q_EMIT keyEscapePressed();
862  }
863  }
864  return QItemDelegate::eventFilter(object, event);
865 }
866 
867 void PolishProgressDialog(QProgressDialog* dialog)
868 {
869 #ifdef Q_OS_MAC
870  // Workaround for macOS-only Qt bug; see: QTBUG-65750, QTBUG-70357.
871  const int margin = TextWidth(dialog->fontMetrics(), ("X"));
872  dialog->resize(dialog->width() + 2 * margin, dialog->height());
873  dialog->show();
874 #else
875  Q_UNUSED(dialog);
876 #endif
877 }
878 
879 int TextWidth(const QFontMetrics& fm, const QString& text)
880 {
881 #if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
882  return fm.horizontalAdvance(text);
883 #else
884  return fm.width(text);
885 #endif
886 }
887 
888 void LogQtInfo()
889 {
890 #ifdef QT_STATIC
891  const std::string qt_link{"static"};
892 #else
893  const std::string qt_link{"dynamic"};
894 #endif
895 #ifdef QT_STATICPLUGIN
896  const std::string plugin_link{"static"};
897 #else
898  const std::string plugin_link{"dynamic"};
899 #endif
900  LogPrintf("Qt %s (%s), plugin=%s (%s)\n", qVersion(), qt_link, QGuiApplication::platformName().toStdString(), plugin_link);
901  LogPrintf("System: %s, %s\n", QSysInfo::prettyProductName().toStdString(), QSysInfo::buildAbi().toStdString());
902  for (const QScreen* s : QGuiApplication::screens()) {
903  LogPrintf("Screen: %s %dx%d, pixel ratio=%.1f\n", s->name().toStdString(), s->size().width(), s->size().height(), s->devicePixelRatio());
904  }
905 }
906 
907 } // namespace GUIUtil
void openDebugLogfile()
Definition: guiutil.cpp:381
ToolTipToRichTextFilter(int size_threshold, QObject *parent=nullptr)
Definition: guiutil.cpp:414
QFont fixedPitchFont()
Definition: guiutil.cpp:81
Utility functions used by the Bitcoin Qt UI.
Definition: bitcoingui.h:55
void LogQtInfo()
Writes to debug.log short info about the used Qt and the host system.
Definition: guiutil.cpp:888
ServiceFlags
nServices flags
Definition: protocol.h:239
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:304
QList< QModelIndex > getEntryData(QAbstractItemView *view, int column)
Return a field of the currently selected entry as a QString.
Definition: guiutil.cpp:246
fs::path GetDefaultDataDir()
Definition: system.cpp:556
void setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode)
Definition: guiutil.cpp:454
bool IsValidDestinationString(const std::string &str, const CChainParams &params)
Definition: key_io.cpp:220
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
int TextWidth(const QFontMetrics &fm, const QString &text)
Returns the distance in pixels appropriate for drawing a subsequent character after text...
Definition: guiutil.cpp:879
bool isDust(interfaces::Node &node, const QString &address, const CAmount &amount)
Definition: guiutil.cpp:210
fs::ifstream ifstream
Definition: fs.h:90
#define MAX_PATH
Definition: compat.h:69
QString dateTimeStr(const QDateTime &date)
Definition: guiutil.cpp:71
std::string EncodeBase58(const unsigned char *pbegin, const unsigned char *pend)
Why base-58 instead of standard base-64 encoding?
Definition: base58.cpp:87
Qt::ConnectionType blockingGUIThreadConnection()
Get connection type to call object slot in GUI thread with invokeMethod.
Definition: guiutil.cpp:335
QString formatBytes(uint64_t bytes)
Definition: guiutil.cpp:823
QString formatTimeOffset(int64_t nTimeOffset)
Definition: guiutil.cpp:781
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:163
bool GetStartOnSystemStartup()
Definition: guiutil.cpp:699
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:47
QString HtmlEscape(const QString &str, bool fMultiLine)
Definition: guiutil.cpp:218
Line edit that can be marked as "invalid" to show input validation feedback.
fs::ofstream ofstream
Definition: fs.h:91
const char *const BITCOIN_CONF_FILENAME
Definition: system.cpp:74
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
Definition: guiutil.cpp:117
virtual CFeeRate getDustRelayFee()=0
Get dust relay fee.
QString formatBitcoinURI(const SendCoinsRecipient &info)
Definition: guiutil.cpp:180
static bool parse(int unit, const QString &value, CAmount *val_out)
Parse string to coin amount.
void bringToFront(QWidget *w)
Definition: guiutil.cpp:363
static const std::string MAIN
Chain name strings.
TableViewLastColumnResizingFixer(QTableView *table, int lastColMinimumWidth, int allColsMinimumWidth, QObject *parent)
Initializes all internal variables and prepares the the resize modes of the last 2 columns of the tab...
Definition: guiutil.cpp:539
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent)
Definition: guiutil.cpp:104
bool isObscured(QWidget *w)
Definition: guiutil.cpp:354
bool eventFilter(QObject *obj, QEvent *evt)
Definition: guiutil.cpp:421
qreal calculateIdealFontSize(int width, const QString &text, QFont font, qreal minPointSize, qreal font_size)
Definition: guiutil.cpp:835
QString formatDurationStr(int secs)
Definition: guiutil.cpp:720
void setClipboard(const QString &str)
Definition: guiutil.cpp:704
const fs::path & GetDataDir(bool fNetSpecific)
Definition: system.cpp:612
Base58 entry widget validator, checks for valid characters and removes some whitespace.
An output of a transaction.
Definition: transaction.h:133
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:289
void PolishProgressDialog(QProgressDialog *dialog)
Definition: guiutil.cpp:867
bool eventFilter(QObject *object, QEvent *event)
Definition: guiutil.cpp:857
QString formatPingTime(double dPingTime)
Definition: guiutil.cpp:776
void on_sectionResized(int logicalIndex, int oldSize, int newSize)
Definition: guiutil.cpp:513
void mouseReleaseEvent(QMouseEvent *event)
Definition: guiutil.cpp:847
QString serviceFlagToStr(const quint64 mask, const int bit)
Definition: guiutil.cpp:740
CTxDestination DecodeDestination(const std::string &str)
Definition: key_io.cpp:215
bool openBitcoinConf()
Definition: guiutil.cpp:390
void mouseReleaseEvent(QMouseEvent *event)
Definition: guiutil.cpp:852
fs::path GetConfigFile(const std::string &confPath)
Definition: system.cpp:657
fs::path qstringToBoostPath(const QString &path)
Definition: guiutil.cpp:710
const CChainParams & Params()
Return the currently selected parameters.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:390
QString formatServicesStr(quint64 mask)
Definition: guiutil.cpp:758
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:258
static std::string DummyAddress(const CChainParams &params)
Definition: guiutil.cpp:90
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:372
void ForceActivation()
Force application activation on macOS.
bool checkPoint(const QPoint &p, const QWidget *w)
Definition: guiutil.cpp:347
ArgsManager gArgs
Definition: system.cpp:76
Succeeded.
Definition: netbase.cpp:297
void setCheckValidator(const QValidator *v)
static const std::string TESTNET
bool IsDust(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:48
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
Definition: system.cpp:823
bool SetStartOnSystemStartup(bool fAutoStart)
Definition: guiutil.cpp:700
QString formatNiceTimeOffset(qint64 secs)
Definition: guiutil.cpp:786
boost::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:143
void copyEntryData(QAbstractItemView *view, int column, int role)
Copy a field of the currently selected entry of a view to the clipboard.
Definition: guiutil.cpp:233
QString getDefaultDataDirectory()
Determine default data directory for operating system.
Definition: guiutil.cpp:253
QString boostPathToQString(const fs::path &path)
Definition: guiutil.cpp:715
Bitcoin address widget validator, checks for a valid bitcoin address.
Top-level interface for a bitcoin node (bitcoind process).
Definition: node.h:39
static const uint8_t dummydata[]
Definition: guiutil.cpp:87
void resizeColumn(int nColumnIndex, int width)
Definition: guiutil.cpp:459
static QString format(int unit, const CAmount &amount, bool plussign=false, SeparatorStyle separators=separatorStandard)
Format as string.
const std::vector< unsigned char > & Base58Prefix(Base58Type type) const
Definition: chainparams.h:84