Bitcoin Core  22.99.0
P2P Digital Currency
guiutil.h
Go to the documentation of this file.
1 // Copyright (c) 2011-2020 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 #ifndef BITCOIN_QT_GUIUTIL_H
6 #define BITCOIN_QT_GUIUTIL_H
7 
8 #include <consensus/amount.h>
9 #include <fs.h>
10 #include <net.h>
11 #include <netaddress.h>
12 #include <util/check.h>
13 
14 #include <QApplication>
15 #include <QEvent>
16 #include <QHeaderView>
17 #include <QItemDelegate>
18 #include <QLabel>
19 #include <QMessageBox>
20 #include <QMetaObject>
21 #include <QObject>
22 #include <QProgressBar>
23 #include <QString>
24 #include <QTableView>
25 
26 #include <cassert>
27 #include <chrono>
28 #include <utility>
29 
30 class PlatformStyle;
31 class QValidatedLineEdit;
32 class SendCoinsRecipient;
33 
34 namespace interfaces
35 {
36  class Node;
37 }
38 
39 QT_BEGIN_NAMESPACE
40 class QAbstractButton;
41 class QAbstractItemView;
42 class QAction;
43 class QDateTime;
44 class QDialog;
45 class QFont;
46 class QKeySequence;
47 class QLineEdit;
48 class QMenu;
49 class QPoint;
50 class QProgressDialog;
51 class QUrl;
52 class QWidget;
53 QT_END_NAMESPACE
54 
57 namespace GUIUtil
58 {
59  // Use this flags to prevent a "What's This" button in the title bar of the dialog on Windows.
60  constexpr auto dialog_flags = Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
61 
62  // Create human-readable string from date
63  QString dateTimeStr(const QDateTime &datetime);
64  QString dateTimeStr(qint64 nTime);
65 
66  // Return a monospace font
67  QFont fixedPitchFont(bool use_embedded_font = false);
68 
69  // Set up widget for address
70  void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent);
71 
78  void AddButtonShortcut(QAbstractButton* button, const QKeySequence& shortcut);
79 
80  // Parse "bitcoin:" URI into recipient object, return true on successful parsing
81  bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out);
82  bool parseBitcoinURI(QString uri, SendCoinsRecipient *out);
83  QString formatBitcoinURI(const SendCoinsRecipient &info);
84 
85  // Returns true if given address+amount meets "dust" definition
86  bool isDust(interfaces::Node& node, const QString& address, const CAmount& amount);
87 
88  // HTML escaping for rich text controls
89  QString HtmlEscape(const QString& str, bool fMultiLine=false);
90  QString HtmlEscape(const std::string& str, bool fMultiLine=false);
91 
98  void copyEntryData(const QAbstractItemView *view, int column, int role=Qt::EditRole);
99 
105  QList<QModelIndex> getEntryData(const QAbstractItemView *view, int column);
106 
112  bool hasEntryData(const QAbstractItemView *view, int column, int role);
113 
114  void setClipboard(const QString& str);
115 
119  void LoadFont(const QString& file_name);
120 
124  QString getDefaultDataDirectory();
125 
136  QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir,
137  const QString &filter,
138  QString *selectedSuffixOut);
139 
149  QString getOpenFileName(QWidget *parent, const QString &caption, const QString &dir,
150  const QString &filter,
151  QString *selectedSuffixOut);
152 
159 
160  // Determine whether a widget is hidden behind other windows
161  bool isObscured(QWidget *w);
162 
163  // Activate, show and raise the widget
164  void bringToFront(QWidget* w);
165 
166  // Set shortcut to close window
167  void handleCloseWindowShortcut(QWidget* w);
168 
169  // Open debug.log
170  void openDebugLogfile();
171 
172  // Open the config file
173  bool openBitcoinConf();
174 
179  class ToolTipToRichTextFilter : public QObject
180  {
181  Q_OBJECT
182 
183  public:
184  explicit ToolTipToRichTextFilter(int size_threshold, QObject *parent = nullptr);
185 
186  protected:
187  bool eventFilter(QObject *obj, QEvent *evt) override;
188 
189  private:
191  };
192 
199  class LabelOutOfFocusEventFilter : public QObject
200  {
201  Q_OBJECT
202 
203  public:
204  explicit LabelOutOfFocusEventFilter(QObject* parent);
205  bool eventFilter(QObject* watched, QEvent* event) override;
206  };
207 
209  bool SetStartOnSystemStartup(bool fAutoStart);
210 
212  fs::path qstringToBoostPath(const QString &path);
213 
215  QString boostPathToQString(const fs::path &path);
216 
218  QString NetworkToQString(Network net);
219 
221  QString ConnectionTypeToQString(ConnectionType conn_type, bool prepend_direction);
222 
224  QString formatDurationStr(int secs);
225 
227  QString formatServicesStr(quint64 mask);
228 
230  QString formatPingTime(std::chrono::microseconds ping_time);
231 
233  QString formatTimeOffset(int64_t nTimeOffset);
234 
235  QString formatNiceTimeOffset(qint64 secs);
236 
237  QString formatBytes(uint64_t bytes);
238 
239  qreal calculateIdealFontSize(int width, const QString& text, QFont font, qreal minPointSize = 4, qreal startPointSize = 14);
240 
241  class ThemedLabel : public QLabel
242  {
243  Q_OBJECT
244 
245  public:
246  explicit ThemedLabel(const PlatformStyle* platform_style, QWidget* parent = nullptr);
247  void setThemedPixmap(const QString& image_filename, int width, int height);
248 
249  protected:
250  void changeEvent(QEvent* e) override;
251 
252  private:
257  void updateThemedPixmap();
258  };
259 
261  {
262  Q_OBJECT
263 
264  public:
265  explicit ClickableLabel(const PlatformStyle* platform_style, QWidget* parent = nullptr);
266 
267  Q_SIGNALS:
271  void clicked(const QPoint& point);
272  protected:
273  void mouseReleaseEvent(QMouseEvent *event) override;
274  };
275 
276  class ClickableProgressBar : public QProgressBar
277  {
278  Q_OBJECT
279 
280  Q_SIGNALS:
284  void clicked(const QPoint& point);
285  protected:
286  void mouseReleaseEvent(QMouseEvent *event) override;
287  };
288 
290 
291  class ItemDelegate : public QItemDelegate
292  {
293  Q_OBJECT
294  public:
295  ItemDelegate(QObject* parent) : QItemDelegate(parent) {}
296 
297  Q_SIGNALS:
298  void keyEscapePressed();
299 
300  private:
301  bool eventFilter(QObject *object, QEvent *event) override;
302  };
303 
304  // Fix known bugs in QProgressDialog class.
305  void PolishProgressDialog(QProgressDialog* dialog);
306 
313  int TextWidth(const QFontMetrics& fm, const QString& text);
314 
318  void LogQtInfo();
319 
323  void PopupMenu(QMenu* menu, const QPoint& point, QAction* at_action = nullptr);
324 
331  QDateTime StartOfDay(const QDate& date);
332 
338  bool HasPixmap(const QLabel* label);
339  QImage GetImage(const QLabel* label);
340 
351  template <typename SeparatorType>
352  QStringList SplitSkipEmptyParts(const QString& string, const SeparatorType& separator)
353  {
354  #if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
355  return string.split(separator, Qt::SkipEmptyParts);
356  #else
357  return string.split(separator, QString::SkipEmptyParts);
358  #endif
359  }
360 
367  template <typename Fn>
368  void ObjectInvoke(QObject* object, Fn&& function, Qt::ConnectionType connection = Qt::QueuedConnection)
369  {
370  QObject source;
371  QObject::connect(&source, &QObject::destroyed, object, std::forward<Fn>(function), connection);
372  }
373 
377  QString MakeHtmlLink(const QString& source, const QString& link);
378 
379  void PrintSlotException(
380  const std::exception* exception,
381  const QObject* sender,
382  const QObject* receiver);
383 
391  template <typename Sender, typename Signal, typename Receiver, typename Slot>
393  Sender sender, Signal signal, Receiver receiver, Slot method,
394  Qt::ConnectionType type = Qt::AutoConnection)
395  {
396  return QObject::connect(
397  sender, signal, receiver,
398  [sender, receiver, method](auto&&... args) {
399  bool ok{true};
400  try {
401  (receiver->*method)(std::forward<decltype(args)>(args)...);
402  } catch (const NonFatalCheckError& e) {
403  PrintSlotException(&e, sender, receiver);
404  ok = QMetaObject::invokeMethod(
405  qApp, "handleNonFatalException",
407  Q_ARG(QString, QString::fromStdString(e.what())));
408  } catch (const std::exception& e) {
409  PrintSlotException(&e, sender, receiver);
410  ok = QMetaObject::invokeMethod(
411  qApp, "handleRunawayException",
413  Q_ARG(QString, QString::fromStdString(e.what())));
414  } catch (...) {
415  PrintSlotException(nullptr, sender, receiver);
416  ok = QMetaObject::invokeMethod(
417  qApp, "handleRunawayException",
419  Q_ARG(QString, "Unknown failure occurred."));
420  }
421  assert(ok);
422  },
423  type);
424  }
425 
429  void ShowModalDialogAndDeleteOnClose(QDialog* dialog);
430 
431 } // namespace GUIUtil
432 
433 #endif // BITCOIN_QT_GUIUTIL_H
interfaces
Definition: dummywallet.cpp:11
GUIUtil::ToolTipToRichTextFilter
Qt event filter that intercepts ToolTipChange events, and replaces the tooltip with a rich text repre...
Definition: guiutil.h:179
GUIUtil::boostPathToQString
QString boostPathToQString(const fs::path &path)
Convert OS specific boost path to QString through UTF-8.
Definition: guiutil.cpp:659
GUIUtil::openBitcoinConf
bool openBitcoinConf()
Definition: guiutil.cpp:423
GUIUtil::PopupMenu
void PopupMenu(QMenu *menu, const QPoint &point, QAction *at_action)
Call QMenu::popup() only on supported QT_QPA_PLATFORM.
Definition: guiutil.cpp:924
assert
assert(!tx.IsCoinBase())
check.h
GUIUtil::ClickableLabel
Definition: guiutil.h:260
fs.h
GUIUtil::ToolTipToRichTextFilter::ToolTipToRichTextFilter
ToolTipToRichTextFilter(int size_threshold, QObject *parent=nullptr)
Definition: guiutil.cpp:447
GUIUtil::SetStartOnSystemStartup
bool SetStartOnSystemStartup(bool fAutoStart)
Definition: guiutil.cpp:641
GUIUtil::ItemDelegate::ItemDelegate
ItemDelegate(QObject *parent)
Definition: guiutil.h:295
GUIUtil::ItemDelegate::eventFilter
bool eventFilter(QObject *object, QEvent *event) override
Definition: guiutil.cpp:858
source
const char * source
Definition: rpcconsole.cpp:63
GUIUtil::ClickableProgressBar::clicked
void clicked(const QPoint &point)
Emitted when the progressbar is clicked.
GUIUtil::ClickableProgressBar
Definition: guiutil.h:276
GUIUtil
Utility functions used by the Bitcoin Qt UI.
Definition: bitcoingui.h:59
GUIUtil::openDebugLogfile
void openDebugLogfile()
Definition: guiutil.cpp:414
GUIUtil::hasEntryData
bool hasEntryData(const QAbstractItemView *view, int column, int role)
Returns true if the specified field of the currently selected view entry is not empty.
Definition: guiutil.cpp:268
GUIUtil::parseBitcoinURI
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
Definition: guiutil.cpp:132
GUIUtil::formatBitcoinURI
QString formatBitcoinURI(const SendCoinsRecipient &info)
Definition: guiutil.cpp:195
GUIUtil::ExceptionSafeConnect
auto ExceptionSafeConnect(Sender sender, Signal signal, Receiver receiver, Slot method, Qt::ConnectionType type=Qt::AutoConnection)
A drop-in replacement of QObject::connect function (see: https://doc.qt.io/qt-5/qobject....
Definition: guiutil.h:392
GUIUtil::ItemDelegate
Definition: guiutil.h:291
GUIUtil::bringToFront
void bringToFront(QWidget *w)
Definition: guiutil.cpp:391
Network
Network
A network type.
Definition: netaddress.h:45
GUIUtil::qstringToBoostPath
fs::path qstringToBoostPath(const QString &path)
Convert QString to OS specific boost path through UTF-8.
Definition: guiutil.cpp:654
GUIUtil::ItemDelegate::keyEscapePressed
void keyEscapePressed()
GUIUtil::dialog_flags
constexpr auto dialog_flags
Definition: guiutil.h:60
GUIUtil::isObscured
bool isObscured(QWidget *w)
Definition: guiutil.cpp:382
GUIUtil::setClipboard
void setClipboard(const QString &str)
Definition: guiutil.cpp:645
GUIUtil::ClickableLabel::ClickableLabel
ClickableLabel(const PlatformStyle *platform_style, QWidget *parent=nullptr)
Definition: guiutil.cpp:843
GUIUtil::ObjectInvoke
void ObjectInvoke(QObject *object, Fn &&function, Qt::ConnectionType connection=Qt::QueuedConnection)
Queue a function to run in an object's event loop.
Definition: guiutil.h:368
GUIUtil::GetImage
QImage GetImage(const QLabel *label)
Definition: guiutil.cpp:949
GUIUtil::LabelOutOfFocusEventFilter
Qt event filter that intercepts QEvent::FocusOut events for QLabel objects, and resets their ‘textInt...
Definition: guiutil.h:199
GUIUtil::ThemedLabel::m_pixmap_width
int m_pixmap_width
Definition: guiutil.h:255
SendCoinsRecipient
Definition: sendcoinsrecipient.h:19
GUIUtil::ConnectionTypeToQString
QString ConnectionTypeToQString(ConnectionType conn_type, bool prepend_direction)
Convert enum ConnectionType to QString.
Definition: guiutil.cpp:679
GUIUtil::ThemedLabel
Definition: guiutil.h:241
GUIUtil::formatTimeOffset
QString formatTimeOffset(int64_t nTimeOffset)
Format a CNodeCombinedStats.nTimeOffset into a user-readable string.
Definition: guiutil.cpp:749
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:332
GUIUtil::formatNiceTimeOffset
QString formatNiceTimeOffset(qint64 secs)
Definition: guiutil.cpp:754
GUIUtil::StartOfDay
QDateTime StartOfDay(const QDate &date)
Returns the start-moment of the day in local time.
Definition: guiutil.cpp:931
fs::path
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
Definition: fs.h:33
GUIUtil::ClickableLabel::clicked
void clicked(const QPoint &point)
Emitted when the label is clicked.
GUIUtil::PrintSlotException
void PrintSlotException(const std::exception *exception, const QObject *sender, const QObject *receiver)
Definition: guiutil.cpp:969
GUIUtil::ClickableLabel::mouseReleaseEvent
void mouseReleaseEvent(QMouseEvent *event) override
Definition: guiutil.cpp:848
netaddress.h
GUIUtil::LabelOutOfFocusEventFilter::eventFilter
bool eventFilter(QObject *watched, QEvent *event) override
Definition: guiutil.cpp:477
GUIUtil::ThemedLabel::changeEvent
void changeEvent(QEvent *e) override
Definition: guiutil.cpp:829
GUIUtil::PolishProgressDialog
void PolishProgressDialog(QProgressDialog *dialog)
Definition: guiutil.cpp:868
CAmount
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
QValidatedLineEdit
Line edit that can be marked as "invalid" to show input validation feedback.
Definition: qvalidatedlineedit.h:13
GUIUtil::AddButtonShortcut
void AddButtonShortcut(QAbstractButton *button, const QKeySequence &shortcut)
Connects an additional shortcut to a QAbstractButton.
Definition: guiutil.cpp:127
GUIUtil::formatBytes
QString formatBytes(uint64_t bytes)
Definition: guiutil.cpp:791
GUIUtil::formatServicesStr
QString formatServicesStr(quint64 mask)
Format CNodeStats.nServices bitmask into a user-readable string.
Definition: guiutil.cpp:728
GUIUtil::fixedPitchFont
QFont fixedPitchFont(bool use_embedded_font)
Definition: guiutil.cpp:88
GUIUtil::MakeHtmlLink
QString MakeHtmlLink(const QString &source, const QString &link)
Replaces a plain text link with an HTML tagged one.
Definition: guiutil.cpp:962
GUIUtil::getDefaultDataDirectory
QString getDefaultDataDirectory()
Determine default data directory for operating system.
Definition: guiutil.cpp:281
interfaces::Node
Top-level interface for a bitcoin node (bitcoind process).
Definition: node.h:54
GUIUtil::HasPixmap
bool HasPixmap(const QLabel *label)
Returns true if pixmap has been set.
Definition: guiutil.cpp:940
GUIUtil::ToolTipToRichTextFilter::eventFilter
bool eventFilter(QObject *obj, QEvent *evt) override
Definition: guiutil.cpp:454
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:286
GUIUtil::ThemedLabel::m_pixmap_height
int m_pixmap_height
Definition: guiutil.h:256
GUIUtil::LabelOutOfFocusEventFilter::LabelOutOfFocusEventFilter
LabelOutOfFocusEventFilter(QObject *parent)
Definition: guiutil.cpp:472
GUIUtil::GetStartOnSystemStartup
bool GetStartOnSystemStartup()
Definition: guiutil.cpp:640
GUIUtil::ThemedLabel::m_image_filename
QString m_image_filename
Definition: guiutil.h:254
GUIUtil::HtmlEscape
QString HtmlEscape(const QString &str, bool fMultiLine)
Definition: guiutil.cpp:233
GUIUtil::copyEntryData
void copyEntryData(const QAbstractItemView *view, int column, int role)
Copy a field of the currently selected entry of a view to the clipboard.
Definition: guiutil.cpp:248
GUIUtil::ThemedLabel::ThemedLabel
ThemedLabel(const PlatformStyle *platform_style, QWidget *parent=nullptr)
Definition: guiutil.cpp:815
GUIUtil::ToolTipToRichTextFilter::size_threshold
int size_threshold
Definition: guiutil.h:190
GUIUtil::SplitSkipEmptyParts
QStringList SplitSkipEmptyParts(const QString &string, const SeparatorType &separator)
Splits the string into substrings wherever separator occurs, and returns the list of those strings.
Definition: guiutil.h:352
GUIUtil::blockingGUIThreadConnection
Qt::ConnectionType blockingGUIThreadConnection()
Get connection type to call object slot in GUI thread with invokeMethod.
Definition: guiutil.cpp:363
GUIUtil::NetworkToQString
QString NetworkToQString(Network net)
Convert enum Network to QString.
Definition: guiutil.cpp:664
GUIUtil::LogQtInfo
void LogQtInfo()
Writes to debug.log short info about the used Qt and the host system.
Definition: guiutil.cpp:891
node
Definition: interfaces.cpp:68
GUIUtil::ClickableProgressBar::mouseReleaseEvent
void mouseReleaseEvent(QMouseEvent *event) override
Definition: guiutil.cpp:853
GUIUtil::ShowModalDialogAndDeleteOnClose
void ShowModalDialogAndDeleteOnClose(QDialog *dialog)
Shows a QDialog instance asynchronously, and deletes it on close.
Definition: guiutil.cpp:980
GUIUtil::calculateIdealFontSize
qreal calculateIdealFontSize(int width, const QString &text, QFont font, qreal minPointSize, qreal font_size)
Definition: guiutil.cpp:803
GUIUtil::isDust
bool isDust(interfaces::Node &node, const QString &address, const CAmount &amount)
Definition: guiutil.cpp:225
GUIUtil::formatDurationStr
QString formatDurationStr(int secs)
Convert seconds into a QString with days, hours, mins, secs.
Definition: guiutil.cpp:708
GUIUtil::TextWidth
int TextWidth(const QFontMetrics &fm, const QString &text)
Returns the distance in pixels appropriate for drawing a subsequent character after text.
Definition: guiutil.cpp:882
GUIUtil::dateTimeStr
QString dateTimeStr(const QDateTime &date)
Definition: guiutil.cpp:78
GUIUtil::handleCloseWindowShortcut
void handleCloseWindowShortcut(QWidget *w)
Definition: guiutil.cpp:409
GUIUtil::getEntryData
QList< QModelIndex > getEntryData(const QAbstractItemView *view, int column)
Return a field of the currently selected entry as a QString.
Definition: guiutil.cpp:261
GUIUtil::ThemedLabel::setThemedPixmap
void setThemedPixmap(const QString &image_filename, int width, int height)
Definition: guiutil.cpp:821
GUIUtil::LoadFont
void LoadFont(const QString &file_name)
Loads the font from the file specified by file_name, aborts if it fails.
Definition: guiutil.cpp:275
PlatformStyle
Definition: platformstyle.h:13
GUIUtil::formatPingTime
QString formatPingTime(std::chrono::microseconds ping_time)
Format a CNodeStats.m_last_ping_time into a user-readable string or display N/A, if 0.
Definition: guiutil.cpp:742
GUIUtil::setupAddressWidget
void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent)
Definition: guiutil.cpp:114
amount.h
GUIUtil::ThemedLabel::m_platform_style
const PlatformStyle * m_platform_style
Definition: guiutil.h:253
ConnectionType
ConnectionType
Different types of connections to a peer.
Definition: net.h:120
GUIUtil::ProgressBar
ClickableProgressBar ProgressBar
Definition: guiutil.h:289
GUIUtil::ThemedLabel::updateThemedPixmap
void updateThemedPixmap()
Definition: guiutil.cpp:838
NonFatalCheckError
Definition: check.h:16