PageRenderTime 77ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/src/qt/guiutil.cpp

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