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