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