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

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