Fix constness of ArgsManager methods
[bitcoinplatinum.git] / src / qt / guiutil.cpp
blobbffa81137b230c5e2fb5292b53d41b776e1494c1
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.
5 #include "guiutil.h"
7 #include "bitcoinaddressvalidator.h"
8 #include "bitcoinunits.h"
9 #include "qvalidatedlineedit.h"
10 #include "walletmodel.h"
12 #include "fs.h"
13 #include "primitives/transaction.h"
14 #include "init.h"
15 #include "policy/policy.h"
16 #include "protocol.h"
17 #include "script/script.h"
18 #include "script/standard.h"
19 #include "util.h"
21 #ifdef WIN32
22 #ifdef _WIN32_WINNT
23 #undef _WIN32_WINNT
24 #endif
25 #define _WIN32_WINNT 0x0501
26 #ifdef _WIN32_IE
27 #undef _WIN32_IE
28 #endif
29 #define _WIN32_IE 0x0501
30 #define WIN32_LEAN_AND_MEAN 1
31 #ifndef NOMINMAX
32 #define NOMINMAX
33 #endif
34 #include "shellapi.h"
35 #include "shlobj.h"
36 #include "shlwapi.h"
37 #endif
39 #include <boost/scoped_array.hpp>
41 #include <QAbstractItemView>
42 #include <QApplication>
43 #include <QClipboard>
44 #include <QDateTime>
45 #include <QDesktopServices>
46 #include <QDesktopWidget>
47 #include <QDoubleValidator>
48 #include <QFileDialog>
49 #include <QFont>
50 #include <QLineEdit>
51 #include <QSettings>
52 #include <QTextDocument> // for Qt::mightBeRichText
53 #include <QThread>
54 #include <QMouseEvent>
56 #if QT_VERSION < 0x050000
57 #include <QUrl>
58 #else
59 #include <QUrlQuery>
60 #endif
62 #if QT_VERSION >= 0x50200
63 #include <QFontDatabase>
64 #endif
66 static fs::detail::utf8_codecvt_facet utf8;
68 #if defined(Q_OS_MAC)
69 extern double NSAppKitVersionNumber;
70 #if !defined(NSAppKitVersionNumber10_8)
71 #define NSAppKitVersionNumber10_8 1187
72 #endif
73 #if !defined(NSAppKitVersionNumber10_9)
74 #define NSAppKitVersionNumber10_9 1265
75 #endif
76 #endif
78 namespace GUIUtil {
80 QString dateTimeStr(const QDateTime &date)
82 return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
85 QString dateTimeStr(qint64 nTime)
87 return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
90 QFont fixedPitchFont()
92 #if QT_VERSION >= 0x50200
93 return QFontDatabase::systemFont(QFontDatabase::FixedFont);
94 #else
95 QFont font("Monospace");
96 #if QT_VERSION >= 0x040800
97 font.setStyleHint(QFont::Monospace);
98 #else
99 font.setStyleHint(QFont::TypeWriter);
100 #endif
101 return font;
102 #endif
105 // Just some dummy data to generate an convincing random-looking (but consistent) address
106 static const uint8_t dummydata[] = {0xeb,0x15,0x23,0x1d,0xfc,0xeb,0x60,0x92,0x58,0x86,0xb6,0x7d,0x06,0x52,0x99,0x92,0x59,0x15,0xae,0xb1,0x72,0xc0,0x66,0x47};
108 // Generate a dummy address with invalid CRC, starting with the network prefix.
109 static std::string DummyAddress(const CChainParams &params)
111 std::vector<unsigned char> sourcedata = params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);
112 sourcedata.insert(sourcedata.end(), dummydata, dummydata + sizeof(dummydata));
113 for(int i=0; i<256; ++i) { // Try every trailing byte
114 std::string s = EncodeBase58(sourcedata.data(), sourcedata.data() + sourcedata.size());
115 if (!CBitcoinAddress(s).IsValid())
116 return s;
117 sourcedata[sourcedata.size()-1] += 1;
119 return "";
122 void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent)
124 parent->setFocusProxy(widget);
126 widget->setFont(fixedPitchFont());
127 #if QT_VERSION >= 0x040700
128 // We don't want translators to use own addresses in translations
129 // and this is the only place, where this address is supplied.
130 widget->setPlaceholderText(QObject::tr("Enter a Bitcoin address (e.g. %1)").arg(
131 QString::fromStdString(DummyAddress(Params()))));
132 #endif
133 widget->setValidator(new BitcoinAddressEntryValidator(parent));
134 widget->setCheckValidator(new BitcoinAddressCheckValidator(parent));
137 void setupAmountWidget(QLineEdit *widget, QWidget *parent)
139 QDoubleValidator *amountValidator = new QDoubleValidator(parent);
140 amountValidator->setDecimals(8);
141 amountValidator->setBottom(0.0);
142 widget->setValidator(amountValidator);
143 widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
146 bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
148 // return if URI is not valid or is no bitcoin: URI
149 if(!uri.isValid() || uri.scheme() != QString("bitcoin"))
150 return false;
152 SendCoinsRecipient rv;
153 rv.address = uri.path();
154 // Trim any following forward slash which may have been added by the OS
155 if (rv.address.endsWith("/")) {
156 rv.address.truncate(rv.address.length() - 1);
158 rv.amount = 0;
160 #if QT_VERSION < 0x050000
161 QList<QPair<QString, QString> > items = uri.queryItems();
162 #else
163 QUrlQuery uriQuery(uri);
164 QList<QPair<QString, QString> > items = uriQuery.queryItems();
165 #endif
166 for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
168 bool fShouldReturnFalse = false;
169 if (i->first.startsWith("req-"))
171 i->first.remove(0, 4);
172 fShouldReturnFalse = true;
175 if (i->first == "label")
177 rv.label = i->second;
178 fShouldReturnFalse = false;
180 if (i->first == "message")
182 rv.message = i->second;
183 fShouldReturnFalse = false;
185 else if (i->first == "amount")
187 if(!i->second.isEmpty())
189 if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
191 return false;
194 fShouldReturnFalse = false;
197 if (fShouldReturnFalse)
198 return false;
200 if(out)
202 *out = rv;
204 return true;
207 bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
209 // Convert bitcoin:// to bitcoin:
211 // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
212 // which will lower-case it (and thus invalidate the address).
213 if(uri.startsWith("bitcoin://", Qt::CaseInsensitive))
215 uri.replace(0, 10, "bitcoin:");
217 QUrl uriInstance(uri);
218 return parseBitcoinURI(uriInstance, out);
221 QString formatBitcoinURI(const SendCoinsRecipient &info)
223 QString ret = QString("bitcoin:%1").arg(info.address);
224 int paramCount = 0;
226 if (info.amount)
228 ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, info.amount, false, BitcoinUnits::separatorNever));
229 paramCount++;
232 if (!info.label.isEmpty())
234 QString lbl(QUrl::toPercentEncoding(info.label));
235 ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl);
236 paramCount++;
239 if (!info.message.isEmpty())
241 QString msg(QUrl::toPercentEncoding(info.message));
242 ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg);
243 paramCount++;
246 return ret;
249 bool isDust(const QString& address, const CAmount& amount)
251 CTxDestination dest = CBitcoinAddress(address.toStdString()).Get();
252 CScript script = GetScriptForDestination(dest);
253 CTxOut txOut(amount, script);
254 return IsDust(txOut, ::dustRelayFee);
257 QString HtmlEscape(const QString& str, bool fMultiLine)
259 #if QT_VERSION < 0x050000
260 QString escaped = Qt::escape(str);
261 #else
262 QString escaped = str.toHtmlEscaped();
263 #endif
264 if(fMultiLine)
266 escaped = escaped.replace("\n", "<br>\n");
268 return escaped;
271 QString HtmlEscape(const std::string& str, bool fMultiLine)
273 return HtmlEscape(QString::fromStdString(str), fMultiLine);
276 void copyEntryData(QAbstractItemView *view, int column, int role)
278 if(!view || !view->selectionModel())
279 return;
280 QModelIndexList selection = view->selectionModel()->selectedRows(column);
282 if(!selection.isEmpty())
284 // Copy first item
285 setClipboard(selection.at(0).data(role).toString());
289 QList<QModelIndex> getEntryData(QAbstractItemView *view, int column)
291 if(!view || !view->selectionModel())
292 return QList<QModelIndex>();
293 return view->selectionModel()->selectedRows(column);
296 QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir,
297 const QString &filter,
298 QString *selectedSuffixOut)
300 QString selectedFilter;
301 QString myDir;
302 if(dir.isEmpty()) // Default to user documents location
304 #if QT_VERSION < 0x050000
305 myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
306 #else
307 myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
308 #endif
310 else
312 myDir = dir;
314 /* Directly convert path to native OS path separators */
315 QString result = QDir::toNativeSeparators(QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter));
317 /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
318 QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
319 QString selectedSuffix;
320 if(filter_re.exactMatch(selectedFilter))
322 selectedSuffix = filter_re.cap(1);
325 /* Add suffix if needed */
326 QFileInfo info(result);
327 if(!result.isEmpty())
329 if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
331 /* No suffix specified, add selected suffix */
332 if(!result.endsWith("."))
333 result.append(".");
334 result.append(selectedSuffix);
338 /* Return selected suffix if asked to */
339 if(selectedSuffixOut)
341 *selectedSuffixOut = selectedSuffix;
343 return result;
346 QString getOpenFileName(QWidget *parent, const QString &caption, const QString &dir,
347 const QString &filter,
348 QString *selectedSuffixOut)
350 QString selectedFilter;
351 QString myDir;
352 if(dir.isEmpty()) // Default to user documents location
354 #if QT_VERSION < 0x050000
355 myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
356 #else
357 myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
358 #endif
360 else
362 myDir = dir;
364 /* Directly convert path to native OS path separators */
365 QString result = QDir::toNativeSeparators(QFileDialog::getOpenFileName(parent, caption, myDir, filter, &selectedFilter));
367 if(selectedSuffixOut)
369 /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
370 QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
371 QString selectedSuffix;
372 if(filter_re.exactMatch(selectedFilter))
374 selectedSuffix = filter_re.cap(1);
376 *selectedSuffixOut = selectedSuffix;
378 return result;
381 Qt::ConnectionType blockingGUIThreadConnection()
383 if(QThread::currentThread() != qApp->thread())
385 return Qt::BlockingQueuedConnection;
387 else
389 return Qt::DirectConnection;
393 bool checkPoint(const QPoint &p, const QWidget *w)
395 QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p));
396 if (!atW) return false;
397 return atW->topLevelWidget() == w;
400 bool isObscured(QWidget *w)
402 return !(checkPoint(QPoint(0, 0), w)
403 && checkPoint(QPoint(w->width() - 1, 0), w)
404 && checkPoint(QPoint(0, w->height() - 1), w)
405 && checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
406 && checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
409 void openDebugLogfile()
411 fs::path pathDebug = GetDataDir() / "debug.log";
413 /* Open debug.log with the associated application */
414 if (fs::exists(pathDebug))
415 QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathDebug)));
418 bool openBitcoinConf()
420 boost::filesystem::path pathConfig = GetConfigFile(BITCOIN_CONF_FILENAME);
422 /* Create the file */
423 boost::filesystem::ofstream configFile(pathConfig, std::ios_base::app);
425 if (!configFile.good())
426 return false;
428 configFile.close();
430 /* Open bitcoin.conf with the associated application */
431 return QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathConfig)));
434 void SubstituteFonts(const QString& language)
436 #if defined(Q_OS_MAC)
437 // Background:
438 // OSX's default font changed in 10.9 and Qt is unable to find it with its
439 // usual fallback methods when building against the 10.7 sdk or lower.
440 // The 10.8 SDK added a function to let it find the correct fallback font.
441 // If this fallback is not properly loaded, some characters may fail to
442 // render correctly.
444 // The same thing happened with 10.10. .Helvetica Neue DeskInterface is now default.
446 // Solution: If building with the 10.7 SDK or lower and the user's platform
447 // is 10.9 or higher at runtime, substitute the correct font. This needs to
448 // happen before the QApplication is created.
449 #if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_8
450 if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_8)
452 if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_9)
453 /* On a 10.9 - 10.9.x system */
454 QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande");
455 else
457 /* 10.10 or later system */
458 if (language == "zh_CN" || language == "zh_TW" || language == "zh_HK") // traditional or simplified Chinese
459 QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Heiti SC");
460 else if (language == "ja") // Japanese
461 QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Songti SC");
462 else
463 QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Lucida Grande");
466 #endif
467 #endif
470 ToolTipToRichTextFilter::ToolTipToRichTextFilter(int _size_threshold, QObject *parent) :
471 QObject(parent),
472 size_threshold(_size_threshold)
477 bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
479 if(evt->type() == QEvent::ToolTipChange)
481 QWidget *widget = static_cast<QWidget*>(obj);
482 QString tooltip = widget->toolTip();
483 if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt") && !Qt::mightBeRichText(tooltip))
485 // Envelop with <qt></qt> to make sure Qt detects this as rich text
486 // Escape the current message as HTML and replace \n by <br>
487 tooltip = "<qt>" + HtmlEscape(tooltip, true) + "</qt>";
488 widget->setToolTip(tooltip);
489 return true;
492 return QObject::eventFilter(obj, evt);
495 void TableViewLastColumnResizingFixer::connectViewHeadersSignals()
497 connect(tableView->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(on_sectionResized(int,int,int)));
498 connect(tableView->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged()));
501 // We need to disconnect these while handling the resize events, otherwise we can enter infinite loops.
502 void TableViewLastColumnResizingFixer::disconnectViewHeadersSignals()
504 disconnect(tableView->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(on_sectionResized(int,int,int)));
505 disconnect(tableView->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged()));
508 // Setup the resize mode, handles compatibility for Qt5 and below as the method signatures changed.
509 // Refactored here for readability.
510 void TableViewLastColumnResizingFixer::setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode)
512 #if QT_VERSION < 0x050000
513 tableView->horizontalHeader()->setResizeMode(logicalIndex, resizeMode);
514 #else
515 tableView->horizontalHeader()->setSectionResizeMode(logicalIndex, resizeMode);
516 #endif
519 void TableViewLastColumnResizingFixer::resizeColumn(int nColumnIndex, int width)
521 tableView->setColumnWidth(nColumnIndex, width);
522 tableView->horizontalHeader()->resizeSection(nColumnIndex, width);
525 int TableViewLastColumnResizingFixer::getColumnsWidth()
527 int nColumnsWidthSum = 0;
528 for (int i = 0; i < columnCount; i++)
530 nColumnsWidthSum += tableView->horizontalHeader()->sectionSize(i);
532 return nColumnsWidthSum;
535 int TableViewLastColumnResizingFixer::getAvailableWidthForColumn(int column)
537 int nResult = lastColumnMinimumWidth;
538 int nTableWidth = tableView->horizontalHeader()->width();
540 if (nTableWidth > 0)
542 int nOtherColsWidth = getColumnsWidth() - tableView->horizontalHeader()->sectionSize(column);
543 nResult = std::max(nResult, nTableWidth - nOtherColsWidth);
546 return nResult;
549 // Make sure we don't make the columns wider than the table's viewport width.
550 void TableViewLastColumnResizingFixer::adjustTableColumnsWidth()
552 disconnectViewHeadersSignals();
553 resizeColumn(lastColumnIndex, getAvailableWidthForColumn(lastColumnIndex));
554 connectViewHeadersSignals();
556 int nTableWidth = tableView->horizontalHeader()->width();
557 int nColsWidth = getColumnsWidth();
558 if (nColsWidth > nTableWidth)
560 resizeColumn(secondToLastColumnIndex,getAvailableWidthForColumn(secondToLastColumnIndex));
564 // Make column use all the space available, useful during window resizing.
565 void TableViewLastColumnResizingFixer::stretchColumnWidth(int column)
567 disconnectViewHeadersSignals();
568 resizeColumn(column, getAvailableWidthForColumn(column));
569 connectViewHeadersSignals();
572 // When a section is resized this is a slot-proxy for ajustAmountColumnWidth().
573 void TableViewLastColumnResizingFixer::on_sectionResized(int logicalIndex, int oldSize, int newSize)
575 adjustTableColumnsWidth();
576 int remainingWidth = getAvailableWidthForColumn(logicalIndex);
577 if (newSize > remainingWidth)
579 resizeColumn(logicalIndex, remainingWidth);
583 // When the table's geometry is ready, we manually perform the stretch of the "Message" column,
584 // as the "Stretch" resize mode does not allow for interactive resizing.
585 void TableViewLastColumnResizingFixer::on_geometriesChanged()
587 if ((getColumnsWidth() - this->tableView->horizontalHeader()->width()) != 0)
589 disconnectViewHeadersSignals();
590 resizeColumn(secondToLastColumnIndex, getAvailableWidthForColumn(secondToLastColumnIndex));
591 connectViewHeadersSignals();
596 * Initializes all internal variables and prepares the
597 * the resize modes of the last 2 columns of the table and
599 TableViewLastColumnResizingFixer::TableViewLastColumnResizingFixer(QTableView* table, int lastColMinimumWidth, int allColsMinimumWidth, QObject *parent) :
600 QObject(parent),
601 tableView(table),
602 lastColumnMinimumWidth(lastColMinimumWidth),
603 allColumnsMinimumWidth(allColsMinimumWidth)
605 columnCount = tableView->horizontalHeader()->count();
606 lastColumnIndex = columnCount - 1;
607 secondToLastColumnIndex = columnCount - 2;
608 tableView->horizontalHeader()->setMinimumSectionSize(allColumnsMinimumWidth);
609 setViewHeaderResizeMode(secondToLastColumnIndex, QHeaderView::Interactive);
610 setViewHeaderResizeMode(lastColumnIndex, QHeaderView::Interactive);
613 #ifdef WIN32
614 fs::path static StartupShortcutPath()
616 std::string chain = ChainNameFromCommandLine();
617 if (chain == CBaseChainParams::MAIN)
618 return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin.lnk";
619 if (chain == CBaseChainParams::TESTNET) // Remove this special case when CBaseChainParams::TESTNET = "testnet4"
620 return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin (testnet).lnk";
621 return GetSpecialFolderPath(CSIDL_STARTUP) / strprintf("Bitcoin (%s).lnk", chain);
624 bool GetStartOnSystemStartup()
626 // check for Bitcoin*.lnk
627 return fs::exists(StartupShortcutPath());
630 bool SetStartOnSystemStartup(bool fAutoStart)
632 // If the shortcut exists already, remove it for updating
633 fs::remove(StartupShortcutPath());
635 if (fAutoStart)
637 CoInitialize(NULL);
639 // Get a pointer to the IShellLink interface.
640 IShellLink* psl = NULL;
641 HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
642 CLSCTX_INPROC_SERVER, IID_IShellLink,
643 reinterpret_cast<void**>(&psl));
645 if (SUCCEEDED(hres))
647 // Get the current executable path
648 TCHAR pszExePath[MAX_PATH];
649 GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
651 // Start client minimized
652 QString strArgs = "-min";
653 // Set -testnet /-regtest options
654 strArgs += QString::fromStdString(strprintf(" -testnet=%d -regtest=%d", GetBoolArg("-testnet", false), GetBoolArg("-regtest", false)));
656 #ifdef UNICODE
657 boost::scoped_array<TCHAR> args(new TCHAR[strArgs.length() + 1]);
658 // Convert the QString to TCHAR*
659 strArgs.toWCharArray(args.get());
660 // Add missing '\0'-termination to string
661 args[strArgs.length()] = '\0';
662 #endif
664 // Set the path to the shortcut target
665 psl->SetPath(pszExePath);
666 PathRemoveFileSpec(pszExePath);
667 psl->SetWorkingDirectory(pszExePath);
668 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
669 #ifndef UNICODE
670 psl->SetArguments(strArgs.toStdString().c_str());
671 #else
672 psl->SetArguments(args.get());
673 #endif
675 // Query IShellLink for the IPersistFile interface for
676 // saving the shortcut in persistent storage.
677 IPersistFile* ppf = NULL;
678 hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf));
679 if (SUCCEEDED(hres))
681 WCHAR pwsz[MAX_PATH];
682 // Ensure that the string is ANSI.
683 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
684 // Save the link by calling IPersistFile::Save.
685 hres = ppf->Save(pwsz, TRUE);
686 ppf->Release();
687 psl->Release();
688 CoUninitialize();
689 return true;
691 psl->Release();
693 CoUninitialize();
694 return false;
696 return true;
698 #elif defined(Q_OS_LINUX)
700 // Follow the Desktop Application Autostart Spec:
701 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
703 fs::path static GetAutostartDir()
705 char* pszConfigHome = getenv("XDG_CONFIG_HOME");
706 if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
707 char* pszHome = getenv("HOME");
708 if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
709 return fs::path();
712 fs::path static GetAutostartFilePath()
714 std::string chain = ChainNameFromCommandLine();
715 if (chain == CBaseChainParams::MAIN)
716 return GetAutostartDir() / "bitcoin.desktop";
717 return GetAutostartDir() / strprintf("bitcoin-%s.lnk", chain);
720 bool GetStartOnSystemStartup()
722 fs::ifstream optionFile(GetAutostartFilePath());
723 if (!optionFile.good())
724 return false;
725 // Scan through file for "Hidden=true":
726 std::string line;
727 while (!optionFile.eof())
729 getline(optionFile, line);
730 if (line.find("Hidden") != std::string::npos &&
731 line.find("true") != std::string::npos)
732 return false;
734 optionFile.close();
736 return true;
739 bool SetStartOnSystemStartup(bool fAutoStart)
741 if (!fAutoStart)
742 fs::remove(GetAutostartFilePath());
743 else
745 char pszExePath[MAX_PATH+1];
746 memset(pszExePath, 0, sizeof(pszExePath));
747 if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
748 return false;
750 fs::create_directories(GetAutostartDir());
752 fs::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
753 if (!optionFile.good())
754 return false;
755 std::string chain = ChainNameFromCommandLine();
756 // Write a bitcoin.desktop file to the autostart directory:
757 optionFile << "[Desktop Entry]\n";
758 optionFile << "Type=Application\n";
759 if (chain == CBaseChainParams::MAIN)
760 optionFile << "Name=Bitcoin\n";
761 else
762 optionFile << strprintf("Name=Bitcoin (%s)\n", chain);
763 optionFile << "Exec=" << pszExePath << strprintf(" -min -testnet=%d -regtest=%d\n", GetBoolArg("-testnet", false), GetBoolArg("-regtest", false));
764 optionFile << "Terminal=false\n";
765 optionFile << "Hidden=false\n";
766 optionFile.close();
768 return true;
772 #elif defined(Q_OS_MAC)
773 #pragma GCC diagnostic push
774 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
775 // based on: https://github.com/Mozketo/LaunchAtLoginController/blob/master/LaunchAtLoginController.m
777 #include <CoreFoundation/CoreFoundation.h>
778 #include <CoreServices/CoreServices.h>
780 LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl);
781 LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl)
783 // loop through the list of startup items and try to find the bitcoin app
784 CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, NULL);
785 for(int i = 0; i < CFArrayGetCount(listSnapshot); i++) {
786 LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i);
787 UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes;
788 CFURLRef currentItemURL = NULL;
790 #if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED >= 10100
791 if(&LSSharedFileListItemCopyResolvedURL)
792 currentItemURL = LSSharedFileListItemCopyResolvedURL(item, resolutionFlags, NULL);
793 #if defined(MAC_OS_X_VERSION_MIN_REQUIRED) && MAC_OS_X_VERSION_MIN_REQUIRED < 10100
794 else
795 LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, NULL);
796 #endif
797 #else
798 LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, NULL);
799 #endif
801 if(currentItemURL && CFEqual(currentItemURL, findUrl)) {
802 // found
803 CFRelease(currentItemURL);
804 return item;
806 if(currentItemURL) {
807 CFRelease(currentItemURL);
810 return NULL;
813 bool GetStartOnSystemStartup()
815 CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
816 LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
817 LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);
818 return !!foundItem; // return boolified object
821 bool SetStartOnSystemStartup(bool fAutoStart)
823 CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
824 LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
825 LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);
827 if(fAutoStart && !foundItem) {
828 // add bitcoin app to startup item list
829 LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, NULL, NULL, bitcoinAppUrl, NULL, NULL);
831 else if(!fAutoStart && foundItem) {
832 // remove item
833 LSSharedFileListItemRemove(loginItems, foundItem);
835 return true;
837 #pragma GCC diagnostic pop
838 #else
840 bool GetStartOnSystemStartup() { return false; }
841 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
843 #endif
845 void saveWindowGeometry(const QString& strSetting, QWidget *parent)
847 QSettings settings;
848 settings.setValue(strSetting + "Pos", parent->pos());
849 settings.setValue(strSetting + "Size", parent->size());
852 void restoreWindowGeometry(const QString& strSetting, const QSize& defaultSize, QWidget *parent)
854 QSettings settings;
855 QPoint pos = settings.value(strSetting + "Pos").toPoint();
856 QSize size = settings.value(strSetting + "Size", defaultSize).toSize();
858 parent->resize(size);
859 parent->move(pos);
861 if ((!pos.x() && !pos.y()) || (QApplication::desktop()->screenNumber(parent) == -1))
863 QRect screen = QApplication::desktop()->screenGeometry();
864 QPoint defaultPos((screen.width() - defaultSize.width()) / 2,
865 (screen.height() - defaultSize.height()) / 2);
866 parent->resize(defaultSize);
867 parent->move(defaultPos);
871 void setClipboard(const QString& str)
873 QApplication::clipboard()->setText(str, QClipboard::Clipboard);
874 QApplication::clipboard()->setText(str, QClipboard::Selection);
877 fs::path qstringToBoostPath(const QString &path)
879 return fs::path(path.toStdString(), utf8);
882 QString boostPathToQString(const fs::path &path)
884 return QString::fromStdString(path.string(utf8));
887 QString formatDurationStr(int secs)
889 QStringList strList;
890 int days = secs / 86400;
891 int hours = (secs % 86400) / 3600;
892 int mins = (secs % 3600) / 60;
893 int seconds = secs % 60;
895 if (days)
896 strList.append(QString(QObject::tr("%1 d")).arg(days));
897 if (hours)
898 strList.append(QString(QObject::tr("%1 h")).arg(hours));
899 if (mins)
900 strList.append(QString(QObject::tr("%1 m")).arg(mins));
901 if (seconds || (!days && !hours && !mins))
902 strList.append(QString(QObject::tr("%1 s")).arg(seconds));
904 return strList.join(" ");
907 QString formatServicesStr(quint64 mask)
909 QStringList strList;
911 // Just scan the last 8 bits for now.
912 for (int i = 0; i < 8; i++) {
913 uint64_t check = 1 << i;
914 if (mask & check)
916 switch (check)
918 case NODE_NETWORK:
919 strList.append("NETWORK");
920 break;
921 case NODE_GETUTXO:
922 strList.append("GETUTXO");
923 break;
924 case NODE_BLOOM:
925 strList.append("BLOOM");
926 break;
927 case NODE_WITNESS:
928 strList.append("WITNESS");
929 break;
930 case NODE_XTHIN:
931 strList.append("XTHIN");
932 break;
933 default:
934 strList.append(QString("%1[%2]").arg("UNKNOWN").arg(check));
939 if (strList.size())
940 return strList.join(" & ");
941 else
942 return QObject::tr("None");
945 QString formatPingTime(double dPingTime)
947 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));
950 QString formatTimeOffset(int64_t nTimeOffset)
952 return QString(QObject::tr("%1 s")).arg(QString::number((int)nTimeOffset, 10));
955 QString formatNiceTimeOffset(qint64 secs)
957 // Represent time from last generated block in human readable text
958 QString timeBehindText;
959 const int HOUR_IN_SECONDS = 60*60;
960 const int DAY_IN_SECONDS = 24*60*60;
961 const int WEEK_IN_SECONDS = 7*24*60*60;
962 const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar
963 if(secs < 60)
965 timeBehindText = QObject::tr("%n second(s)","",secs);
967 else if(secs < 2*HOUR_IN_SECONDS)
969 timeBehindText = QObject::tr("%n minute(s)","",secs/60);
971 else if(secs < 2*DAY_IN_SECONDS)
973 timeBehindText = QObject::tr("%n hour(s)","",secs/HOUR_IN_SECONDS);
975 else if(secs < 2*WEEK_IN_SECONDS)
977 timeBehindText = QObject::tr("%n day(s)","",secs/DAY_IN_SECONDS);
979 else if(secs < YEAR_IN_SECONDS)
981 timeBehindText = QObject::tr("%n week(s)","",secs/WEEK_IN_SECONDS);
983 else
985 qint64 years = secs / YEAR_IN_SECONDS;
986 qint64 remainder = secs % YEAR_IN_SECONDS;
987 timeBehindText = QObject::tr("%1 and %2").arg(QObject::tr("%n year(s)", "", years)).arg(QObject::tr("%n week(s)","", remainder/WEEK_IN_SECONDS));
989 return timeBehindText;
992 void ClickableLabel::mouseReleaseEvent(QMouseEvent *event)
994 Q_EMIT clicked(event->pos());
997 void ClickableProgressBar::mouseReleaseEvent(QMouseEvent *event)
999 Q_EMIT clicked(event->pos());
1002 } // namespace GUIUtil