Fabcoin Core  0.16.2
P2P Digital Currency
guiutil.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-2017 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 <guiutil.h>
6 
8 #include <fabcoinunits.h>
9 #include <qvalidatedlineedit.h>
10 #include <walletmodel.h>
11 
12 #include <fs.h>
13 #include <primitives/transaction.h>
14 #include <init.h>
15 #include <policy/policy.h>
16 #include <protocol.h>
17 #include <script/script.h>
18 #include <script/standard.h>
19 #include <util.h>
20 
21 #ifdef WIN32
22 #ifdef _WIN32_WINNT
23 #undef _WIN32_WINNT
24 #endif
25 #define _WIN32_WINNT 0x0501
26 #ifdef _WIN32_IE
27 #undef _WIN32_IE
28 #endif
29 #define _WIN32_IE 0x0501
30 #define WIN32_LEAN_AND_MEAN 1
31 #ifndef NOMINMAX
32 #define NOMINMAX
33 #endif
34 #include <shellapi.h>
35 #include <shlobj.h>
36 #include <shlwapi.h>
37 #endif
38 
39 #include <boost/scoped_array.hpp>
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 <QLineEdit>
51 #include <QSettings>
52 #include <QTextDocument> // for Qt::mightBeRichText
53 #include <QThread>
54 #include <QMouseEvent>
55 
56 #if QT_VERSION < 0x050000
57 #include <QUrl>
58 #else
59 #include <QUrlQuery>
60 #endif
61 
62 #if QT_VERSION >= 0x50200
63 #include <QFontDatabase>
64 #endif
65 
66 static fs::detail::utf8_codecvt_facet utf8;
67 
68 #if defined(Q_OS_MAC)
69 extern double NSAppKitVersionNumber;
70 #if !defined(NSAppKitVersionNumber10_8)
71 #define NSAppKitVersionNumber10_8 1187
72 #endif
73 #if !defined(NSAppKitVersionNumber10_9)
74 #define NSAppKitVersionNumber10_9 1265
75 #endif
76 #endif
77 
78 namespace GUIUtil {
79 
80 QString dateTimeStr(const QDateTime &date)
81 {
82  return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
83 }
84 
85 QString dateTimeStr(qint64 nTime)
86 {
87  return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
88 }
89 
91 {
92 #if QT_VERSION >= 0x50200
93  return QFontDatabase::systemFont(QFontDatabase::FixedFont);
94 #else
95  QFont font("Monospace");
96 #if QT_VERSION >= 0x040800
97  font.setStyleHint(QFont::Monospace);
98 #else
99  font.setStyleHint(QFont::TypeWriter);
100 #endif
101  return font;
102 #endif
103 }
104 
105 // Just some dummy data to generate an convincing random-looking (but consistent) address
106 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};
107 
108 // Generate a dummy address with invalid CRC, starting with the network prefix.
109 static std::string DummyAddress(const CChainParams &params)
110 {
111  std::vector<unsigned char> sourcedata = params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);
112  sourcedata.insert(sourcedata.end(), dummydata, dummydata + sizeof(dummydata));
113  for(int i=0; i<256; ++i) { // Try every trailing byte
114  std::string s = EncodeBase58(sourcedata.data(), sourcedata.data() + sourcedata.size());
115  if (!CFabcoinAddress(s).IsValid())
116  return s;
117  sourcedata[sourcedata.size()-1] += 1;
118  }
119  return "";
120 }
121 
122 void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent)
123 {
124  parent->setFocusProxy(widget);
125 
126  widget->setFont(fixedPitchFont());
127 #if QT_VERSION >= 0x040700
128  // We don't want translators to use own addresses in translations
129  // and this is the only place, where this address is supplied.
130  widget->setPlaceholderText(QObject::tr("Enter a Fabcoin address (e.g. %1)").arg(
131  QString::fromStdString(DummyAddress(Params()))));
132 #endif
133  widget->setValidator(new FabcoinAddressEntryValidator(parent));
134  widget->setCheckValidator(new FabcoinAddressCheckValidator(parent));
135 }
136 
137 void setupAmountWidget(QLineEdit *widget, QWidget *parent)
138 {
139  QDoubleValidator *amountValidator = new QDoubleValidator(parent);
140  amountValidator->setDecimals(8);
141  amountValidator->setBottom(0.0);
142  widget->setValidator(amountValidator);
143  widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
144 }
145 
146 bool parseFabcoinURI(const QUrl &uri, SendCoinsRecipient *out)
147 {
148  // return if URI is not valid or is no fabcoin: URI
149  //if(!uri.isValid() || uri.scheme() != QString("fabcoin"))
150  if(!uri.isValid() || uri.scheme() != QString("fabcoin"))
151  return false;
152 
154  rv.address = uri.path();
155  // Trim any following forward slash which may have been added by the OS
156  if (rv.address.endsWith("/")) {
157  rv.address.truncate(rv.address.length() - 1);
158  }
159  rv.amount = 0;
160 
161 #if QT_VERSION < 0x050000
162  QList<QPair<QString, QString> > items = uri.queryItems();
163 #else
164  QUrlQuery uriQuery(uri);
165  QList<QPair<QString, QString> > items = uriQuery.queryItems();
166 #endif
167  for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
168  {
169  bool fShouldReturnFalse = false;
170  if (i->first.startsWith("req-"))
171  {
172  i->first.remove(0, 4);
173  fShouldReturnFalse = true;
174  }
175 
176  if (i->first == "label")
177  {
178  rv.label = i->second;
179  fShouldReturnFalse = false;
180  }
181  if (i->first == "message")
182  {
183  rv.message = i->second;
184  fShouldReturnFalse = false;
185  }
186  else if (i->first == "amount")
187  {
188  if(!i->second.isEmpty())
189  {
190  if(!FabcoinUnits::parse(FabcoinUnits::FAB, i->second, &rv.amount))
191  {
192  return false;
193  }
194  }
195  fShouldReturnFalse = false;
196  }
197 
198  if (fShouldReturnFalse)
199  return false;
200  }
201  if(out)
202  {
203  *out = rv;
204  }
205  return true;
206 }
207 
208 bool parseFabcoinURI(QString uri, SendCoinsRecipient *out)
209 {
210  // Convert fabcoin:// to fabcoin:
211  //
212  // Cannot handle this later, because fabcoin:// will cause Qt to see the part after // as host,
213  // which will lower-case it (and thus invalidate the address).
214  if(uri.startsWith("fabcoin://", Qt::CaseInsensitive))
215  {
216  uri.replace(0, 10, "fabcoin:");
217  }
218  QUrl uriInstance(uri);
219  return parseFabcoinURI(uriInstance, out);
220 }
221 
223 {
224  QString ret = QString("fabcoin:%1").arg(info.address);
225  int paramCount = 0;
226 
227  if (info.amount)
228  {
229  ret += QString("?amount=%1").arg(FabcoinUnits::format(FabcoinUnits::FAB, info.amount, false, FabcoinUnits::separatorNever));
230  paramCount++;
231  }
232 
233  if (!info.label.isEmpty())
234  {
235  QString lbl(QUrl::toPercentEncoding(info.label));
236  ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl);
237  paramCount++;
238  }
239 
240  if (!info.message.isEmpty())
241  {
242  QString msg(QUrl::toPercentEncoding(info.message));
243  ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg);
244  paramCount++;
245  }
246 
247  return ret;
248 }
249 
250 bool isDust(const QString& address, const CAmount& amount)
251 {
252  CTxDestination dest = CFabcoinAddress(address.toStdString()).Get();
253  CScript script = GetScriptForDestination(dest);
254  CTxOut txOut(amount, script);
255  return IsDust(txOut, ::dustRelayFee);
256 }
257 
258 QString HtmlEscape(const QString& str, bool fMultiLine)
259 {
260 #if QT_VERSION < 0x050000
261  QString escaped = Qt::escape(str);
262 #else
263  QString escaped = str.toHtmlEscaped();
264 #endif
265  if(fMultiLine)
266  {
267  escaped = escaped.replace("\n", "<br>\n");
268  }
269  return escaped;
270 }
271 
272 QString HtmlEscape(const std::string& str, bool fMultiLine)
273 {
274  return HtmlEscape(QString::fromStdString(str), fMultiLine);
275 }
276 
277 void copyEntryData(QAbstractItemView *view, int column, int role)
278 {
279  if(!view || !view->selectionModel())
280  return;
281  QModelIndexList selection = view->selectionModel()->selectedRows(column);
282 
283  if(!selection.isEmpty())
284  {
285  // Copy first item
286  setClipboard(selection.at(0).data(role).toString());
287  }
288 }
289 
290 void copyEntryDataFromList(QAbstractItemView *view, int role)
291 {
292  if(!view || !view->selectionModel())
293  return;
294  QModelIndexList selection = view->selectionModel()->selectedIndexes();
295 
296  if(!selection.isEmpty())
297  {
298  // Copy first item
299  setClipboard(selection.at(0).data(role).toString());
300  }
301 }
302 QList<QModelIndex> getEntryData(QAbstractItemView *view, int column)
303 {
304  if(!view || !view->selectionModel())
305  return QList<QModelIndex>();
306  return view->selectionModel()->selectedRows(column);
307 }
308 
309 QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir,
310  const QString &filter,
311  QString *selectedSuffixOut)
312 {
313  QString selectedFilter;
314  QString myDir;
315  if(dir.isEmpty()) // Default to user documents location
316  {
317 #if QT_VERSION < 0x050000
318  myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
319 #else
320  myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
321 #endif
322  }
323  else
324  {
325  myDir = dir;
326  }
327  /* Directly convert path to native OS path separators */
328  QString result = QDir::toNativeSeparators(QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter));
329 
330  /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
331  QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
332  QString selectedSuffix;
333  if(filter_re.exactMatch(selectedFilter))
334  {
335  selectedSuffix = filter_re.cap(1);
336  }
337 
338  /* Add suffix if needed */
339  QFileInfo info(result);
340  if(!result.isEmpty())
341  {
342  if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
343  {
344  /* No suffix specified, add selected suffix */
345  if(!result.endsWith("."))
346  result.append(".");
347  result.append(selectedSuffix);
348  }
349  }
350 
351  /* Return selected suffix if asked to */
352  if(selectedSuffixOut)
353  {
354  *selectedSuffixOut = selectedSuffix;
355  }
356  return result;
357 }
358 
359 QString getOpenFileName(QWidget *parent, const QString &caption, const QString &dir,
360  const QString &filter,
361  QString *selectedSuffixOut)
362 {
363  QString selectedFilter;
364  QString myDir;
365  if(dir.isEmpty()) // Default to user documents location
366  {
367 #if QT_VERSION < 0x050000
368  myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
369 #else
370  myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
371 #endif
372  }
373  else
374  {
375  myDir = dir;
376  }
377  /* Directly convert path to native OS path separators */
378  QString result = QDir::toNativeSeparators(QFileDialog::getOpenFileName(parent, caption, myDir, filter, &selectedFilter));
379 
380  if(selectedSuffixOut)
381  {
382  /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
383  QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
384  QString selectedSuffix;
385  if(filter_re.exactMatch(selectedFilter))
386  {
387  selectedSuffix = filter_re.cap(1);
388  }
389  *selectedSuffixOut = selectedSuffix;
390  }
391  return result;
392 }
393 
394 Qt::ConnectionType blockingGUIThreadConnection()
395 {
396  if(QThread::currentThread() != qApp->thread())
397  {
398  return Qt::BlockingQueuedConnection;
399  }
400  else
401  {
402  return Qt::DirectConnection;
403  }
404 }
405 
406 bool checkPoint(const QPoint &p, const QWidget *w)
407 {
408  QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p));
409  if (!atW) return false;
410  return atW->topLevelWidget() == w;
411 }
412 
413 bool isObscured(QWidget *w)
414 {
415  return !(checkPoint(QPoint(0, 0), w)
416  && checkPoint(QPoint(w->width() - 1, 0), w)
417  && checkPoint(QPoint(0, w->height() - 1), w)
418  && checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
419  && checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
420 }
421 
423 {
424  fs::path pathDebug = GetDataDir() / "debug.log";
425 
426  /* Open debug.log with the associated application */
427  if (fs::exists(pathDebug))
428  QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathDebug)));
429 }
430 
432 {
433  boost::filesystem::path pathConfig = GetConfigFile(FABCOIN_CONF_FILENAME);
434 
435  /* Create the file */
436  boost::filesystem::ofstream configFile(pathConfig, std::ios_base::app);
437 
438  if (!configFile.good())
439  return false;
440 
441  configFile.close();
442 
443  /* Open fabcoin.conf with the associated application */
444  return QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathConfig)));
445 }
446 
447 void SubstituteFonts(const QString& language)
448 {
449 #if defined(Q_OS_MAC)
450 // Background:
451 // OSX's default font changed in 10.9 and Qt is unable to find it with its
452 // usual fallback methods when building against the 10.7 sdk or lower.
453 // The 10.8 SDK added a function to let it find the correct fallback font.
454 // If this fallback is not properly loaded, some characters may fail to
455 // render correctly.
456 //
457 // The same thing happened with 10.10. .Helvetica Neue DeskInterface is now default.
458 //
459 // Solution: If building with the 10.7 SDK or lower and the user's platform
460 // is 10.9 or higher at runtime, substitute the correct font. This needs to
461 // happen before the QApplication is created.
462 #if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_8
463  if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_8)
464  {
465  if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_9)
466  /* On a 10.9 - 10.9.x system */
467  QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande");
468  else
469  {
470  /* 10.10 or later system */
471  if (language == "zh_CN" || language == "zh_TW" || language == "zh_HK") // traditional or simplified Chinese
472  QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Heiti SC");
473  else if (language == "ja") // Japanese
474  QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Songti SC");
475  else
476  QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Lucida Grande");
477  }
478  }
479 #endif
480 #endif
481 }
482 
483 ToolTipToRichTextFilter::ToolTipToRichTextFilter(int _size_threshold, QObject *parent) :
484  QObject(parent),
485  size_threshold(_size_threshold)
486 {
487 
488 }
489 
490 bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
491 {
492  if(evt->type() == QEvent::ToolTipChange)
493  {
494  QWidget *widget = static_cast<QWidget*>(obj);
495  QString tooltip = widget->toolTip();
496  if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt") && !Qt::mightBeRichText(tooltip))
497  {
498  // Envelop with <qt></qt> to make sure Qt detects this as rich text
499  // Escape the current message as HTML and replace \n by <br>
500  tooltip = "<qt>" + HtmlEscape(tooltip, true) + "</qt>";
501  widget->setToolTip(tooltip);
502  return true;
503  }
504  }
505  return QObject::eventFilter(obj, evt);
506 }
507 
509 {
510  connect(tableView->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(on_sectionResized(int,int,int)));
511  connect(tableView->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged()));
512 }
513 
514 // We need to disconnect these while handling the resize events, otherwise we can enter infinite loops.
516 {
517  disconnect(tableView->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(on_sectionResized(int,int,int)));
518  disconnect(tableView->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged()));
519 }
520 
521 // Setup the resize mode, handles compatibility for Qt5 and below as the method signatures changed.
522 // Refactored here for readability.
523 void TableViewLastColumnResizingFixer::setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode)
524 {
525 #if QT_VERSION < 0x050000
526  tableView->horizontalHeader()->setResizeMode(logicalIndex, resizeMode);
527 #else
528  tableView->horizontalHeader()->setSectionResizeMode(logicalIndex, resizeMode);
529 #endif
530 }
531 
532 void TableViewLastColumnResizingFixer::resizeColumn(int nColumnIndex, int width)
533 {
534  tableView->setColumnWidth(nColumnIndex, width);
535  tableView->horizontalHeader()->resizeSection(nColumnIndex, width);
536 }
537 
539 {
540  int nColumnsWidthSum = 0;
541  for (int i = 0; i < columnCount; i++)
542  {
543  nColumnsWidthSum += tableView->horizontalHeader()->sectionSize(i);
544  }
545  return nColumnsWidthSum;
546 }
547 
549 {
550  int nResult = lastColumnMinimumWidth;
551  int nTableWidth = tableView->horizontalHeader()->width();
552 
553  if (nTableWidth > 0)
554  {
555  int nOtherColsWidth = getColumnsWidth() - tableView->horizontalHeader()->sectionSize(column);
556  nResult = std::max(nResult, nTableWidth - nOtherColsWidth);
557  }
558 
559  return nResult;
560 }
561 
562 // Make sure we don't make the columns wider than the table's viewport width.
564 {
565  disconnectViewHeadersSignals();
566  resizeColumn(lastColumnIndex, getAvailableWidthForColumn(lastColumnIndex));
567  connectViewHeadersSignals();
568 
569  int nTableWidth = tableView->horizontalHeader()->width();
570  int nColsWidth = getColumnsWidth();
571  if (nColsWidth > nTableWidth)
572  {
573  resizeColumn(secondToLastColumnIndex,getAvailableWidthForColumn(secondToLastColumnIndex));
574  }
575 }
576 
577 // Make column use all the space available, useful during window resizing.
579 {
580  disconnectViewHeadersSignals();
581  resizeColumn(column, getAvailableWidthForColumn(column));
582  connectViewHeadersSignals();
583 }
584 
585 // When a section is resized this is a slot-proxy for ajustAmountColumnWidth().
586 void TableViewLastColumnResizingFixer::on_sectionResized(int logicalIndex, int oldSize, int newSize)
587 {
588  adjustTableColumnsWidth();
589  int remainingWidth = getAvailableWidthForColumn(logicalIndex);
590  if (newSize > remainingWidth)
591  {
592  resizeColumn(logicalIndex, remainingWidth);
593  }
594 }
595 
596 // When the table's geometry is ready, we manually perform the stretch of the "Message" column,
597 // as the "Stretch" resize mode does not allow for interactive resizing.
599 {
600  if ((getColumnsWidth() - this->tableView->horizontalHeader()->width()) != 0)
601  {
602  disconnectViewHeadersSignals();
603  resizeColumn(secondToLastColumnIndex, getAvailableWidthForColumn(secondToLastColumnIndex));
604  connectViewHeadersSignals();
605  }
606 }
607 
612 TableViewLastColumnResizingFixer::TableViewLastColumnResizingFixer(QTableView* table, int lastColMinimumWidth, int allColsMinimumWidth, QObject *parent, int columnStretch) :
613  QObject(parent),
614  tableView(table),
615  lastColumnMinimumWidth(lastColMinimumWidth),
616  allColumnsMinimumWidth(allColsMinimumWidth)
617 {
618  columnCount = tableView->horizontalHeader()->count();
620  secondToLastColumnIndex = columnCount - columnStretch;
621  tableView->horizontalHeader()->setMinimumSectionSize(allColumnsMinimumWidth);
622  setViewHeaderResizeMode(secondToLastColumnIndex, QHeaderView::Interactive);
623  setViewHeaderResizeMode(lastColumnIndex, QHeaderView::Interactive);
624 }
625 
626 #ifdef WIN32
627 fs::path static StartupShortcutPath()
628 {
629  std::string chain = ChainNameFromCommandLine();
630  if (chain == CBaseChainParams::MAIN)
631  return GetSpecialFolderPath(CSIDL_STARTUP) / "Fabcoin.lnk";
632  if (chain == CBaseChainParams::TESTNET) // Remove this special case when CBaseChainParams::TESTNET = "testnet4"
633  return GetSpecialFolderPath(CSIDL_STARTUP) / "Fabcoin (testnet).lnk";
634  return GetSpecialFolderPath(CSIDL_STARTUP) / strprintf("Fabcoin (%s).lnk", chain);
635 }
636 
638 {
639  // check for Fabcoin*.lnk
640  return fs::exists(StartupShortcutPath());
641 }
642 
643 bool SetStartOnSystemStartup(bool fAutoStart)
644 {
645  // If the shortcut exists already, remove it for updating
646  fs::remove(StartupShortcutPath());
647 
648  if (fAutoStart)
649  {
650  CoInitialize(nullptr);
651 
652  // Get a pointer to the IShellLink interface.
653  IShellLink* psl = nullptr;
654  HRESULT hres = CoCreateInstance(CLSID_ShellLink, nullptr,
655  CLSCTX_INPROC_SERVER, IID_IShellLink,
656  reinterpret_cast<void**>(&psl));
657 
658  if (SUCCEEDED(hres))
659  {
660  // Get the current executable path
661  TCHAR pszExePath[MAX_PATH];
662  GetModuleFileName(nullptr, pszExePath, sizeof(pszExePath));
663 
664  // Start client minimized
665  QString strArgs = "-min";
666  // Set -testnet /-regtest options
667  strArgs += QString::fromStdString(strprintf(" -testnet=%d -regtest=%d", gArgs.GetBoolArg("-testnet", false), gArgs.GetBoolArg("-regtest", false)));
668 
669 #ifdef UNICODE
670  boost::scoped_array<TCHAR> args(new TCHAR[strArgs.length() + 1]);
671  // Convert the QString to TCHAR*
672  strArgs.toWCharArray(args.get());
673  // Add missing '\0'-termination to string
674  args[strArgs.length()] = '\0';
675 #endif
676 
677  // Set the path to the shortcut target
678  psl->SetPath(pszExePath);
679  PathRemoveFileSpec(pszExePath);
680  psl->SetWorkingDirectory(pszExePath);
681  psl->SetShowCmd(SW_SHOWMINNOACTIVE);
682 #ifndef UNICODE
683  psl->SetArguments(strArgs.toStdString().c_str());
684 #else
685  psl->SetArguments(args.get());
686 #endif
687 
688  // Query IShellLink for the IPersistFile interface for
689  // saving the shortcut in persistent storage.
690  IPersistFile* ppf = nullptr;
691  hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf));
692  if (SUCCEEDED(hres))
693  {
694  WCHAR pwsz[MAX_PATH];
695  // Ensure that the string is ANSI.
696  MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
697  // Save the link by calling IPersistFile::Save.
698  hres = ppf->Save(pwsz, TRUE);
699  ppf->Release();
700  psl->Release();
701  CoUninitialize();
702  return true;
703  }
704  psl->Release();
705  }
706  CoUninitialize();
707  return false;
708  }
709  return true;
710 }
711 #elif defined(Q_OS_LINUX)
712 
713 // Follow the Desktop Application Autostart Spec:
714 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
715 
716 fs::path static GetAutostartDir()
717 {
718  char* pszConfigHome = getenv("XDG_CONFIG_HOME");
719  if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
720  char* pszHome = getenv("HOME");
721  if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
722  return fs::path();
723 }
724 
725 fs::path static GetAutostartFilePath()
726 {
727  std::string chain = ChainNameFromCommandLine();
728  if (chain == CBaseChainParams::MAIN)
729  return GetAutostartDir() / "fabcoin.desktop";
730  return GetAutostartDir() / strprintf("fabcoin-%s.lnk", chain);
731 }
732 
734 {
735  fs::ifstream optionFile(GetAutostartFilePath());
736  if (!optionFile.good())
737  return false;
738  // Scan through file for "Hidden=true":
739  std::string line;
740  while (!optionFile.eof())
741  {
742  getline(optionFile, line);
743  if (line.find("Hidden") != std::string::npos &&
744  line.find("true") != std::string::npos)
745  return false;
746  }
747  optionFile.close();
748 
749  return true;
750 }
751 
752 bool SetStartOnSystemStartup(bool fAutoStart)
753 {
754  if (!fAutoStart)
755  fs::remove(GetAutostartFilePath());
756  else
757  {
758  char pszExePath[MAX_PATH+1];
759  memset(pszExePath, 0, sizeof(pszExePath));
760  if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
761  return false;
762 
763  fs::create_directories(GetAutostartDir());
764 
765  fs::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
766  if (!optionFile.good())
767  return false;
768  std::string chain = ChainNameFromCommandLine();
769  // Write a fabcoin.desktop file to the autostart directory:
770  optionFile << "[Desktop Entry]\n";
771  optionFile << "Type=Application\n";
772  if (chain == CBaseChainParams::MAIN)
773  optionFile << "Name=Fabcoin\n";
774  else
775  optionFile << strprintf("Name=Fabcoin (%s)\n", chain);
776  optionFile << "Exec=" << pszExePath << strprintf(" -min -testnet=%d -regtest=%d\n", gArgs.GetBoolArg("-testnet", false), gArgs.GetBoolArg("-regtest", false));
777  optionFile << "Terminal=false\n";
778  optionFile << "Hidden=false\n";
779  optionFile.close();
780  }
781  return true;
782 }
783 
784 
785 #elif defined(Q_OS_MAC)
786 #pragma GCC diagnostic push
787 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
788 // based on: https://github.com/Mozketo/LaunchAtLoginController/blob/master/LaunchAtLoginController.m
789 
790 #include <CoreFoundation/CoreFoundation.h>
791 #include <CoreServices/CoreServices.h>
792 
793 LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl);
794 LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl)
795 {
796  // loop through the list of startup items and try to find the fabcoin app
797  CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, nullptr);
798  for(int i = 0; i < CFArrayGetCount(listSnapshot); i++) {
799  LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i);
800  UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes;
801  CFURLRef currentItemURL = nullptr;
802 
803 #if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED >= 10100
804  if(&LSSharedFileListItemCopyResolvedURL)
805  currentItemURL = LSSharedFileListItemCopyResolvedURL(item, resolutionFlags, nullptr);
806 #if defined(MAC_OS_X_VERSION_MIN_REQUIRED) && MAC_OS_X_VERSION_MIN_REQUIRED < 10100
807  else
808  LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, nullptr);
809 #endif
810 #else
811  LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, nullptr);
812 #endif
813 
814  if(currentItemURL && CFEqual(currentItemURL, findUrl)) {
815  // found
816  CFRelease(currentItemURL);
817  return item;
818  }
819  if(currentItemURL) {
820  CFRelease(currentItemURL);
821  }
822  }
823  return nullptr;
824 }
825 
827 {
828  CFURLRef fabcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
829  LSSharedFileListRef loginItems = LSSharedFileListCreate(nullptr, kLSSharedFileListSessionLoginItems, nullptr);
830  LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, fabcoinAppUrl);
831  return !!foundItem; // return boolified object
832 }
833 
834 bool SetStartOnSystemStartup(bool fAutoStart)
835 {
836  CFURLRef fabcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
837  LSSharedFileListRef loginItems = LSSharedFileListCreate(nullptr, kLSSharedFileListSessionLoginItems, nullptr);
838  LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, fabcoinAppUrl);
839 
840  if(fAutoStart && !foundItem) {
841  // add fabcoin app to startup item list
842  LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, nullptr, nullptr, fabcoinAppUrl, nullptr, nullptr);
843  }
844  else if(!fAutoStart && foundItem) {
845  // remove item
846  LSSharedFileListItemRemove(loginItems, foundItem);
847  }
848  return true;
849 }
850 #pragma GCC diagnostic pop
851 #else
852 
853 bool GetStartOnSystemStartup() { return false; }
854 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
855 
856 #endif
857 
858 void setClipboard(const QString& str)
859 {
860  QApplication::clipboard()->setText(str, QClipboard::Clipboard);
861  QApplication::clipboard()->setText(str, QClipboard::Selection);
862 }
863 
864 fs::path qstringToBoostPath(const QString &path)
865 {
866  return fs::path(path.toStdString(), utf8);
867 }
868 
869 QString boostPathToQString(const fs::path &path)
870 {
871  return QString::fromStdString(path.string(utf8));
872 }
873 
874 QString formatDurationStr(int secs)
875 {
876  QStringList strList;
877  int days = secs / 86400;
878  int hours = (secs % 86400) / 3600;
879  int mins = (secs % 3600) / 60;
880  int seconds = secs % 60;
881 
882  if (days)
883  strList.append(QString(QObject::tr("%1 d")).arg(days));
884  if (hours)
885  strList.append(QString(QObject::tr("%1 h")).arg(hours));
886  if (mins)
887  strList.append(QString(QObject::tr("%1 m")).arg(mins));
888  if (seconds || (!days && !hours && !mins))
889  strList.append(QString(QObject::tr("%1 s")).arg(seconds));
890 
891  return strList.join(" ");
892 }
893 
894 QString formatServicesStr(quint64 mask)
895 {
896  QStringList strList;
897 
898  // Just scan the last 8 bits for now.
899  for (int i = 0; i < 8; i++) {
900  uint64_t check = 1 << i;
901  if (mask & check)
902  {
903  switch (check)
904  {
905  case NODE_NETWORK:
906  strList.append("NETWORK");
907  break;
908  case NODE_GETUTXO:
909  strList.append("GETUTXO");
910  break;
911  case NODE_BLOOM:
912  strList.append("BLOOM");
913  break;
914  case NODE_WITNESS:
915  strList.append("WITNESS");
916  break;
917  case NODE_XTHIN:
918  strList.append("XTHIN");
919  break;
920  default:
921  strList.append(QString("%1[%2]").arg("UNKNOWN").arg(check));
922  }
923  }
924  }
925 
926  if (strList.size())
927  return strList.join(" & ");
928  else
929  return QObject::tr("None");
930 }
931 
932 QString formatPingTime(double dPingTime)
933 {
934  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));
935 }
936 
937 QString formatTimeOffset(int64_t nTimeOffset)
938 {
939  return QString(QObject::tr("%1 s")).arg(QString::number((int)nTimeOffset, 10));
940 }
941 
942 QString formatNiceTimeOffset(qint64 secs)
943 {
944  // Represent time from last generated block in human readable text
945  QString timeBehindText;
946  const int HOUR_IN_SECONDS = 60*60;
947  const int DAY_IN_SECONDS = 24*60*60;
948  const int WEEK_IN_SECONDS = 7*24*60*60;
949  const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar
950  if(secs < 60)
951  {
952  timeBehindText = QObject::tr("%n second(s)","",secs);
953  }
954  else if(secs < 2*HOUR_IN_SECONDS)
955  {
956  timeBehindText = QObject::tr("%n minute(s)","",secs/60);
957  }
958  else if(secs < 2*DAY_IN_SECONDS)
959  {
960  timeBehindText = QObject::tr("%n hour(s)","",secs/HOUR_IN_SECONDS);
961  }
962  else if(secs < 2*WEEK_IN_SECONDS)
963  {
964  timeBehindText = QObject::tr("%n day(s)","",secs/DAY_IN_SECONDS);
965  }
966  else if(secs < YEAR_IN_SECONDS)
967  {
968  timeBehindText = QObject::tr("%n week(s)","",secs/WEEK_IN_SECONDS);
969  }
970  else
971  {
972  qint64 years = secs / YEAR_IN_SECONDS;
973  qint64 remainder = secs % YEAR_IN_SECONDS;
974  timeBehindText = QObject::tr("%1 and %2").arg(QObject::tr("%n year(s)", "", years)).arg(QObject::tr("%n week(s)","", remainder/WEEK_IN_SECONDS));
975  }
976  return timeBehindText;
977 }
978 
979 void ClickableLabel::mouseReleaseEvent(QMouseEvent *event)
980 {
981  Q_EMIT clicked(event->pos());
982 }
983 
985 {
986  Q_EMIT clicked(event->pos());
987 }
988 
989 void formatToolButtons(QToolButton *btn1, QToolButton *btn2, QToolButton *btn3)
990 {
991  QList<QToolButton *> btnList;
992  if(btn1) btnList.append(btn1);
993  if(btn2) btnList.append(btn2);
994  if(btn3) btnList.append(btn3);
995  for(int i = 0; i < btnList.count(); i++)
996  {
997  QToolButton* btn = btnList[i];
998  btn->setIconSize(QSize(16, 16));
999  }
1000 }
1001 
1002 } // namespace GUIUtil
void SubstituteFonts(const QString &language)
Definition: guiutil.cpp:447
void openDebugLogfile()
Definition: guiutil.cpp:422
bool isDust(const QString &address, const CAmount &amount)
Definition: guiutil.cpp:250
boost::variant< CNoDestination, CKeyID, CScriptID > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:79
QFont fixedPitchFont()
Definition: guiutil.cpp:90
Utility functions used by the Fabcoin Qt UI.
Definition: guiutil.cpp:78
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:359
QList< QModelIndex > getEntryData(QAbstractItemView *view, int column)
Return a field of the currently selected entry as a QString.
Definition: guiutil.cpp:302
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
Definition: guiutil.cpp:137
void setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode)
Definition: guiutil.cpp:523
#define strprintf
Definition: tinyformat.h:1054
base58-encoded Fabcoin addresses.
Definition: base58.h:104
#define MAX_PATH
Definition: compat.h:72
QString dateTimeStr(const QDateTime &date)
Definition: guiutil.cpp:80
std::string EncodeBase58(const unsigned char *pbegin, const unsigned char *pend)
Why base-58 instead of standard base-64 encoding?
Definition: base58.cpp:71
Qt::ConnectionType blockingGUIThreadConnection()
Get connection type to call object slot in GUI thread with invokeMethod.
Definition: guiutil.cpp:394
QString formatTimeOffset(int64_t nTimeOffset)
Definition: guiutil.cpp:937
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
Definition: util.cpp:520
bool GetStartOnSystemStartup()
Definition: guiutil.cpp:853
TableViewLastColumnResizingFixer(QTableView *table, int lastColMinimumWidth, int allColsMinimumWidth, QObject *parent, int columnStretch=2)
Initializes all internal variables and prepares the the resize modes of the last 2 columns of the tab...
Definition: guiutil.cpp:612
ToolTipToRichTextFilter(int size_threshold, QObject *parent=0)
Definition: guiutil.cpp:483
static bool parse(int unit, const QString &value, CAmount *val_out)
Parse string to coin amount.
CChainParams defines various tweakable parameters of a given instance of the Fabcoin system...
Definition: chainparams.h:47
bool IsValid() const
Definition: base58.cpp:247
QString HtmlEscape(const QString &str, bool fMultiLine)
Definition: guiutil.cpp:258
void copyEntryDataFromList(QAbstractItemView *view, int role)
Copy a field of the currently selected entry of a view to the clipboard.
Definition: guiutil.cpp:290
Line edit that can be marked as "invalid" to show input validation feedback.
std::string escaped(std::string const &_s, bool _all=true)
Escapes a string into the C-string representation.
Definition: CommonData.cpp:60
const std::vector< unsigned char > & Base58Prefix(Base58Type type) const
Definition: chainparams.h:80
static const std::string MAIN
BIP70 chain name strings (main, test or regtest)
int64_t CAmount
Amount in lius (Can be negative)
Definition: amount.h:15
void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent)
Definition: guiutil.cpp:122
bool isObscured(QWidget *w)
Definition: guiutil.cpp:413
bool eventFilter(QObject *obj, QEvent *evt)
Definition: guiutil.cpp:490
bool parseFabcoinURI(const QUrl &uri, SendCoinsRecipient *out)
Definition: guiutil.cpp:146
QString formatDurationStr(int secs)
Definition: guiutil.cpp:874
const char *const FABCOIN_CONF_FILENAME
Definition: util.cpp:91
void setClipboard(const QString &str)
Definition: guiutil.cpp:858
ExecStats::duration max
Definition: ExecStats.cpp:36
static QString format(int unit, const CAmount &amount, bool plussign=false, SeparatorStyle separators=separatorStandard)
Format as string.
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)
Definition: standard.cpp:370
QString formatPingTime(double dPingTime)
Definition: guiutil.cpp:932
void on_sectionResized(int logicalIndex, int oldSize, int newSize)
Definition: guiutil.cpp:586
void mouseReleaseEvent(QMouseEvent *event)
Definition: guiutil.cpp:979
ArgsManager gArgs
Definition: util.cpp:94
QString formatFabcoinURI(const SendCoinsRecipient &info)
Definition: guiutil.cpp:222
void mouseReleaseEvent(QMouseEvent *event)
Definition: guiutil.cpp:984
fs::path qstringToBoostPath(const QString &path)
Definition: guiutil.cpp:864
const CChainParams & Params()
Return the currently selected parameters.
fs::path GetConfigFile(const std::string &confPath)
Definition: util.cpp:660
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:417
QString formatServicesStr(quint64 mask)
Definition: guiutil.cpp:894
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:309
bool checkPoint(const QPoint &p, const QWidget *w)
Definition: guiutil.cpp:406
std::string ChainNameFromCommandLine()
Looks for -regtest, -testnet and returns the appropriate BIP70 chain name.
void setCheckValidator(const QValidator *v)
static const std::string TESTNET
bool IsDust(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:52
bool SetStartOnSystemStartup(bool fAutoStart)
Definition: guiutil.cpp:854
const fs::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:623
QString formatNiceTimeOffset(qint64 secs)
Definition: guiutil.cpp:942
dev::WithExisting max(dev::WithExisting _a, dev::WithExisting _b)
Definition: Common.h:326
struct evm_uint160be address(struct evm_env *env)
Definition: capi.c:13
void formatToolButtons(QToolButton *btn1, QToolButton *btn2, QToolButton *btn3)
Definition: guiutil.cpp:989
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:277
QString boostPathToQString(const fs::path &path)
Definition: guiutil.cpp:869
Fabcoin address widget validator, checks for a valid fabcoin address.
void resizeColumn(int nColumnIndex, int width)
Definition: guiutil.cpp:532
bool openFabcoinConf()
Definition: guiutil.cpp:431
CFeeRate dustRelayFee
Definition: policy.cpp:251