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