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