1 // Copyright (c) 2011-2013 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"
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 BOOST_FILESYSTEM_VERSION >= 3
66 static boost::filesystem::detail::utf8_codecvt_facet utf8;
70 extern double NSAppKitVersionNumber;
71 #if !defined(NSAppKitVersionNumber10_8)
72 #define NSAppKitVersionNumber10_8 1187
74 #if !defined(NSAppKitVersionNumber10_9)
75 #define NSAppKitVersionNumber10_9 1265
81 QString dateTimeStr(const QDateTime &date)
83 return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
86 QString dateTimeStr(qint64 nTime)
88 return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
91 QFont bitcoinAddressFont()
93 QFont font("Monospace");
94 #if QT_VERSION >= 0x040800
95 font.setStyleHint(QFont::Monospace);
97 font.setStyleHint(QFont::TypeWriter);
102 void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent)
104 parent->setFocusProxy(widget);
106 widget->setFont(bitcoinAddressFont());
107 #if QT_VERSION >= 0x040700
108 // We don't want translators to use own addresses in translations
109 // and this is the only place, where this address is supplied.
110 widget->setPlaceholderText(QObject::tr("Enter a Bitcoin address (e.g. %1)").arg("1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L"));
112 widget->setValidator(new BitcoinAddressEntryValidator(parent));
113 widget->setCheckValidator(new BitcoinAddressCheckValidator(parent));
116 void setupAmountWidget(QLineEdit *widget, QWidget *parent)
118 QDoubleValidator *amountValidator = new QDoubleValidator(parent);
119 amountValidator->setDecimals(8);
120 amountValidator->setBottom(0.0);
121 widget->setValidator(amountValidator);
122 widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
125 bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
127 // return if URI is not valid or is no bitcoin: URI
128 if(!uri.isValid() || uri.scheme() != QString("bitcoin"))
131 SendCoinsRecipient rv;
132 rv.address = uri.path();
133 // Trim any following forward slash which may have been added by the OS
134 if (rv.address.endsWith("/")) {
135 rv.address.truncate(rv.address.length() - 1);
139 #if QT_VERSION < 0x050000
140 QList<QPair<QString, QString> > items = uri.queryItems();
142 QUrlQuery uriQuery(uri);
143 QList<QPair<QString, QString> > items = uriQuery.queryItems();
145 for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
147 bool fShouldReturnFalse = false;
148 if (i->first.startsWith("req-"))
150 i->first.remove(0, 4);
151 fShouldReturnFalse = true;
154 if (i->first == "label")
156 rv.label = i->second;
157 fShouldReturnFalse = false;
159 if (i->first == "message")
161 rv.message = i->second;
162 fShouldReturnFalse = false;
164 else if (i->first == "amount")
166 if(!i->second.isEmpty())
168 if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
173 fShouldReturnFalse = false;
176 if (fShouldReturnFalse)
186 bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
188 // Convert bitcoin:// to bitcoin:
190 // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
191 // which will lower-case it (and thus invalidate the address).
192 if(uri.startsWith("bitcoin://", Qt::CaseInsensitive))
194 uri.replace(0, 10, "bitcoin:");
196 QUrl uriInstance(uri);
197 return parseBitcoinURI(uriInstance, out);
200 QString formatBitcoinURI(const SendCoinsRecipient &info)
202 QString ret = QString("bitcoin:%1").arg(info.address);
207 ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, info.amount, false, BitcoinUnits::separatorNever));
211 if (!info.label.isEmpty())
213 QString lbl(QUrl::toPercentEncoding(info.label));
214 ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl);
218 if (!info.message.isEmpty())
220 QString msg(QUrl::toPercentEncoding(info.message));;
221 ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg);
228 bool isDust(const QString& address, const CAmount& amount)
230 CTxDestination dest = CBitcoinAddress(address.toStdString()).Get();
231 CScript script = GetScriptForDestination(dest);
232 CTxOut txOut(amount, script);
233 return txOut.IsDust(::minRelayTxFee);
236 QString HtmlEscape(const QString& str, bool fMultiLine)
238 #if QT_VERSION < 0x050000
239 QString escaped = Qt::escape(str);
241 QString escaped = str.toHtmlEscaped();
245 escaped = escaped.replace("\n", "<br>\n");
250 QString HtmlEscape(const std::string& str, bool fMultiLine)
252 return HtmlEscape(QString::fromStdString(str), fMultiLine);
255 void copyEntryData(QAbstractItemView *view, int column, int role)
257 if(!view || !view->selectionModel())
259 QModelIndexList selection = view->selectionModel()->selectedRows(column);
261 if(!selection.isEmpty())
264 setClipboard(selection.at(0).data(role).toString());
268 QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir,
269 const QString &filter,
270 QString *selectedSuffixOut)
272 QString selectedFilter;
274 if(dir.isEmpty()) // Default to user documents location
276 #if QT_VERSION < 0x050000
277 myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
279 myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
286 /* Directly convert path to native OS path separators */
287 QString result = QDir::toNativeSeparators(QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter));
289 /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
290 QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
291 QString selectedSuffix;
292 if(filter_re.exactMatch(selectedFilter))
294 selectedSuffix = filter_re.cap(1);
297 /* Add suffix if needed */
298 QFileInfo info(result);
299 if(!result.isEmpty())
301 if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
303 /* No suffix specified, add selected suffix */
304 if(!result.endsWith("."))
306 result.append(selectedSuffix);
310 /* Return selected suffix if asked to */
311 if(selectedSuffixOut)
313 *selectedSuffixOut = selectedSuffix;
318 QString getOpenFileName(QWidget *parent, const QString &caption, const QString &dir,
319 const QString &filter,
320 QString *selectedSuffixOut)
322 QString selectedFilter;
324 if(dir.isEmpty()) // Default to user documents location
326 #if QT_VERSION < 0x050000
327 myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
329 myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
336 /* Directly convert path to native OS path separators */
337 QString result = QDir::toNativeSeparators(QFileDialog::getOpenFileName(parent, caption, myDir, filter, &selectedFilter));
339 if(selectedSuffixOut)
341 /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
342 QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
343 QString selectedSuffix;
344 if(filter_re.exactMatch(selectedFilter))
346 selectedSuffix = filter_re.cap(1);
348 *selectedSuffixOut = selectedSuffix;
353 Qt::ConnectionType blockingGUIThreadConnection()
355 if(QThread::currentThread() != qApp->thread())
357 return Qt::BlockingQueuedConnection;
361 return Qt::DirectConnection;
365 bool checkPoint(const QPoint &p, const QWidget *w)
367 QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p));
368 if (!atW) return false;
369 return atW->topLevelWidget() == w;
372 bool isObscured(QWidget *w)
374 return !(checkPoint(QPoint(0, 0), w)
375 && checkPoint(QPoint(w->width() - 1, 0), w)
376 && checkPoint(QPoint(0, w->height() - 1), w)
377 && checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
378 && checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
381 void openDebugLogfile()
383 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
385 /* Open debug.log with the associated application */
386 if (boost::filesystem::exists(pathDebug))
387 QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathDebug)));
390 void SubstituteFonts(const QString& language)
392 #if defined(Q_OS_MAC)
394 // OSX's default font changed in 10.9 and Qt is unable to find it with its
395 // usual fallback methods when building against the 10.7 sdk or lower.
396 // The 10.8 SDK added a function to let it find the correct fallback font.
397 // If this fallback is not properly loaded, some characters may fail to
400 // The same thing happened with 10.10. .Helvetica Neue DeskInterface is now default.
402 // Solution: If building with the 10.7 SDK or lower and the user's platform
403 // is 10.9 or higher at runtime, substitute the correct font. This needs to
404 // happen before the QApplication is created.
405 #if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_8
406 if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_8)
408 if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_9)
409 /* On a 10.9 - 10.9.x system */
410 QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande");
413 /* 10.10 or later system */
414 if (language == "zh_CN" || language == "zh_TW" || language == "zh_HK") // traditional or simplified Chinese
415 QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Heiti SC");
416 else if (language == "ja") // Japanesee
417 QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Songti SC");
419 QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Lucida Grande");
426 ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
428 size_threshold(size_threshold)
433 bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
435 if(evt->type() == QEvent::ToolTipChange)
437 QWidget *widget = static_cast<QWidget*>(obj);
438 QString tooltip = widget->toolTip();
439 if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt") && !Qt::mightBeRichText(tooltip))
441 // Envelop with <qt></qt> to make sure Qt detects this as rich text
442 // Escape the current message as HTML and replace \n by <br>
443 tooltip = "<qt>" + HtmlEscape(tooltip, true) + "</qt>";
444 widget->setToolTip(tooltip);
448 return QObject::eventFilter(obj, evt);
451 void TableViewLastColumnResizingFixer::connectViewHeadersSignals()
453 connect(tableView->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(on_sectionResized(int,int,int)));
454 connect(tableView->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged()));
457 // We need to disconnect these while handling the resize events, otherwise we can enter infinite loops.
458 void TableViewLastColumnResizingFixer::disconnectViewHeadersSignals()
460 disconnect(tableView->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(on_sectionResized(int,int,int)));
461 disconnect(tableView->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged()));
464 // Setup the resize mode, handles compatibility for Qt5 and below as the method signatures changed.
465 // Refactored here for readability.
466 void TableViewLastColumnResizingFixer::setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode)
468 #if QT_VERSION < 0x050000
469 tableView->horizontalHeader()->setResizeMode(logicalIndex, resizeMode);
471 tableView->horizontalHeader()->setSectionResizeMode(logicalIndex, resizeMode);
475 void TableViewLastColumnResizingFixer::resizeColumn(int nColumnIndex, int width)
477 tableView->setColumnWidth(nColumnIndex, width);
478 tableView->horizontalHeader()->resizeSection(nColumnIndex, width);
481 int TableViewLastColumnResizingFixer::getColumnsWidth()
483 int nColumnsWidthSum = 0;
484 for (int i = 0; i < columnCount; i++)
486 nColumnsWidthSum += tableView->horizontalHeader()->sectionSize(i);
488 return nColumnsWidthSum;
491 int TableViewLastColumnResizingFixer::getAvailableWidthForColumn(int column)
493 int nResult = lastColumnMinimumWidth;
494 int nTableWidth = tableView->horizontalHeader()->width();
498 int nOtherColsWidth = getColumnsWidth() - tableView->horizontalHeader()->sectionSize(column);
499 nResult = std::max(nResult, nTableWidth - nOtherColsWidth);
505 // Make sure we don't make the columns wider than the tables viewport width.
506 void TableViewLastColumnResizingFixer::adjustTableColumnsWidth()
508 disconnectViewHeadersSignals();
509 resizeColumn(lastColumnIndex, getAvailableWidthForColumn(lastColumnIndex));
510 connectViewHeadersSignals();
512 int nTableWidth = tableView->horizontalHeader()->width();
513 int nColsWidth = getColumnsWidth();
514 if (nColsWidth > nTableWidth)
516 resizeColumn(secondToLastColumnIndex,getAvailableWidthForColumn(secondToLastColumnIndex));
520 // Make column use all the space available, useful during window resizing.
521 void TableViewLastColumnResizingFixer::stretchColumnWidth(int column)
523 disconnectViewHeadersSignals();
524 resizeColumn(column, getAvailableWidthForColumn(column));
525 connectViewHeadersSignals();
528 // When a section is resized this is a slot-proxy for ajustAmountColumnWidth().
529 void TableViewLastColumnResizingFixer::on_sectionResized(int logicalIndex, int oldSize, int newSize)
531 adjustTableColumnsWidth();
532 int remainingWidth = getAvailableWidthForColumn(logicalIndex);
533 if (newSize > remainingWidth)
535 resizeColumn(logicalIndex, remainingWidth);
539 // When the tabless geometry is ready, we manually perform the stretch of the "Message" column,
540 // as the "Stretch" resize mode does not allow for interactive resizing.
541 void TableViewLastColumnResizingFixer::on_geometriesChanged()
543 if ((getColumnsWidth() - this->tableView->horizontalHeader()->width()) != 0)
545 disconnectViewHeadersSignals();
546 resizeColumn(secondToLastColumnIndex, getAvailableWidthForColumn(secondToLastColumnIndex));
547 connectViewHeadersSignals();
552 * Initializes all internal variables and prepares the
553 * the resize modes of the last 2 columns of the table and
555 TableViewLastColumnResizingFixer::TableViewLastColumnResizingFixer(QTableView* table, int lastColMinimumWidth, int allColsMinimumWidth) :
557 lastColumnMinimumWidth(lastColMinimumWidth),
558 allColumnsMinimumWidth(allColsMinimumWidth)
560 columnCount = tableView->horizontalHeader()->count();
561 lastColumnIndex = columnCount - 1;
562 secondToLastColumnIndex = columnCount - 2;
563 tableView->horizontalHeader()->setMinimumSectionSize(allColumnsMinimumWidth);
564 setViewHeaderResizeMode(secondToLastColumnIndex, QHeaderView::Interactive);
565 setViewHeaderResizeMode(lastColumnIndex, QHeaderView::Interactive);
569 boost::filesystem::path static StartupShortcutPath()
571 if (GetBoolArg("-testnet", false))
572 return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin (testnet).lnk";
573 else if (GetBoolArg("-regtest", false))
574 return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin (regtest).lnk";
576 return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin.lnk";
579 bool GetStartOnSystemStartup()
581 // check for Bitcoin*.lnk
582 return boost::filesystem::exists(StartupShortcutPath());
585 bool SetStartOnSystemStartup(bool fAutoStart)
587 // If the shortcut exists already, remove it for updating
588 boost::filesystem::remove(StartupShortcutPath());
594 // Get a pointer to the IShellLink interface.
595 IShellLink* psl = NULL;
596 HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
597 CLSCTX_INPROC_SERVER, IID_IShellLink,
598 reinterpret_cast<void**>(&psl));
602 // Get the current executable path
603 TCHAR pszExePath[MAX_PATH];
604 GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
606 // Start client minimized
607 QString strArgs = "-min";
608 // Set -testnet /-regtest options
609 strArgs += QString::fromStdString(strprintf(" -testnet=%d -regtest=%d", GetBoolArg("-testnet", false), GetBoolArg("-regtest", false)));
612 boost::scoped_array<TCHAR> args(new TCHAR[strArgs.length() + 1]);
613 // Convert the QString to TCHAR*
614 strArgs.toWCharArray(args.get());
615 // Add missing '\0'-termination to string
616 args[strArgs.length()] = '\0';
619 // Set the path to the shortcut target
620 psl->SetPath(pszExePath);
621 PathRemoveFileSpec(pszExePath);
622 psl->SetWorkingDirectory(pszExePath);
623 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
625 psl->SetArguments(strArgs.toStdString().c_str());
627 psl->SetArguments(args.get());
630 // Query IShellLink for the IPersistFile interface for
631 // saving the shortcut in persistent storage.
632 IPersistFile* ppf = NULL;
633 hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf));
636 WCHAR pwsz[MAX_PATH];
637 // Ensure that the string is ANSI.
638 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
639 // Save the link by calling IPersistFile::Save.
640 hres = ppf->Save(pwsz, TRUE);
653 #elif defined(Q_OS_LINUX)
655 // Follow the Desktop Application Autostart Spec:
656 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
658 boost::filesystem::path static GetAutostartDir()
660 namespace fs = boost::filesystem;
662 char* pszConfigHome = getenv("XDG_CONFIG_HOME");
663 if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
664 char* pszHome = getenv("HOME");
665 if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
669 boost::filesystem::path static GetAutostartFilePath()
671 return GetAutostartDir() / "bitcoin.desktop";
674 bool GetStartOnSystemStartup()
676 boost::filesystem::ifstream optionFile(GetAutostartFilePath());
677 if (!optionFile.good())
679 // Scan through file for "Hidden=true":
681 while (!optionFile.eof())
683 getline(optionFile, line);
684 if (line.find("Hidden") != std::string::npos &&
685 line.find("true") != std::string::npos)
693 bool SetStartOnSystemStartup(bool fAutoStart)
696 boost::filesystem::remove(GetAutostartFilePath());
699 char pszExePath[MAX_PATH+1];
700 memset(pszExePath, 0, sizeof(pszExePath));
701 if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
704 boost::filesystem::create_directories(GetAutostartDir());
706 boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
707 if (!optionFile.good())
709 // Write a bitcoin.desktop file to the autostart directory:
710 optionFile << "[Desktop Entry]\n";
711 optionFile << "Type=Application\n";
712 if (GetBoolArg("-testnet", false))
713 optionFile << "Name=Bitcoin (testnet)\n";
714 else if (GetBoolArg("-regtest", false))
715 optionFile << "Name=Bitcoin (regtest)\n";
717 optionFile << "Name=Bitcoin\n";
718 optionFile << "Exec=" << pszExePath << strprintf(" -min -testnet=%d -regtest=%d\n", GetBoolArg("-testnet", false), GetBoolArg("-regtest", false));
719 optionFile << "Terminal=false\n";
720 optionFile << "Hidden=false\n";
727 #elif defined(Q_OS_MAC)
728 // based on: https://github.com/Mozketo/LaunchAtLoginController/blob/master/LaunchAtLoginController.m
730 #include <CoreFoundation/CoreFoundation.h>
731 #include <CoreServices/CoreServices.h>
733 LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl);
734 LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl)
736 // loop through the list of startup items and try to find the bitcoin app
737 CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, NULL);
738 for(int i = 0; i < CFArrayGetCount(listSnapshot); i++) {
739 LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i);
740 UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes;
741 CFURLRef currentItemURL = NULL;
743 #if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED >= 10100
744 if(&LSSharedFileListItemCopyResolvedURL)
745 currentItemURL = LSSharedFileListItemCopyResolvedURL(item, resolutionFlags, NULL);
746 #if defined(MAC_OS_X_VERSION_MIN_REQUIRED) && MAC_OS_X_VERSION_MIN_REQUIRED < 10100
748 LSSharedFileListItemResolve(item, resolutionFlags, ¤tItemURL, NULL);
751 LSSharedFileListItemResolve(item, resolutionFlags, ¤tItemURL, NULL);
754 if(currentItemURL && CFEqual(currentItemURL, findUrl)) {
756 CFRelease(currentItemURL);
760 CFRelease(currentItemURL);
766 bool GetStartOnSystemStartup()
768 CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
769 LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
770 LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);
771 return !!foundItem; // return boolified object
774 bool SetStartOnSystemStartup(bool fAutoStart)
776 CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
777 LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
778 LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);
780 if(fAutoStart && !foundItem) {
781 // add bitcoin app to startup item list
782 LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, NULL, NULL, bitcoinAppUrl, NULL, NULL);
784 else if(!fAutoStart && foundItem) {
786 LSSharedFileListItemRemove(loginItems, foundItem);
792 bool GetStartOnSystemStartup() { return false; }
793 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
797 void saveWindowGeometry(const QString& strSetting, QWidget *parent)
800 settings.setValue(strSetting + "Pos", parent->pos());
801 settings.setValue(strSetting + "Size", parent->size());
804 void restoreWindowGeometry(const QString& strSetting, const QSize& defaultSize, QWidget *parent)
807 QPoint pos = settings.value(strSetting + "Pos").toPoint();
808 QSize size = settings.value(strSetting + "Size", defaultSize).toSize();
810 if (!pos.x() && !pos.y()) {
811 QRect screen = QApplication::desktop()->screenGeometry();
812 pos.setX((screen.width() - size.width()) / 2);
813 pos.setY((screen.height() - size.height()) / 2);
816 parent->resize(size);
820 void setClipboard(const QString& str)
822 QApplication::clipboard()->setText(str, QClipboard::Clipboard);
823 QApplication::clipboard()->setText(str, QClipboard::Selection);
826 #if BOOST_FILESYSTEM_VERSION >= 3
827 boost::filesystem::path qstringToBoostPath(const QString &path)
829 return boost::filesystem::path(path.toStdString(), utf8);
832 QString boostPathToQString(const boost::filesystem::path &path)
834 return QString::fromStdString(path.string(utf8));
837 #warning Conversion between boost path and QString can use invalid character encoding with boost_filesystem v2 and older
838 boost::filesystem::path qstringToBoostPath(const QString &path)
840 return boost::filesystem::path(path.toStdString());
843 QString boostPathToQString(const boost::filesystem::path &path)
845 return QString::fromStdString(path.string());
849 QString formatDurationStr(int secs)
852 int days = secs / 86400;
853 int hours = (secs % 86400) / 3600;
854 int mins = (secs % 3600) / 60;
855 int seconds = secs % 60;
858 strList.append(QString(QObject::tr("%1 d")).arg(days));
860 strList.append(QString(QObject::tr("%1 h")).arg(hours));
862 strList.append(QString(QObject::tr("%1 m")).arg(mins));
863 if (seconds || (!days && !hours && !mins))
864 strList.append(QString(QObject::tr("%1 s")).arg(seconds));
866 return strList.join(" ");
869 QString formatServicesStr(quint64 mask)
873 // Just scan the last 8 bits for now.
874 for (int i = 0; i < 8; i++) {
875 uint64_t check = 1 << i;
881 strList.append("NETWORK");
884 strList.append("GETUTXO");
887 strList.append(QString("%1[%2]").arg("UNKNOWN").arg(check));
893 return strList.join(" & ");
895 return QObject::tr("None");
898 QString formatPingTime(double dPingTime)
900 return dPingTime == 0 ? QObject::tr("N/A") : QString(QObject::tr("%1 ms")).arg(QString::number((int)(dPingTime * 1000), 10));
903 QString formatTimeOffset(int64_t nTimeOffset)
905 return QString(QObject::tr("%1 s")).arg(QString::number((int)nTimeOffset, 10));
908 } // namespace GUIUtil