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