Bitcoin Core  0.18.99
P2P Digital Currency
guiutil.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-2018 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/walletmodel.h>
11 
12 #include <base58.h>
13 #include <chainparams.h>
14 #include <primitives/transaction.h>
15 #include <key_io.h>
16 #include <interfaces/node.h>
17 #include <policy/policy.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 <QDesktopWidget>
43 #include <QDoubleValidator>
44 #include <QFileDialog>
45 #include <QFont>
46 #include <QFontDatabase>
47 #include <QFontMetrics>
48 #include <QKeyEvent>
49 #include <QLineEdit>
50 #include <QMouseEvent>
51 #include <QProgressDialog>
52 #include <QSettings>
53 #include <QTextDocument> // for Qt::mightBeRichText
54 #include <QThread>
55 #include <QUrlQuery>
56 
57 #if defined(Q_OS_MAC)
58 #pragma GCC diagnostic push
59 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
60 
61 #include <objc/objc-runtime.h>
62 #include <CoreServices/CoreServices.h>
63 #include <QProcess>
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.data(), sourcedata.data() + sourcedata.size());
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::separatorNever));
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(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(QAbstractItemView *view, int column)
244 {
245  if(!view || !view->selectionModel())
246  return QList<QModelIndex>();
247  return view->selectionModel()->selectedRows(column);
248 }
249 
251 {
253 }
254 
255 QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir,
256  const QString &filter,
257  QString *selectedSuffixOut)
258 {
259  QString selectedFilter;
260  QString myDir;
261  if(dir.isEmpty()) // Default to user documents location
262  {
263  myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
264  }
265  else
266  {
267  myDir = dir;
268  }
269  /* Directly convert path to native OS path separators */
270  QString result = QDir::toNativeSeparators(QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter));
271 
272  /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
273  QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
274  QString selectedSuffix;
275  if(filter_re.exactMatch(selectedFilter))
276  {
277  selectedSuffix = filter_re.cap(1);
278  }
279 
280  /* Add suffix if needed */
281  QFileInfo info(result);
282  if(!result.isEmpty())
283  {
284  if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
285  {
286  /* No suffix specified, add selected suffix */
287  if(!result.endsWith("."))
288  result.append(".");
289  result.append(selectedSuffix);
290  }
291  }
292 
293  /* Return selected suffix if asked to */
294  if(selectedSuffixOut)
295  {
296  *selectedSuffixOut = selectedSuffix;
297  }
298  return result;
299 }
300 
301 QString getOpenFileName(QWidget *parent, const QString &caption, const QString &dir,
302  const QString &filter,
303  QString *selectedSuffixOut)
304 {
305  QString selectedFilter;
306  QString myDir;
307  if(dir.isEmpty()) // Default to user documents location
308  {
309  myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
310  }
311  else
312  {
313  myDir = dir;
314  }
315  /* Directly convert path to native OS path separators */
316  QString result = QDir::toNativeSeparators(QFileDialog::getOpenFileName(parent, caption, myDir, filter, &selectedFilter));
317 
318  if(selectedSuffixOut)
319  {
320  /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
321  QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
322  QString selectedSuffix;
323  if(filter_re.exactMatch(selectedFilter))
324  {
325  selectedSuffix = filter_re.cap(1);
326  }
327  *selectedSuffixOut = selectedSuffix;
328  }
329  return result;
330 }
331 
332 Qt::ConnectionType blockingGUIThreadConnection()
333 {
334  if(QThread::currentThread() != qApp->thread())
335  {
336  return Qt::BlockingQueuedConnection;
337  }
338  else
339  {
340  return Qt::DirectConnection;
341  }
342 }
343 
344 bool checkPoint(const QPoint &p, const QWidget *w)
345 {
346  QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p));
347  if (!atW) return false;
348  return atW->window() == w;
349 }
350 
351 bool isObscured(QWidget *w)
352 {
353  return !(checkPoint(QPoint(0, 0), w)
354  && checkPoint(QPoint(w->width() - 1, 0), w)
355  && checkPoint(QPoint(0, w->height() - 1), w)
356  && checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
357  && checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
358 }
359 
360 void bringToFront(QWidget* w)
361 {
362 #ifdef Q_OS_MAC
363  // Force application activation on macOS. With Qt 5.4 this is required when
364  // an action in the dock menu is triggered.
365  id app = objc_msgSend((id) objc_getClass("NSApplication"), sel_registerName("sharedApplication"));
366  objc_msgSend(app, sel_registerName("activateIgnoringOtherApps:"), YES);
367 #endif
368 
369  if (w) {
370  // activateWindow() (sometimes) helps with keyboard focus on Windows
371  if (w->isMinimized()) {
372  w->showNormal();
373  } else {
374  w->show();
375  }
376  w->activateWindow();
377  w->raise();
378  }
379 }
380 
382 {
383  fs::path pathDebug = GetDataDir() / "debug.log";
384 
385  /* Open debug.log with the associated application */
386  if (fs::exists(pathDebug))
387  QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathDebug)));
388 }
389 
391 {
392  fs::path pathConfig = GetConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME));
393 
394  /* Create the file */
395  fsbridge::ofstream configFile(pathConfig, std::ios_base::app);
396 
397  if (!configFile.good())
398  return false;
399 
400  configFile.close();
401 
402  /* Open bitcoin.conf with the associated application */
403  bool res = QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathConfig)));
404 #ifdef Q_OS_MAC
405  // Workaround for macOS-specific behavior; see #15409.
406  if (!res) {
407  res = QProcess::startDetached("/usr/bin/open", QStringList{"-t", boostPathToQString(pathConfig)});
408  }
409 #endif
410 
411  return res;
412 }
413 
414 ToolTipToRichTextFilter::ToolTipToRichTextFilter(int _size_threshold, QObject *parent) :
415  QObject(parent),
416  size_threshold(_size_threshold)
417 {
418 
419 }
420 
421 bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
422 {
423  if(evt->type() == QEvent::ToolTipChange)
424  {
425  QWidget *widget = static_cast<QWidget*>(obj);
426  QString tooltip = widget->toolTip();
427  if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt") && !Qt::mightBeRichText(tooltip))
428  {
429  // Envelop with <qt></qt> to make sure Qt detects this as rich text
430  // Escape the current message as HTML and replace \n by <br>
431  tooltip = "<qt>" + HtmlEscape(tooltip, true) + "</qt>";
432  widget->setToolTip(tooltip);
433  return true;
434  }
435  }
436  return QObject::eventFilter(obj, evt);
437 }
438 
440 {
441  connect(tableView->horizontalHeader(), &QHeaderView::sectionResized, this, &TableViewLastColumnResizingFixer::on_sectionResized);
442  connect(tableView->horizontalHeader(), &QHeaderView::geometriesChanged, this, &TableViewLastColumnResizingFixer::on_geometriesChanged);
443 }
444 
445 // We need to disconnect these while handling the resize events, otherwise we can enter infinite loops.
447 {
448  disconnect(tableView->horizontalHeader(), &QHeaderView::sectionResized, this, &TableViewLastColumnResizingFixer::on_sectionResized);
449  disconnect(tableView->horizontalHeader(), &QHeaderView::geometriesChanged, this, &TableViewLastColumnResizingFixer::on_geometriesChanged);
450 }
451 
452 // Setup the resize mode, handles compatibility for Qt5 and below as the method signatures changed.
453 // Refactored here for readability.
454 void TableViewLastColumnResizingFixer::setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode)
455 {
456  tableView->horizontalHeader()->setSectionResizeMode(logicalIndex, resizeMode);
457 }
458 
459 void TableViewLastColumnResizingFixer::resizeColumn(int nColumnIndex, int width)
460 {
461  tableView->setColumnWidth(nColumnIndex, width);
462  tableView->horizontalHeader()->resizeSection(nColumnIndex, width);
463 }
464 
466 {
467  int nColumnsWidthSum = 0;
468  for (int i = 0; i < columnCount; i++)
469  {
470  nColumnsWidthSum += tableView->horizontalHeader()->sectionSize(i);
471  }
472  return nColumnsWidthSum;
473 }
474 
476 {
477  int nResult = lastColumnMinimumWidth;
478  int nTableWidth = tableView->horizontalHeader()->width();
479 
480  if (nTableWidth > 0)
481  {
482  int nOtherColsWidth = getColumnsWidth() - tableView->horizontalHeader()->sectionSize(column);
483  nResult = std::max(nResult, nTableWidth - nOtherColsWidth);
484  }
485 
486  return nResult;
487 }
488 
489 // Make sure we don't make the columns wider than the table's viewport width.
491 {
492  disconnectViewHeadersSignals();
493  resizeColumn(lastColumnIndex, getAvailableWidthForColumn(lastColumnIndex));
494  connectViewHeadersSignals();
495 
496  int nTableWidth = tableView->horizontalHeader()->width();
497  int nColsWidth = getColumnsWidth();
498  if (nColsWidth > nTableWidth)
499  {
500  resizeColumn(secondToLastColumnIndex,getAvailableWidthForColumn(secondToLastColumnIndex));
501  }
502 }
503 
504 // Make column use all the space available, useful during window resizing.
506 {
507  disconnectViewHeadersSignals();
508  resizeColumn(column, getAvailableWidthForColumn(column));
509  connectViewHeadersSignals();
510 }
511 
512 // When a section is resized this is a slot-proxy for ajustAmountColumnWidth().
513 void TableViewLastColumnResizingFixer::on_sectionResized(int logicalIndex, int oldSize, int newSize)
514 {
515  adjustTableColumnsWidth();
516  int remainingWidth = getAvailableWidthForColumn(logicalIndex);
517  if (newSize > remainingWidth)
518  {
519  resizeColumn(logicalIndex, remainingWidth);
520  }
521 }
522 
523 // When the table's geometry is ready, we manually perform the stretch of the "Message" column,
524 // as the "Stretch" resize mode does not allow for interactive resizing.
526 {
527  if ((getColumnsWidth() - this->tableView->horizontalHeader()->width()) != 0)
528  {
529  disconnectViewHeadersSignals();
530  resizeColumn(secondToLastColumnIndex, getAvailableWidthForColumn(secondToLastColumnIndex));
531  connectViewHeadersSignals();
532  }
533 }
534 
539 TableViewLastColumnResizingFixer::TableViewLastColumnResizingFixer(QTableView* table, int lastColMinimumWidth, int allColsMinimumWidth, QObject *parent) :
540  QObject(parent),
541  tableView(table),
542  lastColumnMinimumWidth(lastColMinimumWidth),
543  allColumnsMinimumWidth(allColsMinimumWidth)
544 {
545  columnCount = tableView->horizontalHeader()->count();
548  tableView->horizontalHeader()->setMinimumSectionSize(allColumnsMinimumWidth);
549  setViewHeaderResizeMode(secondToLastColumnIndex, QHeaderView::Interactive);
550  setViewHeaderResizeMode(lastColumnIndex, QHeaderView::Interactive);
551 }
552 
553 #ifdef WIN32
554 fs::path static StartupShortcutPath()
555 {
556  std::string chain = gArgs.GetChainName();
557  if (chain == CBaseChainParams::MAIN)
558  return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin.lnk";
559  if (chain == CBaseChainParams::TESTNET) // Remove this special case when CBaseChainParams::TESTNET = "testnet4"
560  return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin (testnet).lnk";
561  return GetSpecialFolderPath(CSIDL_STARTUP) / strprintf("Bitcoin (%s).lnk", chain);
562 }
563 
565 {
566  // check for Bitcoin*.lnk
567  return fs::exists(StartupShortcutPath());
568 }
569 
570 bool SetStartOnSystemStartup(bool fAutoStart)
571 {
572  // If the shortcut exists already, remove it for updating
573  fs::remove(StartupShortcutPath());
574 
575  if (fAutoStart)
576  {
577  CoInitialize(nullptr);
578 
579  // Get a pointer to the IShellLink interface.
580  IShellLinkW* psl = nullptr;
581  HRESULT hres = CoCreateInstance(CLSID_ShellLink, nullptr,
582  CLSCTX_INPROC_SERVER, IID_IShellLinkW,
583  reinterpret_cast<void**>(&psl));
584 
585  if (SUCCEEDED(hres))
586  {
587  // Get the current executable path
588  WCHAR pszExePath[MAX_PATH];
589  GetModuleFileNameW(nullptr, pszExePath, ARRAYSIZE(pszExePath));
590 
591  // Start client minimized
592  QString strArgs = "-min";
593  // Set -testnet /-regtest options
594  strArgs += QString::fromStdString(strprintf(" -testnet=%d -regtest=%d", gArgs.GetBoolArg("-testnet", false), gArgs.GetBoolArg("-regtest", false)));
595 
596  // Set the path to the shortcut target
597  psl->SetPath(pszExePath);
598  PathRemoveFileSpecW(pszExePath);
599  psl->SetWorkingDirectory(pszExePath);
600  psl->SetShowCmd(SW_SHOWMINNOACTIVE);
601  psl->SetArguments(strArgs.toStdWString().c_str());
602 
603  // Query IShellLink for the IPersistFile interface for
604  // saving the shortcut in persistent storage.
605  IPersistFile* ppf = nullptr;
606  hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf));
607  if (SUCCEEDED(hres))
608  {
609  // Save the link by calling IPersistFile::Save.
610  hres = ppf->Save(StartupShortcutPath().wstring().c_str(), TRUE);
611  ppf->Release();
612  psl->Release();
613  CoUninitialize();
614  return true;
615  }
616  psl->Release();
617  }
618  CoUninitialize();
619  return false;
620  }
621  return true;
622 }
623 #elif defined(Q_OS_LINUX)
624 
625 // Follow the Desktop Application Autostart Spec:
626 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
627 
628 fs::path static GetAutostartDir()
629 {
630  char* pszConfigHome = getenv("XDG_CONFIG_HOME");
631  if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
632  char* pszHome = getenv("HOME");
633  if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
634  return fs::path();
635 }
636 
637 fs::path static GetAutostartFilePath()
638 {
639  std::string chain = gArgs.GetChainName();
640  if (chain == CBaseChainParams::MAIN)
641  return GetAutostartDir() / "bitcoin.desktop";
642  return GetAutostartDir() / strprintf("bitcoin-%s.lnk", chain);
643 }
644 
646 {
647  fsbridge::ifstream optionFile(GetAutostartFilePath());
648  if (!optionFile.good())
649  return false;
650  // Scan through file for "Hidden=true":
651  std::string line;
652  while (!optionFile.eof())
653  {
654  getline(optionFile, line);
655  if (line.find("Hidden") != std::string::npos &&
656  line.find("true") != std::string::npos)
657  return false;
658  }
659  optionFile.close();
660 
661  return true;
662 }
663 
664 bool SetStartOnSystemStartup(bool fAutoStart)
665 {
666  if (!fAutoStart)
667  fs::remove(GetAutostartFilePath());
668  else
669  {
670  char pszExePath[MAX_PATH+1];
671  ssize_t r = readlink("/proc/self/exe", pszExePath, sizeof(pszExePath) - 1);
672  if (r == -1)
673  return false;
674  pszExePath[r] = '\0';
675 
676  fs::create_directories(GetAutostartDir());
677 
678  fsbridge::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out | std::ios_base::trunc);
679  if (!optionFile.good())
680  return false;
681  std::string chain = gArgs.GetChainName();
682  // Write a bitcoin.desktop file to the autostart directory:
683  optionFile << "[Desktop Entry]\n";
684  optionFile << "Type=Application\n";
685  if (chain == CBaseChainParams::MAIN)
686  optionFile << "Name=Bitcoin\n";
687  else
688  optionFile << strprintf("Name=Bitcoin (%s)\n", chain);
689  optionFile << "Exec=" << pszExePath << strprintf(" -min -testnet=%d -regtest=%d\n", gArgs.GetBoolArg("-testnet", false), gArgs.GetBoolArg("-regtest", false));
690  optionFile << "Terminal=false\n";
691  optionFile << "Hidden=false\n";
692  optionFile.close();
693  }
694  return true;
695 }
696 
697 
698 #elif defined(Q_OS_MAC) && defined(MAC_OS_X_VERSION_MIN_REQUIRED) && MAC_OS_X_VERSION_MIN_REQUIRED <= 101100
699 // based on: https://github.com/Mozketo/LaunchAtLoginController/blob/master/LaunchAtLoginController.m
700 
701 LSSharedFileListItemRef findStartupItemInList(CFArrayRef listSnapshot, LSSharedFileListRef list, CFURLRef findUrl)
702 {
703  if (listSnapshot == nullptr) {
704  return nullptr;
705  }
706 
707  // loop through the list of startup items and try to find the bitcoin app
708  for(int i = 0; i < CFArrayGetCount(listSnapshot); i++) {
709  LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i);
710  UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes;
711  CFURLRef currentItemURL = nullptr;
712 
713 #if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED >= 10100
714  if(&LSSharedFileListItemCopyResolvedURL)
715  currentItemURL = LSSharedFileListItemCopyResolvedURL(item, resolutionFlags, nullptr);
716 #if defined(MAC_OS_X_VERSION_MIN_REQUIRED) && MAC_OS_X_VERSION_MIN_REQUIRED < 10100
717  else
718  LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, nullptr);
719 #endif
720 #else
721  LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, nullptr);
722 #endif
723 
724  if(currentItemURL) {
725  if (CFEqual(currentItemURL, findUrl)) {
726  // found
727  CFRelease(currentItemURL);
728  return item;
729  }
730  CFRelease(currentItemURL);
731  }
732  }
733  return nullptr;
734 }
735 
737 {
738  CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
739  if (bitcoinAppUrl == nullptr) {
740  return false;
741  }
742 
743  LSSharedFileListRef loginItems = LSSharedFileListCreate(nullptr, kLSSharedFileListSessionLoginItems, nullptr);
744  CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(loginItems, nullptr);
745  bool res = (findStartupItemInList(listSnapshot, loginItems, bitcoinAppUrl) != nullptr);
746  CFRelease(bitcoinAppUrl);
747  CFRelease(loginItems);
748  CFRelease(listSnapshot);
749  return res;
750 }
751 
752 bool SetStartOnSystemStartup(bool fAutoStart)
753 {
754  CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
755  if (bitcoinAppUrl == nullptr) {
756  return false;
757  }
758 
759  LSSharedFileListRef loginItems = LSSharedFileListCreate(nullptr, kLSSharedFileListSessionLoginItems, nullptr);
760  CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(loginItems, nullptr);
761  LSSharedFileListItemRef foundItem = findStartupItemInList(listSnapshot, loginItems, bitcoinAppUrl);
762 
763  if(fAutoStart && !foundItem) {
764  // add bitcoin app to startup item list
765  LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, nullptr, nullptr, bitcoinAppUrl, nullptr, nullptr);
766  }
767  else if(!fAutoStart && foundItem) {
768  // remove item
769  LSSharedFileListItemRemove(loginItems, foundItem);
770  }
771 
772  CFRelease(bitcoinAppUrl);
773  CFRelease(loginItems);
774  CFRelease(listSnapshot);
775  return true;
776 }
777 #pragma GCC diagnostic pop
778 #else
779 
780 bool GetStartOnSystemStartup() { return false; }
781 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
782 
783 #endif
784 
785 void setClipboard(const QString& str)
786 {
787  QApplication::clipboard()->setText(str, QClipboard::Clipboard);
788  QApplication::clipboard()->setText(str, QClipboard::Selection);
789 }
790 
791 fs::path qstringToBoostPath(const QString &path)
792 {
793  return fs::path(path.toStdString());
794 }
795 
796 QString boostPathToQString(const fs::path &path)
797 {
798  return QString::fromStdString(path.string());
799 }
800 
801 QString formatDurationStr(int secs)
802 {
803  QStringList strList;
804  int days = secs / 86400;
805  int hours = (secs % 86400) / 3600;
806  int mins = (secs % 3600) / 60;
807  int seconds = secs % 60;
808 
809  if (days)
810  strList.append(QString(QObject::tr("%1 d")).arg(days));
811  if (hours)
812  strList.append(QString(QObject::tr("%1 h")).arg(hours));
813  if (mins)
814  strList.append(QString(QObject::tr("%1 m")).arg(mins));
815  if (seconds || (!days && !hours && !mins))
816  strList.append(QString(QObject::tr("%1 s")).arg(seconds));
817 
818  return strList.join(" ");
819 }
820 
821 QString formatServicesStr(quint64 mask)
822 {
823  QStringList strList;
824 
825  // Just scan the last 8 bits for now.
826  for (int i = 0; i < 8; i++) {
827  uint64_t check = 1 << i;
828  if (mask & check)
829  {
830  switch (check)
831  {
832  case NODE_NETWORK:
833  strList.append("NETWORK");
834  break;
835  case NODE_GETUTXO:
836  strList.append("GETUTXO");
837  break;
838  case NODE_BLOOM:
839  strList.append("BLOOM");
840  break;
841  case NODE_WITNESS:
842  strList.append("WITNESS");
843  break;
844  case NODE_XTHIN:
845  strList.append("XTHIN");
846  break;
847  default:
848  strList.append(QString("%1[%2]").arg("UNKNOWN").arg(check));
849  }
850  }
851  }
852 
853  if (strList.size())
854  return strList.join(" & ");
855  else
856  return QObject::tr("None");
857 }
858 
859 QString formatPingTime(double dPingTime)
860 {
861  return (dPingTime == std::numeric_limits<int64_t>::max()/1e6 || dPingTime == 0) ? QObject::tr("N/A") : QString(QObject::tr("%1 ms")).arg(QString::number((int)(dPingTime * 1000), 10));
862 }
863 
864 QString formatTimeOffset(int64_t nTimeOffset)
865 {
866  return QString(QObject::tr("%1 s")).arg(QString::number((int)nTimeOffset, 10));
867 }
868 
869 QString formatNiceTimeOffset(qint64 secs)
870 {
871  // Represent time from last generated block in human readable text
872  QString timeBehindText;
873  const int HOUR_IN_SECONDS = 60*60;
874  const int DAY_IN_SECONDS = 24*60*60;
875  const int WEEK_IN_SECONDS = 7*24*60*60;
876  const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar
877  if(secs < 60)
878  {
879  timeBehindText = QObject::tr("%n second(s)","",secs);
880  }
881  else if(secs < 2*HOUR_IN_SECONDS)
882  {
883  timeBehindText = QObject::tr("%n minute(s)","",secs/60);
884  }
885  else if(secs < 2*DAY_IN_SECONDS)
886  {
887  timeBehindText = QObject::tr("%n hour(s)","",secs/HOUR_IN_SECONDS);
888  }
889  else if(secs < 2*WEEK_IN_SECONDS)
890  {
891  timeBehindText = QObject::tr("%n day(s)","",secs/DAY_IN_SECONDS);
892  }
893  else if(secs < YEAR_IN_SECONDS)
894  {
895  timeBehindText = QObject::tr("%n week(s)","",secs/WEEK_IN_SECONDS);
896  }
897  else
898  {
899  qint64 years = secs / YEAR_IN_SECONDS;
900  qint64 remainder = secs % YEAR_IN_SECONDS;
901  timeBehindText = QObject::tr("%1 and %2").arg(QObject::tr("%n year(s)", "", years)).arg(QObject::tr("%n week(s)","", remainder/WEEK_IN_SECONDS));
902  }
903  return timeBehindText;
904 }
905 
906 QString formatBytes(uint64_t bytes)
907 {
908  if(bytes < 1024)
909  return QString(QObject::tr("%1 B")).arg(bytes);
910  if(bytes < 1024 * 1024)
911  return QString(QObject::tr("%1 KB")).arg(bytes / 1024);
912  if(bytes < 1024 * 1024 * 1024)
913  return QString(QObject::tr("%1 MB")).arg(bytes / 1024 / 1024);
914 
915  return QString(QObject::tr("%1 GB")).arg(bytes / 1024 / 1024 / 1024);
916 }
917 
918 qreal calculateIdealFontSize(int width, const QString& text, QFont font, qreal minPointSize, qreal font_size) {
919  while(font_size >= minPointSize) {
920  font.setPointSizeF(font_size);
921  QFontMetrics fm(font);
922  if (fm.width(text) < width) {
923  break;
924  }
925  font_size -= 0.5;
926  }
927  return font_size;
928 }
929 
930 void ClickableLabel::mouseReleaseEvent(QMouseEvent *event)
931 {
932  Q_EMIT clicked(event->pos());
933 }
934 
936 {
937  Q_EMIT clicked(event->pos());
938 }
939 
940 bool ItemDelegate::eventFilter(QObject *object, QEvent *event)
941 {
942  if (event->type() == QEvent::KeyPress) {
943  if (static_cast<QKeyEvent*>(event)->key() == Qt::Key_Escape) {
944  Q_EMIT keyEscapePressed();
945  }
946  }
947  return QItemDelegate::eventFilter(object, event);
948 }
949 
950 void PolishProgressDialog(QProgressDialog* dialog)
951 {
952 #ifdef Q_OS_MAC
953  // Workaround for macOS-only Qt bug; see: QTBUG-65750, QTBUG-70357.
954  const int margin = dialog->fontMetrics().width("X");
955  dialog->resize(dialog->width() + 2 * margin, dialog->height());
956  dialog->show();
957 #else
958  Q_UNUSED(dialog);
959 #endif
960 }
961 
962 } // namespace GUIUtil
void openDebugLogfile()
Definition: guiutil.cpp:381
ToolTipToRichTextFilter(int size_threshold, QObject *parent=nullptr)
Definition: guiutil.cpp:414
QFont fixedPitchFont()
Definition: guiutil.cpp:78
Utility functions used by the Bitcoin Qt UI.
Definition: bitcoingui.h:55
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:301
QList< QModelIndex > getEntryData(QAbstractItemView *view, int column)
Return a field of the currently selected entry as a QString.
Definition: guiutil.cpp:243
fs::path GetDefaultDataDir()
Definition: system.cpp:679
void setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode)
Definition: guiutil.cpp:454
bool IsValidDestinationString(const std::string &str, const CChainParams &params)
Definition: key_io.cpp:221
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1067
bool isDust(interfaces::Node &node, const QString &address, const CAmount &amount)
Definition: guiutil.cpp:207
fs::ifstream ifstream
Definition: fs.h:91
#define MAX_PATH
Definition: compat.h:69
QString dateTimeStr(const QDateTime &date)
Definition: guiutil.cpp:68
std::string EncodeBase58(const unsigned char *pbegin, const unsigned char *pend)
Why base-58 instead of standard base-64 encoding?
Definition: base58.cpp:84
Qt::ConnectionType blockingGUIThreadConnection()
Get connection type to call object slot in GUI thread with invokeMethod.
Definition: guiutil.cpp:332
QString formatBytes(uint64_t bytes)
Definition: guiutil.cpp:906
QString formatTimeOffset(int64_t nTimeOffset)
Definition: guiutil.cpp:864
bool GetStartOnSystemStartup()
Definition: guiutil.cpp:780
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:215
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:510
Line edit that can be marked as "invalid" to show input validation feedback.
fs::ofstream ofstream
Definition: fs.h:92
const char *const BITCOIN_CONF_FILENAME
Definition: system.cpp:70
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:360
static const std::string MAIN
BIP70 chain name strings (main, test or regtest)
TableViewLastColumnResizingFixer(QTableView *table, int lastColMinimumWidth, int allColsMinimumWidth, QObject *parent)
Initializes all internal variables and prepares the the resize modes of the last 2 columns of the tab...
Definition: guiutil.cpp:539
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent)
Definition: guiutil.cpp:101
bool isObscured(QWidget *w)
Definition: guiutil.cpp:351
bool eventFilter(QObject *obj, QEvent *evt)
Definition: guiutil.cpp:421
qreal calculateIdealFontSize(int width, const QString &text, QFont font, qreal minPointSize, qreal font_size)
Definition: guiutil.cpp:918
QString formatDurationStr(int secs)
Definition: guiutil.cpp:801
void setClipboard(const QString &str)
Definition: guiutil.cpp:785
const fs::path & GetDataDir(bool fNetSpecific)
Definition: system.cpp:735
Base58 entry widget validator, checks for valid characters and removes some whitespace.
An output of a transaction.
Definition: transaction.h:133
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:289
void PolishProgressDialog(QProgressDialog *dialog)
Definition: guiutil.cpp:950
bool eventFilter(QObject *object, QEvent *event)
Definition: guiutil.cpp:940
QString formatPingTime(double dPingTime)
Definition: guiutil.cpp:859
void on_sectionResized(int logicalIndex, int oldSize, int newSize)
Definition: guiutil.cpp:513
void mouseReleaseEvent(QMouseEvent *event)
Definition: guiutil.cpp:930
CTxDestination DecodeDestination(const std::string &str)
Definition: key_io.cpp:216
bool openBitcoinConf()
Definition: guiutil.cpp:390
void mouseReleaseEvent(QMouseEvent *event)
Definition: guiutil.cpp:935
fs::path GetConfigFile(const std::string &confPath)
Definition: system.cpp:773
fs::path qstringToBoostPath(const QString &path)
Definition: guiutil.cpp:791
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:821
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:255
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:494
bool checkPoint(const QPoint &p, const QWidget *w)
Definition: guiutil.cpp:344
ArgsManager gArgs
Definition: system.cpp:72
Succeeded.
Definition: netbase.cpp:206
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
Looks for -regtest, -testnet and returns the appropriate BIP70 chain name.
Definition: system.cpp:944
bool SetStartOnSystemStartup(bool fAutoStart)
Definition: guiutil.cpp:781
QString formatNiceTimeOffset(qint64 secs)
Definition: guiutil.cpp:869
boost::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:139
void copyEntryData(QAbstractItemView *view, int column, int role)
Copy a field of the currently selected entry of a view to the clipboard.
Definition: guiutil.cpp:230
QString getDefaultDataDirectory()
Determine default data directory for operating system.
Definition: guiutil.cpp:250
QString boostPathToQString(const fs::path &path)
Definition: guiutil.cpp:796
Bitcoin address widget validator, checks for a valid bitcoin address.
Top-level interface for a bitcoin node (bitcoind process).
Definition: node.h:36
static const uint8_t dummydata[]
Definition: guiutil.cpp:84
void resizeColumn(int nColumnIndex, int width)
Definition: guiutil.cpp:459
static QString format(int unit, const CAmount &amount, bool plussign=false, SeparatorStyle separators=separatorStandard)
Format as string.
const std::vector< unsigned char > & Base58Prefix(Base58Type type) const
Definition: chainparams.h:82