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::SeparatorStyle::NEVER));
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  : QObject(parent)
455 {
456 }
457 
458 bool LabelOutOfFocusEventFilter::eventFilter(QObject* watched, QEvent* event)
459 {
460  if (event->type() == QEvent::FocusOut) {
461  auto focus_out = static_cast<QFocusEvent*>(event);
462  if (focus_out->reason() != Qt::PopupFocusReason) {
463  auto label = qobject_cast<QLabel*>(watched);
464  if (label) {
465  auto flags = label->textInteractionFlags();
466  label->setTextInteractionFlags(Qt::NoTextInteraction);
467  label->setTextInteractionFlags(flags);
468  }
469  }
470  }
471 
472  return QObject::eventFilter(watched, event);
473 }
474 
476 {
477  connect(tableView->horizontalHeader(), &QHeaderView::sectionResized, this, &TableViewLastColumnResizingFixer::on_sectionResized);
478  connect(tableView->horizontalHeader(), &QHeaderView::geometriesChanged, this, &TableViewLastColumnResizingFixer::on_geometriesChanged);
479 }
480 
481 // We need to disconnect these while handling the resize events, otherwise we can enter infinite loops.
483 {
484  disconnect(tableView->horizontalHeader(), &QHeaderView::sectionResized, this, &TableViewLastColumnResizingFixer::on_sectionResized);
485  disconnect(tableView->horizontalHeader(), &QHeaderView::geometriesChanged, this, &TableViewLastColumnResizingFixer::on_geometriesChanged);
486 }
487 
488 // Setup the resize mode, handles compatibility for Qt5 and below as the method signatures changed.
489 // Refactored here for readability.
490 void TableViewLastColumnResizingFixer::setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode)
491 {
492  tableView->horizontalHeader()->setSectionResizeMode(logicalIndex, resizeMode);
493 }
494 
495 void TableViewLastColumnResizingFixer::resizeColumn(int nColumnIndex, int width)
496 {
497  tableView->setColumnWidth(nColumnIndex, width);
498  tableView->horizontalHeader()->resizeSection(nColumnIndex, width);
499 }
500 
502 {
503  int nColumnsWidthSum = 0;
504  for (int i = 0; i < columnCount; i++)
505  {
506  nColumnsWidthSum += tableView->horizontalHeader()->sectionSize(i);
507  }
508  return nColumnsWidthSum;
509 }
510 
512 {
513  int nResult = lastColumnMinimumWidth;
514  int nTableWidth = tableView->horizontalHeader()->width();
515 
516  if (nTableWidth > 0)
517  {
518  int nOtherColsWidth = getColumnsWidth() - tableView->horizontalHeader()->sectionSize(column);
519  nResult = std::max(nResult, nTableWidth - nOtherColsWidth);
520  }
521 
522  return nResult;
523 }
524 
525 // Make sure we don't make the columns wider than the table's viewport width.
527 {
528  disconnectViewHeadersSignals();
529  resizeColumn(lastColumnIndex, getAvailableWidthForColumn(lastColumnIndex));
530  connectViewHeadersSignals();
531 
532  int nTableWidth = tableView->horizontalHeader()->width();
533  int nColsWidth = getColumnsWidth();
534  if (nColsWidth > nTableWidth)
535  {
536  resizeColumn(secondToLastColumnIndex,getAvailableWidthForColumn(secondToLastColumnIndex));
537  }
538 }
539 
540 // Make column use all the space available, useful during window resizing.
542 {
543  disconnectViewHeadersSignals();
544  resizeColumn(column, getAvailableWidthForColumn(column));
545  connectViewHeadersSignals();
546 }
547 
548 // When a section is resized this is a slot-proxy for ajustAmountColumnWidth().
549 void TableViewLastColumnResizingFixer::on_sectionResized(int logicalIndex, int oldSize, int newSize)
550 {
551  adjustTableColumnsWidth();
552  int remainingWidth = getAvailableWidthForColumn(logicalIndex);
553  if (newSize > remainingWidth)
554  {
555  resizeColumn(logicalIndex, remainingWidth);
556  }
557 }
558 
559 // When the table's geometry is ready, we manually perform the stretch of the "Message" column,
560 // as the "Stretch" resize mode does not allow for interactive resizing.
562 {
563  if ((getColumnsWidth() - this->tableView->horizontalHeader()->width()) != 0)
564  {
565  disconnectViewHeadersSignals();
566  resizeColumn(secondToLastColumnIndex, getAvailableWidthForColumn(secondToLastColumnIndex));
567  connectViewHeadersSignals();
568  }
569 }
570 
575 TableViewLastColumnResizingFixer::TableViewLastColumnResizingFixer(QTableView* table, int lastColMinimumWidth, int allColsMinimumWidth, QObject *parent) :
576  QObject(parent),
577  tableView(table),
578  lastColumnMinimumWidth(lastColMinimumWidth),
579  allColumnsMinimumWidth(allColsMinimumWidth)
580 {
581  columnCount = tableView->horizontalHeader()->count();
584  tableView->horizontalHeader()->setMinimumSectionSize(allColumnsMinimumWidth);
585  setViewHeaderResizeMode(secondToLastColumnIndex, QHeaderView::Interactive);
586  setViewHeaderResizeMode(lastColumnIndex, QHeaderView::Interactive);
587 }
588 
589 #ifdef WIN32
590 fs::path static StartupShortcutPath()
591 {
592  std::string chain = gArgs.GetChainName();
593  if (chain == CBaseChainParams::MAIN)
594  return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin.lnk";
595  if (chain == CBaseChainParams::TESTNET) // Remove this special case when CBaseChainParams::TESTNET = "testnet4"
596  return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin (testnet).lnk";
597  return GetSpecialFolderPath(CSIDL_STARTUP) / strprintf("Bitcoin (%s).lnk", chain);
598 }
599 
601 {
602  // check for Bitcoin*.lnk
603  return fs::exists(StartupShortcutPath());
604 }
605 
606 bool SetStartOnSystemStartup(bool fAutoStart)
607 {
608  // If the shortcut exists already, remove it for updating
609  fs::remove(StartupShortcutPath());
610 
611  if (fAutoStart)
612  {
613  CoInitialize(nullptr);
614 
615  // Get a pointer to the IShellLink interface.
616  IShellLinkW* psl = nullptr;
617  HRESULT hres = CoCreateInstance(CLSID_ShellLink, nullptr,
618  CLSCTX_INPROC_SERVER, IID_IShellLinkW,
619  reinterpret_cast<void**>(&psl));
620 
621  if (SUCCEEDED(hres))
622  {
623  // Get the current executable path
624  WCHAR pszExePath[MAX_PATH];
625  GetModuleFileNameW(nullptr, pszExePath, ARRAYSIZE(pszExePath));
626 
627  // Start client minimized
628  QString strArgs = "-min";
629  // Set -testnet /-regtest options
630  strArgs += QString::fromStdString(strprintf(" -chain=%s", gArgs.GetChainName()));
631 
632  // Set the path to the shortcut target
633  psl->SetPath(pszExePath);
634  PathRemoveFileSpecW(pszExePath);
635  psl->SetWorkingDirectory(pszExePath);
636  psl->SetShowCmd(SW_SHOWMINNOACTIVE);
637  psl->SetArguments(strArgs.toStdWString().c_str());
638 
639  // Query IShellLink for the IPersistFile interface for
640  // saving the shortcut in persistent storage.
641  IPersistFile* ppf = nullptr;
642  hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf));
643  if (SUCCEEDED(hres))
644  {
645  // Save the link by calling IPersistFile::Save.
646  hres = ppf->Save(StartupShortcutPath().wstring().c_str(), TRUE);
647  ppf->Release();
648  psl->Release();
649  CoUninitialize();
650  return true;
651  }
652  psl->Release();
653  }
654  CoUninitialize();
655  return false;
656  }
657  return true;
658 }
659 #elif defined(Q_OS_LINUX)
660 
661 // Follow the Desktop Application Autostart Spec:
662 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
663 
664 fs::path static GetAutostartDir()
665 {
666  char* pszConfigHome = getenv("XDG_CONFIG_HOME");
667  if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
668  char* pszHome = getenv("HOME");
669  if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
670  return fs::path();
671 }
672 
673 fs::path static GetAutostartFilePath()
674 {
675  std::string chain = gArgs.GetChainName();
676  if (chain == CBaseChainParams::MAIN)
677  return GetAutostartDir() / "bitcoin.desktop";
678  return GetAutostartDir() / strprintf("bitcoin-%s.desktop", chain);
679 }
680 
682 {
683  fsbridge::ifstream optionFile(GetAutostartFilePath());
684  if (!optionFile.good())
685  return false;
686  // Scan through file for "Hidden=true":
687  std::string line;
688  while (!optionFile.eof())
689  {
690  getline(optionFile, line);
691  if (line.find("Hidden") != std::string::npos &&
692  line.find("true") != std::string::npos)
693  return false;
694  }
695  optionFile.close();
696 
697  return true;
698 }
699 
700 bool SetStartOnSystemStartup(bool fAutoStart)
701 {
702  if (!fAutoStart)
703  fs::remove(GetAutostartFilePath());
704  else
705  {
706  char pszExePath[MAX_PATH+1];
707  ssize_t r = readlink("/proc/self/exe", pszExePath, sizeof(pszExePath) - 1);
708  if (r == -1)
709  return false;
710  pszExePath[r] = '\0';
711 
712  fs::create_directories(GetAutostartDir());
713 
714  fsbridge::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out | std::ios_base::trunc);
715  if (!optionFile.good())
716  return false;
717  std::string chain = gArgs.GetChainName();
718  // Write a bitcoin.desktop file to the autostart directory:
719  optionFile << "[Desktop Entry]\n";
720  optionFile << "Type=Application\n";
721  if (chain == CBaseChainParams::MAIN)
722  optionFile << "Name=Bitcoin\n";
723  else
724  optionFile << strprintf("Name=Bitcoin (%s)\n", chain);
725  optionFile << "Exec=" << pszExePath << strprintf(" -min -chain=%s\n", chain);
726  optionFile << "Terminal=false\n";
727  optionFile << "Hidden=false\n";
728  optionFile.close();
729  }
730  return true;
731 }
732 
733 #else
734 
735 bool GetStartOnSystemStartup() { return false; }
736 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
737 
738 #endif
739 
740 void setClipboard(const QString& str)
741 {
742  QApplication::clipboard()->setText(str, QClipboard::Clipboard);
743  QApplication::clipboard()->setText(str, QClipboard::Selection);
744 }
745 
746 fs::path qstringToBoostPath(const QString &path)
747 {
748  return fs::path(path.toStdString());
749 }
750 
751 QString boostPathToQString(const fs::path &path)
752 {
753  return QString::fromStdString(path.string());
754 }
755 
756 QString formatDurationStr(int secs)
757 {
758  QStringList strList;
759  int days = secs / 86400;
760  int hours = (secs % 86400) / 3600;
761  int mins = (secs % 3600) / 60;
762  int seconds = secs % 60;
763 
764  if (days)
765  strList.append(QString(QObject::tr("%1 d")).arg(days));
766  if (hours)
767  strList.append(QString(QObject::tr("%1 h")).arg(hours));
768  if (mins)
769  strList.append(QString(QObject::tr("%1 m")).arg(mins));
770  if (seconds || (!days && !hours && !mins))
771  strList.append(QString(QObject::tr("%1 s")).arg(seconds));
772 
773  return strList.join(" ");
774 }
775 
776 QString formatServicesStr(quint64 mask)
777 {
778  QStringList strList;
779 
780  for (const auto& flag : serviceFlagsToStr(mask)) {
781  strList.append(QString::fromStdString(flag));
782  }
783 
784  if (strList.size())
785  return strList.join(" & ");
786  else
787  return QObject::tr("None");
788 }
789 
790 QString formatPingTime(int64_t ping_usec)
791 {
792  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));
793 }
794 
795 QString formatTimeOffset(int64_t nTimeOffset)
796 {
797  return QString(QObject::tr("%1 s")).arg(QString::number((int)nTimeOffset, 10));
798 }
799 
800 QString formatNiceTimeOffset(qint64 secs)
801 {
802  // Represent time from last generated block in human readable text
803  QString timeBehindText;
804  const int HOUR_IN_SECONDS = 60*60;
805  const int DAY_IN_SECONDS = 24*60*60;
806  const int WEEK_IN_SECONDS = 7*24*60*60;
807  const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar
808  if(secs < 60)
809  {
810  timeBehindText = QObject::tr("%n second(s)","",secs);
811  }
812  else if(secs < 2*HOUR_IN_SECONDS)
813  {
814  timeBehindText = QObject::tr("%n minute(s)","",secs/60);
815  }
816  else if(secs < 2*DAY_IN_SECONDS)
817  {
818  timeBehindText = QObject::tr("%n hour(s)","",secs/HOUR_IN_SECONDS);
819  }
820  else if(secs < 2*WEEK_IN_SECONDS)
821  {
822  timeBehindText = QObject::tr("%n day(s)","",secs/DAY_IN_SECONDS);
823  }
824  else if(secs < YEAR_IN_SECONDS)
825  {
826  timeBehindText = QObject::tr("%n week(s)","",secs/WEEK_IN_SECONDS);
827  }
828  else
829  {
830  qint64 years = secs / YEAR_IN_SECONDS;
831  qint64 remainder = secs % YEAR_IN_SECONDS;
832  timeBehindText = QObject::tr("%1 and %2").arg(QObject::tr("%n year(s)", "", years)).arg(QObject::tr("%n week(s)","", remainder/WEEK_IN_SECONDS));
833  }
834  return timeBehindText;
835 }
836 
837 QString formatBytes(uint64_t bytes)
838 {
839  if(bytes < 1024)
840  return QString(QObject::tr("%1 B")).arg(bytes);
841  if(bytes < 1024 * 1024)
842  return QString(QObject::tr("%1 KB")).arg(bytes / 1024);
843  if(bytes < 1024 * 1024 * 1024)
844  return QString(QObject::tr("%1 MB")).arg(bytes / 1024 / 1024);
845 
846  return QString(QObject::tr("%1 GB")).arg(bytes / 1024 / 1024 / 1024);
847 }
848 
849 qreal calculateIdealFontSize(int width, const QString& text, QFont font, qreal minPointSize, qreal font_size) {
850  while(font_size >= minPointSize) {
851  font.setPointSizeF(font_size);
852  QFontMetrics fm(font);
853  if (TextWidth(fm, text) < width) {
854  break;
855  }
856  font_size -= 0.5;
857  }
858  return font_size;
859 }
860 
861 void ClickableLabel::mouseReleaseEvent(QMouseEvent *event)
862 {
863  Q_EMIT clicked(event->pos());
864 }
865 
867 {
868  Q_EMIT clicked(event->pos());
869 }
870 
871 bool ItemDelegate::eventFilter(QObject *object, QEvent *event)
872 {
873  if (event->type() == QEvent::KeyPress) {
874  if (static_cast<QKeyEvent*>(event)->key() == Qt::Key_Escape) {
875  Q_EMIT keyEscapePressed();
876  }
877  }
878  return QItemDelegate::eventFilter(object, event);
879 }
880 
881 void PolishProgressDialog(QProgressDialog* dialog)
882 {
883 #ifdef Q_OS_MAC
884  // Workaround for macOS-only Qt bug; see: QTBUG-65750, QTBUG-70357.
885  const int margin = TextWidth(dialog->fontMetrics(), ("X"));
886  dialog->resize(dialog->width() + 2 * margin, dialog->height());
887  dialog->show();
888 #else
889  Q_UNUSED(dialog);
890 #endif
891 }
892 
893 int TextWidth(const QFontMetrics& fm, const QString& text)
894 {
895 #if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
896  return fm.horizontalAdvance(text);
897 #else
898  return fm.width(text);
899 #endif
900 }
901 
902 void LogQtInfo()
903 {
904 #ifdef QT_STATIC
905  const std::string qt_link{"static"};
906 #else
907  const std::string qt_link{"dynamic"};
908 #endif
909 #ifdef QT_STATICPLUGIN
910  const std::string plugin_link{"static"};
911 #else
912  const std::string plugin_link{"dynamic"};
913 #endif
914  LogPrintf("Qt %s (%s), plugin=%s (%s)\n", qVersion(), qt_link, QGuiApplication::platformName().toStdString(), plugin_link);
915  LogPrintf("System: %s, %s\n", QSysInfo::prettyProductName().toStdString(), QSysInfo::buildAbi().toStdString());
916  for (const QScreen* s : QGuiApplication::screens()) {
917  LogPrintf("Screen: %s %dx%d, pixel ratio=%.1f\n", s->name().toStdString(), s->size().width(), s->size().height(), s->devicePixelRatio());
918  }
919 }
920 
921 void PopupMenu(QMenu* menu, const QPoint& point, QAction* at_action)
922 {
923  // The qminimal plugin does not provide window system integration.
924  if (QApplication::platformName() == "minimal") return;
925  menu->popup(point, at_action);
926 }
927 
928 } // 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:902
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:647
void mouseReleaseEvent(QMouseEvent *event) override
Definition: guiutil.cpp:866
void setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode)
Definition: guiutil.cpp:490
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:921
int TextWidth(const QFontMetrics &fm, const QString &text)
Returns the distance in pixels appropriate for drawing a subsequent character after text...
Definition: guiutil.cpp:893
bool isDust(interfaces::Node &node, const QString &address, const CAmount &amount)
Definition: guiutil.cpp:212
static QString format(int unit, const CAmount &amount, bool plussign=false, SeparatorStyle separators=SeparatorStyle::STANDARD, bool justify=false)
Format as string.
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:837
QString formatTimeOffset(int64_t nTimeOffset)
Definition: guiutil.cpp:795
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:166
bool GetStartOnSystemStartup()
Definition: guiutil.cpp:735
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:232
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:79
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:575
bool eventFilter(QObject *object, QEvent *event) override
Definition: guiutil.cpp:871
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
void mouseReleaseEvent(QMouseEvent *event) override
Definition: guiutil.cpp:861
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:790
qreal calculateIdealFontSize(int width, const QString &text, QFont font, qreal minPointSize, qreal font_size)
Definition: guiutil.cpp:849
QString formatDurationStr(int secs)
Definition: guiutil.cpp:756
void setClipboard(const QString &str)
Definition: guiutil.cpp:740
void handleCloseWindowShortcut(QWidget *w)
Definition: guiutil.cpp:390
const fs::path & GetDataDir(bool fNetSpecific)
Definition: system.cpp:703
bool eventFilter(QObject *watched, QEvent *event) override
Definition: guiutil.cpp:458
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:122
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:295
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:881
void on_sectionResized(int logicalIndex, int oldSize, int newSize)
Definition: guiutil.cpp:549
int flags
Definition: bitcoin-tx.cpp:509
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:748
fs::path qstringToBoostPath(const QString &path)
Definition: guiutil.cpp:746
LabelOutOfFocusEventFilter(QObject *parent)
Definition: guiutil.cpp:453
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:776
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:463
void ForceActivation()
Force application activation on macOS.
bool checkPoint(const QPoint &p, const QWidget *w)
Definition: guiutil.cpp:356
ArgsManager gArgs
Definition: system.cpp:82
Succeeded.
Definition: netbase.cpp:298
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:914
bool SetStartOnSystemStartup(bool fAutoStart)
Definition: guiutil.cpp:736
QString formatNiceTimeOffset(qint64 secs)
Definition: guiutil.cpp:800
boost::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:212
QString getDefaultDataDirectory()
Determine default data directory for operating system.
Definition: guiutil.cpp:262
QString boostPathToQString(const fs::path &path)
Definition: guiutil.cpp:751
Bitcoin address widget validator, checks for a valid bitcoin address.
Top-level interface for a bitcoin node (bitcoind process).
Definition: node.h:43
static const uint8_t dummydata[]
Definition: guiutil.cpp:89
void resizeColumn(int nColumnIndex, int width)
Definition: guiutil.cpp:495
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