PRCYCoin  2.0.0.7rc1
P2P Digital Currency
guiutil.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-2014 The Bitcoin developers
2 // Copyright (c) 2014-2015 The Dash developers
3 // Copyright (c) 2015-2018 The PIVX developers
4 // Copyright (c) 2018-2020 The DAPS Project developers
5 // Distributed under the MIT/X11 software license, see the accompanying
6 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 
8 #include "guiutil.h"
9 
11 #include "bitcoinunits.h"
12 #include "qvalidatedlineedit.h"
13 #include "walletmodel.h"
14 
15 #include "init.h"
16 #include "main.h"
17 #include "primitives/transaction.h"
18 #include "protocol.h"
19 #include "script/script.h"
20 #include "script/standard.h"
21 #include "util.h"
22 
23 #ifdef WIN32
24 #ifndef NOMINMAX
25 #define NOMINMAX
26 #endif
27 #include "shellapi.h"
28 #include "shlobj.h"
29 #include "shlwapi.h"
30 #endif
31 
32 #include <QAbstractItemView>
33 #include <QAbstractButton>
34 #include <QApplication>
35 #include <QCalendarWidget>
36 #include <QClipboard>
37 #include <QComboBox>
38 #include <QDateTime>
39 #include <QDesktopServices>
40 #include <QDesktopWidget>
41 #include <QDoubleValidator>
42 #include <QFileDialog>
43 #include <QFont>
44 #include <QFontDatabase>
45 #include <QLineEdit>
46 #include <QObject>
47 #include <QSettings>
48 #include <QSizePolicy>
49 #include <QTextDocument> // for Qt::mightBeRichText
50 #include <QThread>
51 #include <QTextStream>
52 #include <QUrlQuery>
53 #include <QMouseEvent>
54 
55 void ForceActivation();
56 
57 static fs::detail::utf8_codecvt_facet utf8;
58 
59 #define URI_SCHEME "prcycoin"
60 
61 #if defined(Q_OS_MAC)
62 
63 #include <QProcess>
64 
65 void ForceActivation();
66 #endif
67 
68 namespace GUIUtil
69 {
70 QString dateTimeStr(const QDateTime& date)
71 {
72  QString format = "MM/dd/yy HH:mm:ss";
73  return date.toString(format);
74 }
75 
76 QString dateTimeStr(qint64 nTime)
77 {
78  return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
79 }
80 
82 {
83  return QFontDatabase::systemFont(QFontDatabase::FixedFont);
84 }
85 
86 void setupAddressWidget(QValidatedLineEdit* widget, QWidget* parent)
87 {
88  parent->setFocusProxy(widget);
89 
90  // We don't want translators to use own addresses in translations
91  // and this is the only place, where this address is supplied.
92 
93 }
94 
95 void setupAmountWidget(QLineEdit* widget, QWidget* parent)
96 {
97  QDoubleValidator* amountValidator = new QDoubleValidator(parent);
98  amountValidator->setDecimals(8);
99  amountValidator->setBottom(0.0);
100  widget->setValidator(amountValidator);
101  widget->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
102 }
103 
104 bool parseBitcoinURI(const QUrl& uri, SendCoinsRecipient* out)
105 {
106  // return if URI is not valid or is no PRCYcoin: URI
107  if (!uri.isValid() || uri.scheme() != QString(URI_SCHEME))
108  return false;
109 
111  rv.address = uri.path();
112  // Trim any following forward slash which may have been added by the OS
113  if (rv.address.endsWith("/")) {
114  rv.address.truncate(rv.address.length() - 1);
115  }
116  rv.amount = 0;
117 
118  QUrlQuery uriQuery(uri);
119  QList<QPair<QString, QString> > items = uriQuery.queryItems();
120 
121  for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
122  {
123  bool fShouldReturnFalse = false;
124  if (i->first.startsWith("req-")) {
125  i->first.remove(0, 4);
126  fShouldReturnFalse = true;
127  }
128 
129  if (i->first == "label") {
130  rv.label = i->second;
131  fShouldReturnFalse = false;
132  }
133  if (i->first == "message") {
134  rv.message = i->second;
135  fShouldReturnFalse = false;
136  } else if (i->first == "amount") {
137  if (!i->second.isEmpty()) {
138  if (!BitcoinUnits::parse(BitcoinUnits::PRCY, i->second, &rv.amount)) {
139  return false;
140  }
141  }
142  fShouldReturnFalse = false;
143  }
144 
145  if (fShouldReturnFalse)
146  return false;
147  }
148  if (out) {
149  *out = rv;
150  }
151  return true;
152 }
153 
154 bool parseBitcoinURI(QString uri, SendCoinsRecipient* out)
155 {
156  // Convert prcycoin:// to prcycoin:
157  //
158  // Cannot handle this later, because prcycoin:// will cause Qt to see the part after // as host,
159  // which will lower-case it (and thus invalidate the address).
160  if (uri.startsWith(URI_SCHEME "://", Qt::CaseInsensitive)) {
161  uri.replace(0, std::strlen(URI_SCHEME) + 3, URI_SCHEME ":");
162  }
163  QUrl uriInstance(uri);
164  return parseBitcoinURI(uriInstance, out);
165 }
166 
168 {
169  QString ret = QString(URI_SCHEME ":%1").arg(info.address);
170  int paramCount = 0;
171 
172  if (info.amount) {
173  ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::PRCY, info.amount, false, BitcoinUnits::separatorNever));
174  paramCount++;
175  }
176 
177  if (!info.label.isEmpty()) {
178  QString lbl(QUrl::toPercentEncoding(info.label));
179  ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl);
180  paramCount++;
181  }
182 
183  if (!info.message.isEmpty()) {
184  QString msg(QUrl::toPercentEncoding(info.message));
185  ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg);
186  paramCount++;
187  }
188 
189  return ret;
190 }
191 
192 bool isDust(const QString& address, const CAmount& amount)
193 {
194  CTxDestination dest = CBitcoinAddress(address.toStdString()).Get();
195  CScript script = GetScriptForDestination(dest);
196  CTxOut txOut(amount, script);
197  return txOut.IsDust(::minRelayTxFee);
198 }
199 
200 QString HtmlEscape(const QString& str, bool fMultiLine)
201 {
202  QString escaped = str.toHtmlEscaped();
203  escaped = escaped.replace(" ", "&nbsp;");
204  if (fMultiLine) {
205  escaped = escaped.replace("\n", "<br>\n");
206  }
207  return escaped;
208 }
209 
210 QString HtmlEscape(const std::string& str, bool fMultiLine)
211 {
212  return HtmlEscape(QString::fromStdString(str), fMultiLine);
213 }
214 
215 void copyEntryData(QAbstractItemView* view, int column, int role)
216 {
217  if (!view || !view->selectionModel())
218  return;
219  QModelIndexList selection = view->selectionModel()->selectedRows(column);
220 
221  if (!selection.isEmpty()) {
222  // Copy first item
223  setClipboard(selection.at(0).data(role).toString());
224  }
225 }
226 
227 QVariant getEntryData(QAbstractItemView *view, int column, int role)
228 {
229  if(!view || !view->selectionModel())
230  return QVariant();
231  QModelIndexList selection = view->selectionModel()->selectedRows(column);
232  if(!selection.isEmpty()) {
233  // Return first item
234  return (selection.at(0).data(role));
235  }
236  return QVariant();
237 }
238 
239 QString getSaveFileName(QWidget* parent, const QString& caption, const QString& dir, const QString& filter, QString* selectedSuffixOut)
240 {
241  QString selectedFilter;
242  QString myDir;
243  if (dir.isEmpty()) // Default to user documents location
244  {
245  myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
246  } else {
247  myDir = dir;
248  }
249  /* Directly convert path to native OS path separators */
250  QString result = QDir::toNativeSeparators(QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter));
251 
252  /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
253  QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
254  QString selectedSuffix;
255  if (filter_re.exactMatch(selectedFilter)) {
256  selectedSuffix = filter_re.cap(1);
257  }
258 
259  /* Add suffix if needed */
260  QFileInfo info(result);
261  if (!result.isEmpty()) {
262  if (info.suffix().isEmpty() && !selectedSuffix.isEmpty()) {
263  /* No suffix specified, add selected suffix */
264  if (!result.endsWith("."))
265  result.append(".");
266  result.append(selectedSuffix);
267  }
268  }
269 
270  /* Return selected suffix if asked to */
271  if (selectedSuffixOut) {
272  *selectedSuffixOut = selectedSuffix;
273  }
274  return result;
275 }
276 
277 QString getOpenFileName(QWidget* parent, const QString& caption, const QString& dir, const QString& filter, QString* selectedSuffixOut)
278 {
279  QString selectedFilter;
280  QString myDir;
281  if (dir.isEmpty()) // Default to user documents location
282  {
283  myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
284  }
285  else
286  {
287  myDir = dir;
288  }
289  /* Directly convert path to native OS path separators */
290  QString result = QDir::toNativeSeparators(QFileDialog::getOpenFileName(parent, caption, myDir, filter, &selectedFilter));
291 
292  if (selectedSuffixOut) {
293  /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
294  QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
295  QString selectedSuffix;
296  if (filter_re.exactMatch(selectedFilter)) {
297  selectedSuffix = filter_re.cap(1);
298  }
299  *selectedSuffixOut = selectedSuffix;
300  }
301  return result;
302 }
303 
304 Qt::ConnectionType blockingGUIThreadConnection()
305 {
306  if (QThread::currentThread() != qApp->thread()) {
307  return Qt::BlockingQueuedConnection;
308  } else {
309  return Qt::DirectConnection;
310  }
311 }
312 
313 bool checkPoint(const QPoint& p, const QWidget* w)
314 {
315  QWidget* atW = QApplication::widgetAt(w->mapToGlobal(p));
316  if (!atW) return false;
317  return atW->window() == w;
318 }
319 
320 bool isObscured(QWidget* w)
321 {
322  return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
323 }
324 
325 void bringToFront(QWidget* w)
326 {
327 #ifdef Q_OS_MAC
328  ForceActivation();
329 #endif
330 
331  if (w) {
332  // activateWindow() (sometimes) helps with keyboard focus on Windows
333  if (w->isMinimized()) {
334  w->showNormal();
335  } else {
336  w->show();
337  }
338  w->activateWindow();
339  w->raise();
340  }
341 }
342 
343 /* Open file with the associated application */
344 bool openFile(fs::path path, bool isTextFile)
345 {
346  bool ret = false;
347  if (fs::exists(path)) {
348  ret = QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(path)));
349 #ifdef Q_OS_MAC
350  // Workaround for macOS-specific behavior; see btc@15409.
351  if (isTextFile && !ret) {
352  ret = QProcess::startDetached("/usr/bin/open", QStringList{"-t", boostPathToQString(path)});
353  }
354 #endif
355  }
356  return ret;
357 }
358 
360 {
361  return openFile(GetDataDir() / "debug.log", true);
362 }
363 
365 {
366  return openFile(GetConfigFile(), true);
367 }
368 
370 {
371  return openFile(GetMasternodeConfigFile(), true);
372 }
373 
375 {
376  fs::path pathDataDir = GetDataDir();
377 
378  /* Open folder with default browser */
379  if (fs::exists(pathDataDir))
380  return QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathDataDir)));
381  return false;
382 }
383 
384 void showQtDir()
385 {
386  QString pathQt = QCoreApplication::applicationDirPath();
387  QDesktopServices::openUrl(QUrl(pathQt, QUrl::TolerantMode));
388 }
389 
391 {
392  return openFile(GetDataDir() / "backups", false);
393 }
394 
395 ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject* parent) : QObject(parent),
396  size_threshold(size_threshold)
397 {
398 }
399 
400 bool ToolTipToRichTextFilter::eventFilter(QObject* obj, QEvent* evt)
401 {
402  if (evt->type() == QEvent::ToolTipChange) {
403  QWidget* widget = static_cast<QWidget*>(obj);
404  QString tooltip = widget->toolTip();
405  if (tooltip.size() > size_threshold && !tooltip.startsWith("<qt")) {
406  // Escape the current message as HTML and replace \n by <br> if it's not rich text
407  if (!Qt::mightBeRichText(tooltip))
408  tooltip = HtmlEscape(tooltip, true);
409  // Envelop with <qt></qt> to make sure Qt detects every tooltip as rich text
410  // and style='white-space:pre' to preserve line composition
411  tooltip = "<qt style='white-space:pre'>" + tooltip + "</qt>";
412  widget->setToolTip(tooltip);
413  return true;
414  }
415  }
416  return QObject::eventFilter(obj, evt);
417 }
418 
420 {
421  connect(tableView->horizontalHeader(), SIGNAL(sectionResized(int, int, int)), this, SLOT(on_sectionResized(int, int, int)));
422  connect(tableView->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged()));
423 }
424 
425 // We need to disconnect these while handling the resize events, otherwise we can enter infinite loops.
427 {
428  disconnect(tableView->horizontalHeader(), SIGNAL(sectionResized(int, int, int)), this, SLOT(on_sectionResized(int, int, int)));
429  disconnect(tableView->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged()));
430 }
431 
432 // Setup the resize mode, handles compatibility for Qt5 and below as the method signatures changed.
433 // Refactored here for readability.
434 void TableViewLastColumnResizingFixer::setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode)
435 {
436  tableView->horizontalHeader()->setSectionResizeMode(logicalIndex, resizeMode);
437 }
438 
439 void TableViewLastColumnResizingFixer::resizeColumn(int nColumnIndex, int width)
440 {
441  tableView->setColumnWidth(nColumnIndex, width);
442  tableView->horizontalHeader()->resizeSection(nColumnIndex, width);
443 }
444 
446 {
447  int nColumnsWidthSum = 0;
448  for (int i = 0; i < columnCount; i++) {
449  nColumnsWidthSum += tableView->horizontalHeader()->sectionSize(i);
450  }
451  return nColumnsWidthSum;
452 }
453 
455 {
456  int nResult = lastColumnMinimumWidth;
457  int nTableWidth = tableView->horizontalHeader()->width();
458 
459  if (nTableWidth > 0) {
460  int nOtherColsWidth = getColumnsWidth() - tableView->horizontalHeader()->sectionSize(column);
461  nResult = std::max(nResult, nTableWidth - nOtherColsWidth);
462  }
463 
464  return nResult;
465 }
466 
467 // Make sure we don't make the columns wider than the tables viewport width.
469 {
473 
474  int nTableWidth = tableView->horizontalHeader()->width();
475  int nColsWidth = getColumnsWidth();
476  if (nColsWidth > nTableWidth) {
478  }
479 }
480 
481 // Make column use all the space available, useful during window resizing.
483 {
485  resizeColumn(column, getAvailableWidthForColumn(column));
487 }
488 
489 // When a section is resized this is a slot-proxy for ajustAmountColumnWidth().
490 void TableViewLastColumnResizingFixer::on_sectionResized(int logicalIndex, int oldSize, int newSize)
491 {
493  int remainingWidth = getAvailableWidthForColumn(logicalIndex);
494  if (newSize > remainingWidth) {
495  resizeColumn(logicalIndex, remainingWidth);
496  }
497 }
498 
499 // When the tabless geometry is ready, we manually perform the stretch of the "Message" column,
500 // as the "Stretch" resize mode does not allow for interactive resizing.
502 {
503  if ((getColumnsWidth() - this->tableView->horizontalHeader()->width()) != 0) {
507  }
508 }
509 
514 TableViewLastColumnResizingFixer::TableViewLastColumnResizingFixer(QTableView* table, int lastColMinimumWidth, int allColsMinimumWidth) : tableView(table),
515  lastColumnMinimumWidth(lastColMinimumWidth),
516  allColumnsMinimumWidth(allColsMinimumWidth)
517 {
518  columnCount = tableView->horizontalHeader()->count();
521  tableView->horizontalHeader()->setMinimumSectionSize(allColumnsMinimumWidth);
522  setViewHeaderResizeMode(secondToLastColumnIndex, QHeaderView::Interactive);
523  setViewHeaderResizeMode(lastColumnIndex, QHeaderView::Interactive);
524 }
525 
530 DHMSTableWidgetItem::DHMSTableWidgetItem(const int64_t seconds) : QTableWidgetItem(),
531  value(seconds)
532 {
533  this->setText(QString::fromStdString(DurationToDHMS(seconds)));
534 }
535 
542 bool DHMSTableWidgetItem::operator<(QTableWidgetItem const& item) const
543 {
544  DHMSTableWidgetItem const* rhs =
545  dynamic_cast<DHMSTableWidgetItem const*>(&item);
546 
547  if (!rhs)
548  return QTableWidgetItem::operator<(item);
549 
550  return value < rhs->value;
551 }
552 
553 #ifdef WIN32
554 fs::path static StartupShortcutPath()
555 {
556  return GetSpecialFolderPath(CSIDL_STARTUP) / "PRCYcoin.lnk";
557 }
558 
560 {
561  // check for PRCYcoin.lnk
562  return fs::exists(StartupShortcutPath());
563 }
564 
565 bool SetStartOnSystemStartup(bool fAutoStart)
566 {
567  // If the shortcut exists already, remove it for updating
568  fs::remove(StartupShortcutPath());
569 
570  if (fAutoStart) {
571  CoInitialize(nullptr);
572 
573  // Get a pointer to the IShellLink interface.
574  IShellLink* psl = nullptr;
575  HRESULT hres = CoCreateInstance(CLSID_ShellLink, nullptr,
576  CLSCTX_INPROC_SERVER, IID_IShellLink,
577  reinterpret_cast<void**>(&psl));
578 
579  if (SUCCEEDED(hres)) {
580  // Get the current executable path
581  TCHAR pszExePath[MAX_PATH];
582  GetModuleFileName(nullptr, pszExePath, sizeof(pszExePath));
583 
584  TCHAR pszArgs[5] = TEXT("-min");
585 
586  // Set the path to the shortcut target
587  psl->SetPath(pszExePath);
588  PathRemoveFileSpec(pszExePath);
589  psl->SetWorkingDirectory(pszExePath);
590  psl->SetShowCmd(SW_SHOWMINNOACTIVE);
591  psl->SetArguments(pszArgs);
592 
593  // Query IShellLink for the IPersistFile interface for
594  // saving the shortcut in persistent storage.
595  IPersistFile* ppf = nullptr;
596  hres = psl->QueryInterface(IID_IPersistFile,
597  reinterpret_cast<void**>(&ppf));
598  if (SUCCEEDED(hres)) {
599  WCHAR pwsz[MAX_PATH];
600  // Ensure that the string is ANSI.
601  MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
602  // Save the link by calling IPersistFile::Save.
603  hres = ppf->Save(pwsz, TRUE);
604  ppf->Release();
605  psl->Release();
606  CoUninitialize();
607  return true;
608  }
609  psl->Release();
610  }
611  CoUninitialize();
612  return false;
613  }
614  return true;
615 }
616 
617 #elif defined(Q_OS_LINUX)
618 
619 // Follow the Desktop Application Autostart Spec:
620 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
621 
622 fs::path static GetAutostartDir()
623 {
624  char* pszConfigHome = getenv("XDG_CONFIG_HOME");
625  if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
626  char* pszHome = getenv("HOME");
627  if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
628  return fs::path();
629 }
630 
631 fs::path static GetAutostartFilePath()
632 {
633  return GetAutostartDir() / "prcycoin.desktop";
634 }
635 
637 {
638  fs::ifstream optionFile(GetAutostartFilePath());
639  if (!optionFile.good())
640  return false;
641  // Scan through file for "Hidden=true":
642  std::string line;
643  while (!optionFile.eof()) {
644  getline(optionFile, line);
645  if (line.find("Hidden") != std::string::npos &&
646  line.find("true") != std::string::npos)
647  return false;
648  }
649  optionFile.close();
650 
651  return true;
652 }
653 
654 bool SetStartOnSystemStartup(bool fAutoStart)
655 {
656  if (!fAutoStart)
657  fs::remove(GetAutostartFilePath());
658  else {
659  char pszExePath[MAX_PATH + 1];
660  memset(pszExePath, 0, sizeof(pszExePath));
661  if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath) - 1) == -1)
662  return false;
663 
664  fs::create_directories(GetAutostartDir());
665 
666  fs::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out | std::ios_base::trunc);
667  if (!optionFile.good())
668  return false;
669  // Write a prcycoin.desktop file to the autostart directory:
670  optionFile << "[Desktop Entry]\n";
671  optionFile << "Type=Application\n";
672  optionFile << "Name=PRCYcoin\n";
673  optionFile << "Exec=" << pszExePath << " -min\n";
674  optionFile << "Terminal=false\n";
675  optionFile << "Hidden=false\n";
676  optionFile.close();
677  }
678  return true;
679 }
680 
681 #else
682 
684 {
685  return false;
686 }
687 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
688 
689 #endif
690 
691 void saveWindowGeometry(const QString& strSetting, QWidget* parent)
692 {
693  QSettings settings;
694  settings.setValue(strSetting + "Pos", parent->pos());
695  settings.setValue(strSetting + "Size", parent->size());
696 }
697 
698 void HideDisabledWidgets( QVector<QWidget*> widgets ){
699  auto hide = []( QWidget* widget) { widget->setVisible(false); };
700  std::for_each (widgets.begin(), widgets.end(), hide);
701 }
702 
703 
704 void restoreWindowGeometry(const QString& strSetting, const QSize& defaultSize, QWidget* parent)
705 {
706  QSettings settings;
707  QPoint pos = settings.value(strSetting + "Pos").toPoint();
708  QSize size = settings.value(strSetting + "Size", defaultSize).toSize();
709 
710  if (!pos.x() && !pos.y()) {
711  QRect screen = QApplication::desktop()->screenGeometry();
712  pos.setX((screen.width() - size.width()) / 2);
713  pos.setY((screen.height() - size.height()) / 2);
714  }
715 
716  parent->resize(size);
717  parent->move(pos);
718 }
719 
720 // Open CSS when configured
721 QString loadStyleSheet()
722 {
723  QString styleSheet;
724  QSettings settings;
725  QVariant theme = settings.value("theme");
726  QString cssName = QString(":/css/" + theme.toString());
727  //LogPrintf("loadStyleSheet: Loading stylesheet %s\n", cssName.toStdString());
728  // Build-in CSS
729  settings.setValue("fCSSexternal", false);
730 
731  QFile qFile(cssName);
732  if (!qFile.exists()){
733  QTextStream qout(stdout);
734  qout << "Error: " << cssName << " not found. Please check qrc." <<endl;
735  } else if (qFile.open(QFile::ReadOnly)) {
736  styleSheet = QLatin1String(qFile.readAll());
737  return styleSheet;
738  }
739  return 0;
740 }
741 
743  qApp->setStyleSheet(GUIUtil::loadStyleSheet());
744  Q_FOREACH (QWidget *widget, QApplication::topLevelWidgets()){
745  widget->setStyleSheet(GUIUtil::loadStyleSheet());
746  widget->update();
747  }
748 }
749 
750 void setWindowless(QWidget* widget){
751  widget->setWindowFlags(Qt::Popup | Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint);
752  widget->setAttribute(Qt::WA_NoSystemBackground, true);
753  widget->setAttribute(Qt::WA_TranslucentBackground, true);
754  widget->setAttribute(Qt::WA_OpaquePaintEvent, false);
755  widget->setStyleSheet(GUIUtil::loadStyleSheet());
756 }
757 
758 void disableTooltips(QWidget* widget){
759 }
760 
761 void prompt(QString message){
762  QMessageBox* errorPrompt = new QMessageBox();
763  GUIUtil::setWindowless(errorPrompt);
764  errorPrompt->setStyleSheet(GUIUtil::loadStyleSheet());
765  errorPrompt->setText(message);
766  errorPrompt->exec();
767  errorPrompt->deleteLater();
768 }
769 
770 void colorCalendarWidgetWeekends(QCalendarWidget* widget, QColor color)
771 {
772  QTextCharFormat format = widget->weekdayTextFormat(Qt::Saturday);
773  format.setForeground(QBrush(color, Qt::SolidPattern));
774  widget->setWeekdayTextFormat(Qt::Saturday, format);
775  format = widget->weekdayTextFormat(Qt::Sunday);
776  format.setForeground(QBrush(color, Qt::SolidPattern));
777  widget->setWeekdayTextFormat(Qt::Sunday, format);
778  widget->parentWidget()->resize(300,300);
779  widget->findChild<QWidget*>("qt_calendar_navigationbar")->setMinimumHeight(65);
780  widget->findChild<QWidget*>("qt_calendar_calendarview")->setStyleSheet("padding:5px; margin:0;");
781  widget->findChild<QAbstractButton*>("qt_calendar_prevmonth")->setIcon(QIcon(":/images/leftArrow_small"));
782  widget->findChild<QAbstractButton*>("qt_calendar_nextmonth")->setIcon(QIcon(":/images/rightArrow_small"));
783 }
784 
785 void setClipboard(const QString& str)
786 {
787  QClipboard* clipboard = QApplication::clipboard();
788  clipboard->setText(str, QClipboard::Clipboard);
789  if (clipboard->supportsSelection()) {
790  clipboard->setText(str, QClipboard::Selection);
791  }
792 }
793 
794 fs::path qstringToBoostPath(const QString& path)
795 {
796  return fs::path(path.toStdString(), utf8);
797 }
798 
799 QString boostPathToQString(const fs::path& path)
800 {
801  return QString::fromStdString(path.string(utf8));
802 }
803 
804 QString formatDurationStr(int secs)
805 {
806  QStringList strList;
807  int days = secs / 86400;
808  int hours = (secs % 86400) / 3600;
809  int mins = (secs % 3600) / 60;
810  int seconds = secs % 60;
811 
812  if (days)
813  strList.append(QString(QObject::tr("%1 d")).arg(days));
814  if (hours)
815  strList.append(QString(QObject::tr("%1 h")).arg(hours));
816  if (mins)
817  strList.append(QString(QObject::tr("%1 m")).arg(mins));
818  if (seconds || (!days && !hours && !mins))
819  strList.append(QString(QObject::tr("%1 s")).arg(seconds));
820 
821  return strList.join(" ");
822 }
823 
824 QString formatServicesStr(quint64 mask)
825 {
826  QStringList strList;
827 
828  // Just scan the last 8 bits for now.
829  for (int i = 0; i < 8; i++) {
830  uint64_t check = 1 << i;
831  if (mask & check) {
832  switch (check) {
833  case NODE_NETWORK:
834  strList.append(QObject::tr("NETWORK"));
835  break;
836  case NODE_BLOOM:
838  strList.append(QObject::tr("BLOOM"));
839  break;
840  default:
841  strList.append(QString("%1[%2]").arg(QObject::tr("UNKNOWN")).arg(check));
842  }
843  }
844  }
845 
846  if (strList.size())
847  return strList.join(" & ");
848  else
849  return QObject::tr("None");
850 }
851 
852 QString formatPingTime(double dPingTime)
853 {
854  return dPingTime == 0 ? QObject::tr("N/A") : QString(QObject::tr("%1 ms")).arg(QString::number((int)(dPingTime * 1000), 10));
855 }
856 
857 QString formatTimeOffset(int64_t nTimeOffset)
858 {
859  return QString(QObject::tr("%1 s")).arg(QString::number((int)nTimeOffset, 10));
860 }
861 
862 QString formatBytes(uint64_t bytes)
863 {
864  if(bytes < 1024)
865  return QString(QObject::tr("%1 B")).arg(bytes);
866  if(bytes < 1024 * 1024)
867  return QString(QObject::tr("%1 KB")).arg(bytes / 1024);
868  if(bytes < 1024 * 1024 * 1024)
869  return QString(QObject::tr("%1 MB")).arg(bytes / 1024 / 1024);
870 
871  return QString(QObject::tr("%1 GB")).arg(bytes / 1024 / 1024 / 1024);
872 }
873 
874 } // namespace GUIUtil
SendCoinsRecipient::amount
CAmount amount
Definition: walletmodel.h:61
GUIUtil::TableViewLastColumnResizingFixer::on_geometriesChanged
void on_geometriesChanged()
Definition: guiutil.cpp:501
GUIUtil::setWindowless
void setWindowless(QWidget *widget)
Hideframes for pop up widgets.
Definition: guiutil.cpp:750
GUIUtil::TableViewLastColumnResizingFixer::connectViewHeadersSignals
void connectViewHeadersSignals()
Definition: guiutil.cpp:419
GUIUtil::DHMSTableWidgetItem::operator<
virtual bool operator<(QTableWidgetItem const &item) const
Comparator overload to ensure that the "DHMS"-type durations as used in the "active-since" list in th...
Definition: guiutil.cpp:542
GUIUtil::bitcoinAddressFont
QFont bitcoinAddressFont()
Definition: guiutil.cpp:81
GUIUtil::boostPathToQString
QString boostPathToQString(const fs::path &path)
Definition: guiutil.cpp:799
GUIUtil::TableViewLastColumnResizingFixer::columnCount
int columnCount
Definition: guiutil.h:192
minRelayTxFee
CFeeRate minRelayTxFee
Fees smaller than this (in duffs) are considered zero fee (for relaying and mining) We are ~100 times...
Definition: main.cpp:100
tinyformat::format
void format(std::ostream &out, const char *fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:958
GUIUtil::openDebugLogfile
bool openDebugLogfile()
Definition: guiutil.cpp:359
transaction.h
GUIUtil::openConfigfile
bool openConfigfile()
Definition: guiutil.cpp:364
GUIUtil::showDataDir
bool showDataDir()
Definition: guiutil.cpp:374
GUIUtil::colorCalendarWidgetWeekends
void colorCalendarWidgetWeekends(QCalendarWidget *widget, QColor color)
Change the color of weekends on calendar widget *Defaults to Red.
Definition: guiutil.cpp:770
GUIUtil::openMNConfigfile
bool openMNConfigfile()
Definition: guiutil.cpp:369
NODE_BLOOM_WITHOUT_MN
@ NODE_BLOOM_WITHOUT_MN
Definition: protocol.h:311
GUIUtil::SetStartOnSystemStartup
bool SetStartOnSystemStartup(bool fAutoStart)
Definition: guiutil.cpp:687
GUIUtil::TableViewLastColumnResizingFixer::resizeColumn
void resizeColumn(int nColumnIndex, int width)
Definition: guiutil.cpp:439
GUIUtil::disableTooltips
void disableTooltips(QWidget *widget)
Disable tooltips.
Definition: guiutil.cpp:758
walletmodel.h
GetScriptForDestination
CScript GetScriptForDestination(const CTxDestination &dest)
Definition: standard.cpp:285
CBitcoinAddress
base58-encoded PRCY addresses.
Definition: base58.h:109
GUIUtil::showQtDir
void showQtDir()
Definition: guiutil.cpp:384
SendCoinsRecipient::label
QString label
Definition: walletmodel.h:58
GUIUtil::ToolTipToRichTextFilter::eventFilter
bool eventFilter(QObject *obj, QEvent *evt)
Definition: guiutil.cpp:400
GUIUtil
Utility functions used by the PRCY Qt UI.
Definition: guiutil.cpp:68
GUIUtil::parseBitcoinURI
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
Definition: guiutil.cpp:104
CTxOut::IsDust
bool IsDust(CFeeRate minRelayTxFee) const
Definition: transaction.h:227
URI_SCHEME
#define URI_SCHEME
Definition: guiutil.cpp:59
GUIUtil::TableViewLastColumnResizingFixer::stretchColumnWidth
void stretchColumnWidth(int column)
Definition: guiutil.cpp:482
GUIUtil::formatBitcoinURI
QString formatBitcoinURI(const SendCoinsRecipient &info)
Definition: guiutil.cpp:167
GUIUtil::bringToFront
void bringToFront(QWidget *w)
Definition: guiutil.cpp:325
NODE_NETWORK
@ NODE_NETWORK
Definition: protocol.h:302
GUIUtil::qstringToBoostPath
fs::path qstringToBoostPath(const QString &path)
Definition: guiutil.cpp:794
GUIUtil::TableViewLastColumnResizingFixer::tableView
QTableView * tableView
Definition: guiutil.h:188
GUIUtil::isObscured
bool isObscured(QWidget *w)
Definition: guiutil.cpp:320
GUIUtil::setClipboard
void setClipboard(const QString &str)
Definition: guiutil.cpp:785
BitcoinUnits::parse
static bool parse(int unit, const QString &value, CAmount *val_out)
Parse string to coin amount.
Definition: bitcoinunits.cpp:220
SendCoinsRecipient
Definition: walletmodel.h:46
operator<
bool operator<(const CBigNum &a, const CBigNum &b)
Definition: bignum.h:797
GUIUtil::getEntryData
QVariant getEntryData(QAbstractItemView *view, int column, int role)
Return a field of the currently selected entry as a QString.
Definition: guiutil.cpp:227
GUIUtil::checkPoint
bool checkPoint(const QPoint &p, const QWidget *w)
Definition: guiutil.cpp:313
GUIUtil::formatTimeOffset
QString formatTimeOffset(int64_t nTimeOffset)
Definition: guiutil.cpp:857
GUIUtil::getOpenFileName
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:277
GUIUtil::openFile
bool openFile(fs::path path, bool isTextFile)
Definition: guiutil.cpp:344
CTxOut
An output of a transaction.
Definition: transaction.h:164
GUIUtil::TableViewLastColumnResizingFixer::secondToLastColumnIndex
int secondToLastColumnIndex
Definition: guiutil.h:193
GUIUtil::TableViewLastColumnResizingFixer::getAvailableWidthForColumn
int getAvailableWidthForColumn(int column)
Definition: guiutil.cpp:454
BitcoinUnits::PRCY
@ PRCY
Definition: bitcoinunits.h:61
init.h
GUIUtil::HideDisabledWidgets
void HideDisabledWidgets(QVector< QWidget * > widgets)
Definition: guiutil.cpp:698
GUIUtil::saveWindowGeometry
void saveWindowGeometry(const QString &strSetting, QWidget *parent)
Save window size and position.
Definition: guiutil.cpp:691
GUIUtil::DHMSTableWidgetItem
Extension to QTableWidgetItem that facilitates proper ordering for "DHMS" strings (primarily used in ...
Definition: guiutil.h:212
NODE_BLOOM
@ NODE_BLOOM
Definition: protocol.h:307
CAmount
int64_t CAmount
Amount in PRCY (Can be negative)
Definition: amount.h:17
QValidatedLineEdit
Line edit that can be marked as "invalid" to show input validation feedback.
Definition: qvalidatedlineedit.h:13
standard.h
GUIUtil::TableViewLastColumnResizingFixer::adjustTableColumnsWidth
void adjustTableColumnsWidth()
Definition: guiutil.cpp:468
GUIUtil::showBackups
bool showBackups()
Definition: guiutil.cpp:390
GUIUtil::copyEntryData
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:215
guiutil.h
GUIUtil::TableViewLastColumnResizingFixer::getColumnsWidth
int getColumnsWidth()
Definition: guiutil.cpp:445
GUIUtil::TableViewLastColumnResizingFixer::disconnectViewHeadersSignals
void disconnectViewHeadersSignals()
Definition: guiutil.cpp:426
GUIUtil::formatBytes
QString formatBytes(uint64_t bytes)
Definition: guiutil.cpp:862
GUIUtil::setupAmountWidget
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
Definition: guiutil.cpp:95
GUIUtil::formatServicesStr
QString formatServicesStr(quint64 mask)
Definition: guiutil.cpp:824
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:363
GUIUtil::prompt
void prompt(QString message)
Definition: guiutil.cpp:761
CTxDestination
boost::variant< CNoDestination, CKeyID, CScriptID > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:81
qvalidatedlineedit.h
BitcoinUnits::format
static QString format(int unit, const CAmount &amount, bool plussign=false, SeparatorStyle separators=separatorStandard)
Format as string.
Definition: bitcoinunits.cpp:140
GUIUtil::DHMSTableWidgetItem::value
int64_t value
Definition: guiutil.h:220
GUIUtil::getSaveFileName
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:239
GetConfigFile
fs::path GetConfigFile()
Definition: util.cpp:383
GUIUtil::GetStartOnSystemStartup
bool GetStartOnSystemStartup()
Definition: guiutil.cpp:683
GUIUtil::HtmlEscape
QString HtmlEscape(const QString &str, bool fMultiLine)
Definition: guiutil.cpp:200
bitcoinaddressvalidator.h
ForceActivation
void ForceActivation()
Force application activation on macOS.
Definition: macdockiconhandler.mm:50
main.h
GUIUtil::DHMSTableWidgetItem::DHMSTableWidgetItem
DHMSTableWidgetItem(const int64_t seconds)
Class constructor.
Definition: guiutil.cpp:530
SendCoinsRecipient::address
QString address
Definition: walletmodel.h:57
GUIUtil::ToolTipToRichTextFilter::size_threshold
int size_threshold
Definition: guiutil.h:166
GUIUtil::TableViewLastColumnResizingFixer::lastColumnMinimumWidth
int lastColumnMinimumWidth
Definition: guiutil.h:189
GUIUtil::TableViewLastColumnResizingFixer::on_sectionResized
void on_sectionResized(int logicalIndex, int oldSize, int newSize)
Definition: guiutil.cpp:490
GUIUtil::blockingGUIThreadConnection
Qt::ConnectionType blockingGUIThreadConnection()
Get connection type to call object slot in GUI thread with invokeMethod.
Definition: guiutil.cpp:304
GetDataDir
const fs::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:349
GUIUtil::formatPingTime
QString formatPingTime(double dPingTime)
Definition: guiutil.cpp:852
bitcoinunits.h
GUIUtil::ToolTipToRichTextFilter::ToolTipToRichTextFilter
ToolTipToRichTextFilter(int size_threshold, QObject *parent=0)
Definition: guiutil.cpp:395
GetMasternodeConfigFile
fs::path GetMasternodeConfigFile()
Definition: util.cpp:389
GUIUtil::formatDurationStr
QString formatDurationStr(int secs)
Definition: guiutil.cpp:804
script.h
GUIUtil::dateTimeStr
QString dateTimeStr(const QDateTime &date)
Definition: guiutil.cpp:70
DurationToDHMS
std::string DurationToDHMS(int64_t nDurationTime)
Definition: utiltime.cpp:60
GUIUtil::loadStyleSheet
QString loadStyleSheet()
Load global CSS theme.
Definition: guiutil.cpp:721
GUIUtil::TableViewLastColumnResizingFixer::TableViewLastColumnResizingFixer
TableViewLastColumnResizingFixer(QTableView *table, int lastColMinimumWidth, int allColsMinimumWidth)
Initializes all internal variables and prepares the the resize modes of the last 2 columns of the tab...
Definition: guiutil.cpp:514
CBitcoinAddress::Get
CTxDestination Get() const
Definition: base58.cpp:267
GUIUtil::isDust
bool isDust(const QString &address, const CAmount &amount)
Definition: guiutil.cpp:192
GUIUtil::setupAddressWidget
void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent)
Definition: guiutil.cpp:86
GUIUtil::refreshStyleSheet
void refreshStyleSheet()
Refresh App theme.
Definition: guiutil.cpp:742
MAX_PATH
#define MAX_PATH
Definition: compat.h:65
GUIUtil::TableViewLastColumnResizingFixer::lastColumnIndex
int lastColumnIndex
Definition: guiutil.h:191
GUIUtil::TableViewLastColumnResizingFixer::setViewHeaderResizeMode
void setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode)
Definition: guiutil.cpp:434
GUIUtil::restoreWindowGeometry
void restoreWindowGeometry(const QString &strSetting, const QSize &defaultSize, QWidget *parent)
Restore window size and position.
Definition: guiutil.cpp:704
BitcoinUnits::separatorNever
@ separatorNever
Definition: bitcoinunits.h:67
GUIUtil::TableViewLastColumnResizingFixer::allColumnsMinimumWidth
int allColumnsMinimumWidth
Definition: guiutil.h:190
SendCoinsRecipient::message
QString message
Definition: walletmodel.h:63