1 // Copyright (c) 2011-2015 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.
7 #include "bitcoinaddressvalidator.h"
8 #include "bitcoinunits.h"
9 #include "qvalidatedlineedit.h"
10 #include "walletmodel.h"
12 #include "primitives/transaction.h"
14 #include "main.h" // For minRelayTxFee
16 #include "script/script.h"
17 #include "script/standard.h"
24 #define _WIN32_WINNT 0x0501
28 #define _WIN32_IE 0x0501
29 #define WIN32_LEAN_AND_MEAN 1
38 #include <boost/filesystem.hpp>
39 #include <boost/filesystem/fstream.hpp>
40 #if BOOST_FILESYSTEM_VERSION >= 3
41 #include <boost/filesystem/detail/utf8_codecvt_facet.hpp>
43 #include <boost/scoped_array.hpp>
45 #include <QAbstractItemView>
46 #include <QApplication>
49 #include <QDesktopServices>
50 #include <QDesktopWidget>
51 #include <QDoubleValidator>
52 #include <QFileDialog>
56 #include <QTextDocument> // for Qt::mightBeRichText
59 #if QT_VERSION < 0x050000
65 #if QT_VERSION >= 0x50200
66 #include <QFontDatabase>
69 #if BOOST_FILESYSTEM_VERSION >= 3
70 static boost::filesystem::detail::utf8_codecvt_facet utf8
;
74 extern double NSAppKitVersionNumber
;
75 #if !defined(NSAppKitVersionNumber10_8)
76 #define NSAppKitVersionNumber10_8 1187
78 #if !defined(NSAppKitVersionNumber10_9)
79 #define NSAppKitVersionNumber10_9 1265
85 QString
dateTimeStr(const QDateTime
&date
)
87 return date
.date().toString(Qt::SystemLocaleShortDate
) + QString(" ") + date
.toString("hh:mm");
90 QString
dateTimeStr(qint64 nTime
)
92 return dateTimeStr(QDateTime::fromTime_t((qint32
)nTime
));
95 QFont
fixedPitchFont()
97 #if QT_VERSION >= 0x50200
98 return QFontDatabase::systemFont(QFontDatabase::FixedFont
);
100 QFont
font("Monospace");
101 #if QT_VERSION >= 0x040800
102 font
.setStyleHint(QFont::Monospace
);
104 font
.setStyleHint(QFont::TypeWriter
);
110 // Just some dummy data to generate an convincing random-looking (but consistent) address
111 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};
113 // Generate a dummy address with invalid CRC, starting with the network prefix.
114 static std::string
DummyAddress(const CChainParams
¶ms
)
116 std::vector
<unsigned char> sourcedata
= params
.Base58Prefix(CChainParams::PUBKEY_ADDRESS
);
117 sourcedata
.insert(sourcedata
.end(), dummydata
, dummydata
+ sizeof(dummydata
));
118 for(int i
=0; i
<256; ++i
) { // Try every trailing byte
119 std::string s
= EncodeBase58(begin_ptr(sourcedata
), end_ptr(sourcedata
));
120 if (!CBitcoinAddress(s
).IsValid())
122 sourcedata
[sourcedata
.size()-1] += 1;
127 void setupAddressWidget(QValidatedLineEdit
*widget
, QWidget
*parent
)
129 parent
->setFocusProxy(widget
);
131 widget
->setFont(fixedPitchFont());
132 #if QT_VERSION >= 0x040700
133 // We don't want translators to use own addresses in translations
134 // and this is the only place, where this address is supplied.
135 widget
->setPlaceholderText(QObject::tr("Enter a Bitcoin address (e.g. %1)").arg(
136 QString::fromStdString(DummyAddress(Params()))));
138 widget
->setValidator(new BitcoinAddressEntryValidator(parent
));
139 widget
->setCheckValidator(new BitcoinAddressCheckValidator(parent
));
142 void setupAmountWidget(QLineEdit
*widget
, QWidget
*parent
)
144 QDoubleValidator
*amountValidator
= new QDoubleValidator(parent
);
145 amountValidator
->setDecimals(8);
146 amountValidator
->setBottom(0.0);
147 widget
->setValidator(amountValidator
);
148 widget
->setAlignment(Qt::AlignRight
|Qt::AlignVCenter
);
151 bool parseBitcoinURI(const QUrl
&uri
, SendCoinsRecipient
*out
)
153 // return if URI is not valid or is no bitcoin: URI
154 if(!uri
.isValid() || uri
.scheme() != QString("bitcoin"))
157 SendCoinsRecipient rv
;
158 rv
.address
= uri
.path();
159 // Trim any following forward slash which may have been added by the OS
160 if (rv
.address
.endsWith("/")) {
161 rv
.address
.truncate(rv
.address
.length() - 1);
165 #if QT_VERSION < 0x050000
166 QList
<QPair
<QString
, QString
> > items
= uri
.queryItems();
168 QUrlQuery
uriQuery(uri
);
169 QList
<QPair
<QString
, QString
> > items
= uriQuery
.queryItems();
171 for (QList
<QPair
<QString
, QString
> >::iterator i
= items
.begin(); i
!= items
.end(); i
++)
173 bool fShouldReturnFalse
= false;
174 if (i
->first
.startsWith("req-"))
176 i
->first
.remove(0, 4);
177 fShouldReturnFalse
= true;
180 if (i
->first
== "label")
182 rv
.label
= i
->second
;
183 fShouldReturnFalse
= false;
185 if (i
->first
== "message")
187 rv
.message
= i
->second
;
188 fShouldReturnFalse
= false;
190 else if (i
->first
== "amount")
192 if(!i
->second
.isEmpty())
194 if(!BitcoinUnits::parse(BitcoinUnits::BTC
, i
->second
, &rv
.amount
))
199 fShouldReturnFalse
= false;
202 if (fShouldReturnFalse
)
212 bool parseBitcoinURI(QString uri
, SendCoinsRecipient
*out
)
214 // Convert bitcoin:// to bitcoin:
216 // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
217 // which will lower-case it (and thus invalidate the address).
218 if(uri
.startsWith("bitcoin://", Qt::CaseInsensitive
))
220 uri
.replace(0, 10, "bitcoin:");
222 QUrl
uriInstance(uri
);
223 return parseBitcoinURI(uriInstance
, out
);
226 QString
formatBitcoinURI(const SendCoinsRecipient
&info
)
228 QString ret
= QString("bitcoin:%1").arg(info
.address
);
233 ret
+= QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC
, info
.amount
, false, BitcoinUnits::separatorNever
));
237 if (!info
.label
.isEmpty())
239 QString
lbl(QUrl::toPercentEncoding(info
.label
));
240 ret
+= QString("%1label=%2").arg(paramCount
== 0 ? "?" : "&").arg(lbl
);
244 if (!info
.message
.isEmpty())
246 QString
msg(QUrl::toPercentEncoding(info
.message
));
247 ret
+= QString("%1message=%2").arg(paramCount
== 0 ? "?" : "&").arg(msg
);
254 bool isDust(const QString
& address
, const CAmount
& amount
)
256 CTxDestination dest
= CBitcoinAddress(address
.toStdString()).Get();
257 CScript script
= GetScriptForDestination(dest
);
258 CTxOut
txOut(amount
, script
);
259 return txOut
.IsDust(::minRelayTxFee
);
262 QString
HtmlEscape(const QString
& str
, bool fMultiLine
)
264 #if QT_VERSION < 0x050000
265 QString escaped
= Qt::escape(str
);
267 QString escaped
= str
.toHtmlEscaped();
271 escaped
= escaped
.replace("\n", "<br>\n");
276 QString
HtmlEscape(const std::string
& str
, bool fMultiLine
)
278 return HtmlEscape(QString::fromStdString(str
), fMultiLine
);
281 void copyEntryData(QAbstractItemView
*view
, int column
, int role
)
283 if(!view
|| !view
->selectionModel())
285 QModelIndexList selection
= view
->selectionModel()->selectedRows(column
);
287 if(!selection
.isEmpty())
290 setClipboard(selection
.at(0).data(role
).toString());
294 QList
<QModelIndex
> getEntryData(QAbstractItemView
*view
, int column
)
296 if(!view
|| !view
->selectionModel())
297 return QList
<QModelIndex
>();
298 return view
->selectionModel()->selectedRows(column
);
301 QString
getSaveFileName(QWidget
*parent
, const QString
&caption
, const QString
&dir
,
302 const QString
&filter
,
303 QString
*selectedSuffixOut
)
305 QString selectedFilter
;
307 if(dir
.isEmpty()) // Default to user documents location
309 #if QT_VERSION < 0x050000
310 myDir
= QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation
);
312 myDir
= QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation
);
319 /* Directly convert path to native OS path separators */
320 QString result
= QDir::toNativeSeparators(QFileDialog::getSaveFileName(parent
, caption
, myDir
, filter
, &selectedFilter
));
322 /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
323 QRegExp
filter_re(".* \\(\\*\\.(.*)[ \\)]");
324 QString selectedSuffix
;
325 if(filter_re
.exactMatch(selectedFilter
))
327 selectedSuffix
= filter_re
.cap(1);
330 /* Add suffix if needed */
331 QFileInfo
info(result
);
332 if(!result
.isEmpty())
334 if(info
.suffix().isEmpty() && !selectedSuffix
.isEmpty())
336 /* No suffix specified, add selected suffix */
337 if(!result
.endsWith("."))
339 result
.append(selectedSuffix
);
343 /* Return selected suffix if asked to */
344 if(selectedSuffixOut
)
346 *selectedSuffixOut
= selectedSuffix
;
351 QString
getOpenFileName(QWidget
*parent
, const QString
&caption
, const QString
&dir
,
352 const QString
&filter
,
353 QString
*selectedSuffixOut
)
355 QString selectedFilter
;
357 if(dir
.isEmpty()) // Default to user documents location
359 #if QT_VERSION < 0x050000
360 myDir
= QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation
);
362 myDir
= QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation
);
369 /* Directly convert path to native OS path separators */
370 QString result
= QDir::toNativeSeparators(QFileDialog::getOpenFileName(parent
, caption
, myDir
, filter
, &selectedFilter
));
372 if(selectedSuffixOut
)
374 /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
375 QRegExp
filter_re(".* \\(\\*\\.(.*)[ \\)]");
376 QString selectedSuffix
;
377 if(filter_re
.exactMatch(selectedFilter
))
379 selectedSuffix
= filter_re
.cap(1);
381 *selectedSuffixOut
= selectedSuffix
;
386 Qt::ConnectionType
blockingGUIThreadConnection()
388 if(QThread::currentThread() != qApp
->thread())
390 return Qt::BlockingQueuedConnection
;
394 return Qt::DirectConnection
;
398 bool checkPoint(const QPoint
&p
, const QWidget
*w
)
400 QWidget
*atW
= QApplication::widgetAt(w
->mapToGlobal(p
));
401 if (!atW
) return false;
402 return atW
->topLevelWidget() == w
;
405 bool isObscured(QWidget
*w
)
407 return !(checkPoint(QPoint(0, 0), w
)
408 && checkPoint(QPoint(w
->width() - 1, 0), w
)
409 && checkPoint(QPoint(0, w
->height() - 1), w
)
410 && checkPoint(QPoint(w
->width() - 1, w
->height() - 1), w
)
411 && checkPoint(QPoint(w
->width() / 2, w
->height() / 2), w
));
414 void openDebugLogfile()
416 boost::filesystem::path pathDebug
= GetDataDir() / "debug.log";
418 /* Open debug.log with the associated application */
419 if (boost::filesystem::exists(pathDebug
))
420 QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathDebug
)));
423 void SubstituteFonts(const QString
& language
)
425 #if defined(Q_OS_MAC)
427 // OSX's default font changed in 10.9 and Qt is unable to find it with its
428 // usual fallback methods when building against the 10.7 sdk or lower.
429 // The 10.8 SDK added a function to let it find the correct fallback font.
430 // If this fallback is not properly loaded, some characters may fail to
433 // The same thing happened with 10.10. .Helvetica Neue DeskInterface is now default.
435 // Solution: If building with the 10.7 SDK or lower and the user's platform
436 // is 10.9 or higher at runtime, substitute the correct font. This needs to
437 // happen before the QApplication is created.
438 #if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_8
439 if (floor(NSAppKitVersionNumber
) > NSAppKitVersionNumber10_8
)
441 if (floor(NSAppKitVersionNumber
) <= NSAppKitVersionNumber10_9
)
442 /* On a 10.9 - 10.9.x system */
443 QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande");
446 /* 10.10 or later system */
447 if (language
== "zh_CN" || language
== "zh_TW" || language
== "zh_HK") // traditional or simplified Chinese
448 QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Heiti SC");
449 else if (language
== "ja") // Japanesee
450 QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Songti SC");
452 QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Lucida Grande");
459 ToolTipToRichTextFilter::ToolTipToRichTextFilter(int _size_threshold
, QObject
*parent
) :
461 size_threshold(_size_threshold
)
466 bool ToolTipToRichTextFilter::eventFilter(QObject
*obj
, QEvent
*evt
)
468 if(evt
->type() == QEvent::ToolTipChange
)
470 QWidget
*widget
= static_cast<QWidget
*>(obj
);
471 QString tooltip
= widget
->toolTip();
472 if(tooltip
.size() > size_threshold
&& !tooltip
.startsWith("<qt") && !Qt::mightBeRichText(tooltip
))
474 // Envelop with <qt></qt> to make sure Qt detects this as rich text
475 // Escape the current message as HTML and replace \n by <br>
476 tooltip
= "<qt>" + HtmlEscape(tooltip
, true) + "</qt>";
477 widget
->setToolTip(tooltip
);
481 return QObject::eventFilter(obj
, evt
);
484 void TableViewLastColumnResizingFixer::connectViewHeadersSignals()
486 connect(tableView
->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(on_sectionResized(int,int,int)));
487 connect(tableView
->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged()));
490 // We need to disconnect these while handling the resize events, otherwise we can enter infinite loops.
491 void TableViewLastColumnResizingFixer::disconnectViewHeadersSignals()
493 disconnect(tableView
->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(on_sectionResized(int,int,int)));
494 disconnect(tableView
->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged()));
497 // Setup the resize mode, handles compatibility for Qt5 and below as the method signatures changed.
498 // Refactored here for readability.
499 void TableViewLastColumnResizingFixer::setViewHeaderResizeMode(int logicalIndex
, QHeaderView::ResizeMode resizeMode
)
501 #if QT_VERSION < 0x050000
502 tableView
->horizontalHeader()->setResizeMode(logicalIndex
, resizeMode
);
504 tableView
->horizontalHeader()->setSectionResizeMode(logicalIndex
, resizeMode
);
508 void TableViewLastColumnResizingFixer::resizeColumn(int nColumnIndex
, int width
)
510 tableView
->setColumnWidth(nColumnIndex
, width
);
511 tableView
->horizontalHeader()->resizeSection(nColumnIndex
, width
);
514 int TableViewLastColumnResizingFixer::getColumnsWidth()
516 int nColumnsWidthSum
= 0;
517 for (int i
= 0; i
< columnCount
; i
++)
519 nColumnsWidthSum
+= tableView
->horizontalHeader()->sectionSize(i
);
521 return nColumnsWidthSum
;
524 int TableViewLastColumnResizingFixer::getAvailableWidthForColumn(int column
)
526 int nResult
= lastColumnMinimumWidth
;
527 int nTableWidth
= tableView
->horizontalHeader()->width();
531 int nOtherColsWidth
= getColumnsWidth() - tableView
->horizontalHeader()->sectionSize(column
);
532 nResult
= std::max(nResult
, nTableWidth
- nOtherColsWidth
);
538 // Make sure we don't make the columns wider than the tables viewport width.
539 void TableViewLastColumnResizingFixer::adjustTableColumnsWidth()
541 disconnectViewHeadersSignals();
542 resizeColumn(lastColumnIndex
, getAvailableWidthForColumn(lastColumnIndex
));
543 connectViewHeadersSignals();
545 int nTableWidth
= tableView
->horizontalHeader()->width();
546 int nColsWidth
= getColumnsWidth();
547 if (nColsWidth
> nTableWidth
)
549 resizeColumn(secondToLastColumnIndex
,getAvailableWidthForColumn(secondToLastColumnIndex
));
553 // Make column use all the space available, useful during window resizing.
554 void TableViewLastColumnResizingFixer::stretchColumnWidth(int column
)
556 disconnectViewHeadersSignals();
557 resizeColumn(column
, getAvailableWidthForColumn(column
));
558 connectViewHeadersSignals();
561 // When a section is resized this is a slot-proxy for ajustAmountColumnWidth().
562 void TableViewLastColumnResizingFixer::on_sectionResized(int logicalIndex
, int oldSize
, int newSize
)
564 adjustTableColumnsWidth();
565 int remainingWidth
= getAvailableWidthForColumn(logicalIndex
);
566 if (newSize
> remainingWidth
)
568 resizeColumn(logicalIndex
, remainingWidth
);
572 // When the tabless geometry is ready, we manually perform the stretch of the "Message" column,
573 // as the "Stretch" resize mode does not allow for interactive resizing.
574 void TableViewLastColumnResizingFixer::on_geometriesChanged()
576 if ((getColumnsWidth() - this->tableView
->horizontalHeader()->width()) != 0)
578 disconnectViewHeadersSignals();
579 resizeColumn(secondToLastColumnIndex
, getAvailableWidthForColumn(secondToLastColumnIndex
));
580 connectViewHeadersSignals();
585 * Initializes all internal variables and prepares the
586 * the resize modes of the last 2 columns of the table and
588 TableViewLastColumnResizingFixer::TableViewLastColumnResizingFixer(QTableView
* table
, int lastColMinimumWidth
, int allColsMinimumWidth
, QObject
*parent
) :
591 lastColumnMinimumWidth(lastColMinimumWidth
),
592 allColumnsMinimumWidth(allColsMinimumWidth
)
594 columnCount
= tableView
->horizontalHeader()->count();
595 lastColumnIndex
= columnCount
- 1;
596 secondToLastColumnIndex
= columnCount
- 2;
597 tableView
->horizontalHeader()->setMinimumSectionSize(allColumnsMinimumWidth
);
598 setViewHeaderResizeMode(secondToLastColumnIndex
, QHeaderView::Interactive
);
599 setViewHeaderResizeMode(lastColumnIndex
, QHeaderView::Interactive
);
603 boost::filesystem::path
static StartupShortcutPath()
605 std::string chain
= ChainNameFromCommandLine();
606 if (chain
== CBaseChainParams::MAIN
)
607 return GetSpecialFolderPath(CSIDL_STARTUP
) / "Bitcoin.lnk";
608 if (chain
== CBaseChainParams::TESTNET
) // Remove this special case when CBaseChainParams::TESTNET = "testnet4"
609 return GetSpecialFolderPath(CSIDL_STARTUP
) / "Bitcoin (testnet).lnk";
610 return GetSpecialFolderPath(CSIDL_STARTUP
) / strprintf("Bitcoin (%s).lnk", chain
);
613 bool GetStartOnSystemStartup()
615 // check for Bitcoin*.lnk
616 return boost::filesystem::exists(StartupShortcutPath());
619 bool SetStartOnSystemStartup(bool fAutoStart
)
621 // If the shortcut exists already, remove it for updating
622 boost::filesystem::remove(StartupShortcutPath());
628 // Get a pointer to the IShellLink interface.
629 IShellLink
* psl
= NULL
;
630 HRESULT hres
= CoCreateInstance(CLSID_ShellLink
, NULL
,
631 CLSCTX_INPROC_SERVER
, IID_IShellLink
,
632 reinterpret_cast<void**>(&psl
));
636 // Get the current executable path
637 TCHAR pszExePath
[MAX_PATH
];
638 GetModuleFileName(NULL
, pszExePath
, sizeof(pszExePath
));
640 // Start client minimized
641 QString strArgs
= "-min";
642 // Set -testnet /-regtest options
643 strArgs
+= QString::fromStdString(strprintf(" -testnet=%d -regtest=%d", GetBoolArg("-testnet", false), GetBoolArg("-regtest", false)));
646 boost::scoped_array
<TCHAR
> args(new TCHAR
[strArgs
.length() + 1]);
647 // Convert the QString to TCHAR*
648 strArgs
.toWCharArray(args
.get());
649 // Add missing '\0'-termination to string
650 args
[strArgs
.length()] = '\0';
653 // Set the path to the shortcut target
654 psl
->SetPath(pszExePath
);
655 PathRemoveFileSpec(pszExePath
);
656 psl
->SetWorkingDirectory(pszExePath
);
657 psl
->SetShowCmd(SW_SHOWMINNOACTIVE
);
659 psl
->SetArguments(strArgs
.toStdString().c_str());
661 psl
->SetArguments(args
.get());
664 // Query IShellLink for the IPersistFile interface for
665 // saving the shortcut in persistent storage.
666 IPersistFile
* ppf
= NULL
;
667 hres
= psl
->QueryInterface(IID_IPersistFile
, reinterpret_cast<void**>(&ppf
));
670 WCHAR pwsz
[MAX_PATH
];
671 // Ensure that the string is ANSI.
672 MultiByteToWideChar(CP_ACP
, 0, StartupShortcutPath().string().c_str(), -1, pwsz
, MAX_PATH
);
673 // Save the link by calling IPersistFile::Save.
674 hres
= ppf
->Save(pwsz
, TRUE
);
687 #elif defined(Q_OS_LINUX)
689 // Follow the Desktop Application Autostart Spec:
690 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
692 boost::filesystem::path
static GetAutostartDir()
694 namespace fs
= boost::filesystem
;
696 char* pszConfigHome
= getenv("XDG_CONFIG_HOME");
697 if (pszConfigHome
) return fs::path(pszConfigHome
) / "autostart";
698 char* pszHome
= getenv("HOME");
699 if (pszHome
) return fs::path(pszHome
) / ".config" / "autostart";
703 boost::filesystem::path
static GetAutostartFilePath()
705 std::string chain
= ChainNameFromCommandLine();
706 if (chain
== CBaseChainParams::MAIN
)
707 return GetAutostartDir() / "bitcoin.desktop";
708 return GetAutostartDir() / strprintf("bitcoin-%s.lnk", chain
);
711 bool GetStartOnSystemStartup()
713 boost::filesystem::ifstream
optionFile(GetAutostartFilePath());
714 if (!optionFile
.good())
716 // Scan through file for "Hidden=true":
718 while (!optionFile
.eof())
720 getline(optionFile
, line
);
721 if (line
.find("Hidden") != std::string::npos
&&
722 line
.find("true") != std::string::npos
)
730 bool SetStartOnSystemStartup(bool fAutoStart
)
733 boost::filesystem::remove(GetAutostartFilePath());
736 char pszExePath
[MAX_PATH
+1];
737 memset(pszExePath
, 0, sizeof(pszExePath
));
738 if (readlink("/proc/self/exe", pszExePath
, sizeof(pszExePath
)-1) == -1)
741 boost::filesystem::create_directories(GetAutostartDir());
743 boost::filesystem::ofstream
optionFile(GetAutostartFilePath(), std::ios_base::out
|std::ios_base::trunc
);
744 if (!optionFile
.good())
746 std::string chain
= ChainNameFromCommandLine();
747 // Write a bitcoin.desktop file to the autostart directory:
748 optionFile
<< "[Desktop Entry]\n";
749 optionFile
<< "Type=Application\n";
750 if (chain
== CBaseChainParams::MAIN
)
751 optionFile
<< "Name=Bitcoin\n";
753 optionFile
<< strprintf("Name=Bitcoin (%s)\n", chain
);
754 optionFile
<< "Exec=" << pszExePath
<< strprintf(" -min -testnet=%d -regtest=%d\n", GetBoolArg("-testnet", false), GetBoolArg("-regtest", false));
755 optionFile
<< "Terminal=false\n";
756 optionFile
<< "Hidden=false\n";
763 #elif defined(Q_OS_MAC)
764 // based on: https://github.com/Mozketo/LaunchAtLoginController/blob/master/LaunchAtLoginController.m
766 #include <CoreFoundation/CoreFoundation.h>
767 #include <CoreServices/CoreServices.h>
769 LSSharedFileListItemRef
findStartupItemInList(LSSharedFileListRef list
, CFURLRef findUrl
);
770 LSSharedFileListItemRef
findStartupItemInList(LSSharedFileListRef list
, CFURLRef findUrl
)
772 // loop through the list of startup items and try to find the bitcoin app
773 CFArrayRef listSnapshot
= LSSharedFileListCopySnapshot(list
, NULL
);
774 for(int i
= 0; i
< CFArrayGetCount(listSnapshot
); i
++) {
775 LSSharedFileListItemRef item
= (LSSharedFileListItemRef
)CFArrayGetValueAtIndex(listSnapshot
, i
);
776 UInt32 resolutionFlags
= kLSSharedFileListNoUserInteraction
| kLSSharedFileListDoNotMountVolumes
;
777 CFURLRef currentItemURL
= NULL
;
779 #if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED >= 10100
780 if(&LSSharedFileListItemCopyResolvedURL
)
781 currentItemURL
= LSSharedFileListItemCopyResolvedURL(item
, resolutionFlags
, NULL
);
782 #if defined(MAC_OS_X_VERSION_MIN_REQUIRED) && MAC_OS_X_VERSION_MIN_REQUIRED < 10100
784 LSSharedFileListItemResolve(item
, resolutionFlags
, ¤tItemURL
, NULL
);
787 LSSharedFileListItemResolve(item
, resolutionFlags
, ¤tItemURL
, NULL
);
790 if(currentItemURL
&& CFEqual(currentItemURL
, findUrl
)) {
792 CFRelease(currentItemURL
);
796 CFRelease(currentItemURL
);
802 bool GetStartOnSystemStartup()
804 CFURLRef bitcoinAppUrl
= CFBundleCopyBundleURL(CFBundleGetMainBundle());
805 LSSharedFileListRef loginItems
= LSSharedFileListCreate(NULL
, kLSSharedFileListSessionLoginItems
, NULL
);
806 LSSharedFileListItemRef foundItem
= findStartupItemInList(loginItems
, bitcoinAppUrl
);
807 return !!foundItem
; // return boolified object
810 bool SetStartOnSystemStartup(bool fAutoStart
)
812 CFURLRef bitcoinAppUrl
= CFBundleCopyBundleURL(CFBundleGetMainBundle());
813 LSSharedFileListRef loginItems
= LSSharedFileListCreate(NULL
, kLSSharedFileListSessionLoginItems
, NULL
);
814 LSSharedFileListItemRef foundItem
= findStartupItemInList(loginItems
, bitcoinAppUrl
);
816 if(fAutoStart
&& !foundItem
) {
817 // add bitcoin app to startup item list
818 LSSharedFileListInsertItemURL(loginItems
, kLSSharedFileListItemBeforeFirst
, NULL
, NULL
, bitcoinAppUrl
, NULL
, NULL
);
820 else if(!fAutoStart
&& foundItem
) {
822 LSSharedFileListItemRemove(loginItems
, foundItem
);
828 bool GetStartOnSystemStartup() { return false; }
829 bool SetStartOnSystemStartup(bool fAutoStart
) { return false; }
833 void saveWindowGeometry(const QString
& strSetting
, QWidget
*parent
)
836 settings
.setValue(strSetting
+ "Pos", parent
->pos());
837 settings
.setValue(strSetting
+ "Size", parent
->size());
840 void restoreWindowGeometry(const QString
& strSetting
, const QSize
& defaultSize
, QWidget
*parent
)
843 QPoint pos
= settings
.value(strSetting
+ "Pos").toPoint();
844 QSize size
= settings
.value(strSetting
+ "Size", defaultSize
).toSize();
846 if (!pos
.x() && !pos
.y()) {
847 QRect screen
= QApplication::desktop()->screenGeometry();
848 pos
.setX((screen
.width() - size
.width()) / 2);
849 pos
.setY((screen
.height() - size
.height()) / 2);
852 parent
->resize(size
);
856 void setClipboard(const QString
& str
)
858 QApplication::clipboard()->setText(str
, QClipboard::Clipboard
);
859 QApplication::clipboard()->setText(str
, QClipboard::Selection
);
862 #if BOOST_FILESYSTEM_VERSION >= 3
863 boost::filesystem::path
qstringToBoostPath(const QString
&path
)
865 return boost::filesystem::path(path
.toStdString(), utf8
);
868 QString
boostPathToQString(const boost::filesystem::path
&path
)
870 return QString::fromStdString(path
.string(utf8
));
873 #warning Conversion between boost path and QString can use invalid character encoding with boost_filesystem v2 and older
874 boost::filesystem::path
qstringToBoostPath(const QString
&path
)
876 return boost::filesystem::path(path
.toStdString());
879 QString
boostPathToQString(const boost::filesystem::path
&path
)
881 return QString::fromStdString(path
.string());
885 QString
formatDurationStr(int secs
)
888 int days
= secs
/ 86400;
889 int hours
= (secs
% 86400) / 3600;
890 int mins
= (secs
% 3600) / 60;
891 int seconds
= secs
% 60;
894 strList
.append(QString(QObject::tr("%1 d")).arg(days
));
896 strList
.append(QString(QObject::tr("%1 h")).arg(hours
));
898 strList
.append(QString(QObject::tr("%1 m")).arg(mins
));
899 if (seconds
|| (!days
&& !hours
&& !mins
))
900 strList
.append(QString(QObject::tr("%1 s")).arg(seconds
));
902 return strList
.join(" ");
905 QString
formatServicesStr(quint64 mask
)
909 // Just scan the last 8 bits for now.
910 for (int i
= 0; i
< 8; i
++) {
911 uint64_t check
= 1 << i
;
917 strList
.append("NETWORK");
920 strList
.append("GETUTXO");
923 strList
.append("BLOOM");
926 strList
.append("WITNESS");
929 strList
.append("XTHIN");
932 strList
.append(QString("%1[%2]").arg("UNKNOWN").arg(check
));
938 return strList
.join(" & ");
940 return QObject::tr("None");
943 QString
formatPingTime(double dPingTime
)
945 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));
948 QString
formatTimeOffset(int64_t nTimeOffset
)
950 return QString(QObject::tr("%1 s")).arg(QString::number((int)nTimeOffset
, 10));
953 QString
formateNiceTimeOffset(qint64 secs
)
955 // Represent time from last generated block in human readable text
956 QString timeBehindText
;
957 const int HOUR_IN_SECONDS
= 60*60;
958 const int DAY_IN_SECONDS
= 24*60*60;
959 const int WEEK_IN_SECONDS
= 7*24*60*60;
960 const int YEAR_IN_SECONDS
= 31556952; // Average length of year in Gregorian calendar
963 timeBehindText
= QObject::tr("%n seconds(s)","",secs
);
965 else if(secs
< 2*HOUR_IN_SECONDS
)
967 timeBehindText
= QObject::tr("%n minutes(s)","",secs
/60);
969 else if(secs
< 2*DAY_IN_SECONDS
)
971 timeBehindText
= QObject::tr("%n hour(s)","",secs
/HOUR_IN_SECONDS
);
973 else if(secs
< 2*WEEK_IN_SECONDS
)
975 timeBehindText
= QObject::tr("%n day(s)","",secs
/DAY_IN_SECONDS
);
977 else if(secs
< YEAR_IN_SECONDS
)
979 timeBehindText
= QObject::tr("%n week(s)","",secs
/WEEK_IN_SECONDS
);
983 qint64 years
= secs
/ YEAR_IN_SECONDS
;
984 qint64 remainder
= secs
% YEAR_IN_SECONDS
;
985 timeBehindText
= QObject::tr("%1 and %2").arg(QObject::tr("%n year(s)", "", years
)).arg(QObject::tr("%n week(s)","", remainder
/WEEK_IN_SECONDS
));
987 return timeBehindText
;
989 } // namespace GUIUtil