You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

guiutil.cpp 31KB

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