Bitcoin Core  23.99.0
P2P Digital Currency
guiutil.h
Go to the documentation of this file.
1 // Copyright (c) 2011-2021 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 
132  QString ExtractFirstSuffixFromFilter(const QString& filter);
133 
144  QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir,
145  const QString &filter,
146  QString *selectedSuffixOut);
147 
157  QString getOpenFileName(QWidget *parent, const QString &caption, const QString &dir,
158  const QString &filter,
159  QString *selectedSuffixOut);
160 
167 
168  // Determine whether a widget is hidden behind other windows
169  bool isObscured(QWidget *w);
170 
171  // Activate, show and raise the widget
172  void bringToFront(QWidget* w);
173 
174  // Set shortcut to close window
175  void handleCloseWindowShortcut(QWidget* w);
176 
177  // Open debug.log
178  void openDebugLogfile();
179 
180  // Open the config file
181  bool openBitcoinConf();
182 
187  class ToolTipToRichTextFilter : public QObject
188  {
189  Q_OBJECT
190 
191  public:
192  explicit ToolTipToRichTextFilter(int size_threshold, QObject *parent = nullptr);
193 
194  protected:
195  bool eventFilter(QObject *obj, QEvent *evt) override;
196 
197  private:
199  };
200 
207  class LabelOutOfFocusEventFilter : public QObject
208  {
209  Q_OBJECT
210 
211  public:
212  explicit LabelOutOfFocusEventFilter(QObject* parent);
213  bool eventFilter(QObject* watched, QEvent* event) override;
214  };
215 
217  bool SetStartOnSystemStartup(bool fAutoStart);
218 
220  fs::path QStringToPath(const QString &path);
221 
223  QString PathToQString(const fs::path &path);
224 
226  QString NetworkToQString(Network net);
227 
229  QString ConnectionTypeToQString(ConnectionType conn_type, bool prepend_direction);
230 
232  QString formatDurationStr(std::chrono::seconds dur);
233 
235  QString FormatPeerAge(std::chrono::seconds time_connected);
236 
238  QString formatServicesStr(quint64 mask);
239 
241  QString formatPingTime(std::chrono::microseconds ping_time);
242 
244  QString formatTimeOffset(int64_t nTimeOffset);
245 
246  QString formatNiceTimeOffset(qint64 secs);
247 
248  QString formatBytes(uint64_t bytes);
249 
250  qreal calculateIdealFontSize(int width, const QString& text, QFont font, qreal minPointSize = 4, qreal startPointSize = 14);
251 
252  class ThemedLabel : public QLabel
253  {
254  Q_OBJECT
255 
256  public:
257  explicit ThemedLabel(const PlatformStyle* platform_style, QWidget* parent = nullptr);
258  void setThemedPixmap(const QString& image_filename, int width, int height);
259 
260  protected:
261  void changeEvent(QEvent* e) override;
262 
263  private:
268  void updateThemedPixmap();
269  };
270 
272  {
273  Q_OBJECT
274 
275  public:
276  explicit ClickableLabel(const PlatformStyle* platform_style, QWidget* parent = nullptr);
277 
278  Q_SIGNALS:
282  void clicked(const QPoint& point);
283  protected:
284  void mouseReleaseEvent(QMouseEvent *event) override;
285  };
286 
287  class ClickableProgressBar : public QProgressBar
288  {
289  Q_OBJECT
290 
291  Q_SIGNALS:
295  void clicked(const QPoint& point);
296  protected:
297  void mouseReleaseEvent(QMouseEvent *event) override;
298  };
299 
301 
302  class ItemDelegate : public QItemDelegate
303  {
304  Q_OBJECT
305  public:
306  ItemDelegate(QObject* parent) : QItemDelegate(parent) {}
307 
308  Q_SIGNALS:
309  void keyEscapePressed();
310 
311  private:
312  bool eventFilter(QObject *object, QEvent *event) override;
313  };
314 
315  // Fix known bugs in QProgressDialog class.
316  void PolishProgressDialog(QProgressDialog* dialog);
317 
324  int TextWidth(const QFontMetrics& fm, const QString& text);
325 
329  void LogQtInfo();
330 
334  void PopupMenu(QMenu* menu, const QPoint& point, QAction* at_action = nullptr);
335 
342  QDateTime StartOfDay(const QDate& date);
343 
349  bool HasPixmap(const QLabel* label);
350  QImage GetImage(const QLabel* label);
351 
362  template <typename SeparatorType>
363  QStringList SplitSkipEmptyParts(const QString& string, const SeparatorType& separator)
364  {
365  #if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
366  return string.split(separator, Qt::SkipEmptyParts);
367  #else
368  return string.split(separator, QString::SkipEmptyParts);
369  #endif
370  }
371 
372 
376  QString MakeHtmlLink(const QString& source, const QString& link);
377 
378  void PrintSlotException(
379  const std::exception* exception,
380  const QObject* sender,
381  const QObject* receiver);
382 
390  template <typename Sender, typename Signal, typename Receiver, typename Slot>
392  Sender sender, Signal signal, Receiver receiver, Slot method,
393  Qt::ConnectionType type = Qt::AutoConnection)
394  {
395  return QObject::connect(
396  sender, signal, receiver,
397  [sender, receiver, method](auto&&... args) {
398  bool ok{true};
399  try {
400  (receiver->*method)(std::forward<decltype(args)>(args)...);
401  } catch (const NonFatalCheckError& e) {
402  PrintSlotException(&e, sender, receiver);
403  ok = QMetaObject::invokeMethod(
404  qApp, "handleNonFatalException",
406  Q_ARG(QString, QString::fromStdString(e.what())));
407  } catch (const std::exception& e) {
408  PrintSlotException(&e, sender, receiver);
409  ok = QMetaObject::invokeMethod(
410  qApp, "handleRunawayException",
412  Q_ARG(QString, QString::fromStdString(e.what())));
413  } catch (...) {
414  PrintSlotException(nullptr, sender, receiver);
415  ok = QMetaObject::invokeMethod(
416  qApp, "handleRunawayException",
418  Q_ARG(QString, "Unknown failure occurred."));
419  }
420  assert(ok);
421  },
422  type);
423  }
424 
428  void ShowModalDialogAsynchronously(QDialog* dialog);
429 
430  inline bool IsEscapeOrBack(int key)
431  {
432  if (key == Qt::Key_Escape) return true;
433 #ifdef Q_OS_ANDROID
434  if (key == Qt::Key_Back) return true;
435 #endif // Q_OS_ANDROID
436  return false;
437  }
438 
439 } // namespace GUIUtil
440 
441 #endif // BITCOIN_QT_GUIUTIL_H
interfaces
Definition: dummywallet.cpp:10
GUIUtil::PathToQString
QString PathToQString(const fs::path &path)
Convert OS specific boost path to QString through UTF-8.
Definition: guiutil.cpp:665
GUIUtil::ToolTipToRichTextFilter
Qt event filter that intercepts ToolTipChange events, and replaces the tooltip with a rich text repre...
Definition: guiutil.h:187
GUIUtil::openBitcoinConf
bool openBitcoinConf()
Definition: guiutil.cpp:429
GUIUtil::PopupMenu
void PopupMenu(QMenu *menu, const QPoint &point, QAction *at_action)
Call QMenu::popup() only on supported QT_QPA_PLATFORM.
Definition: guiutil.cpp:932
assert
assert(!tx.IsCoinBase())
check.h
GUIUtil::ClickableLabel
Definition: guiutil.h:271
GUIUtil::QStringToPath
fs::path QStringToPath(const QString &path)
Convert QString to OS specific boost path through UTF-8.
Definition: guiutil.cpp:660
fs.h
GUIUtil::ToolTipToRichTextFilter::ToolTipToRichTextFilter
ToolTipToRichTextFilter(int size_threshold, QObject *parent=nullptr)
Definition: guiutil.cpp:453
GUIUtil::SetStartOnSystemStartup
bool SetStartOnSystemStartup(bool fAutoStart)
Definition: guiutil.cpp:647
GUIUtil::ItemDelegate::ItemDelegate
ItemDelegate(QObject *parent)
Definition: guiutil.h:306
GUIUtil::ItemDelegate::eventFilter
bool eventFilter(QObject *object, QEvent *event) override
Definition: guiutil.cpp:870
source
const char * source
Definition: rpcconsole.cpp:59
GUIUtil::ClickableProgressBar::clicked
void clicked(const QPoint &point)
Emitted when the progressbar is clicked.
GUIUtil::ClickableProgressBar
Definition: guiutil.h:287
GUIUtil
Utility functions used by the Bitcoin Qt UI.
Definition: bitcoingui.h:60
GUIUtil::openDebugLogfile
void openDebugLogfile()
Definition: guiutil.cpp:420
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:275
GUIUtil::parseBitcoinURI
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
Definition: guiutil.cpp:140
GUIUtil::ExtractFirstSuffixFromFilter
QString ExtractFirstSuffixFromFilter(const QString &filter)
Extract first suffix from filter pattern "Description (*.foo)" or "Description (*....
Definition: guiutil.cpp:293
GUIUtil::formatBitcoinURI
QString formatBitcoinURI(const SendCoinsRecipient &info)
Definition: guiutil.cpp:202
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:391
GUIUtil::ItemDelegate
Definition: guiutil.h:302
GUIUtil::bringToFront
void bringToFront(QWidget *w)
Definition: guiutil.cpp:397
Network
Network
A network type.
Definition: netaddress.h:44
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:388
GUIUtil::setClipboard
void setClipboard(const QString &str)
Definition: guiutil.cpp:651
GUIUtil::ClickableLabel::ClickableLabel
ClickableLabel(const PlatformStyle *platform_style, QWidget *parent=nullptr)
Definition: guiutil.cpp:855
GUIUtil::GetImage
QImage GetImage(const QLabel *label)
Definition: guiutil.cpp:957
GUIUtil::LabelOutOfFocusEventFilter
Qt event filter that intercepts QEvent::FocusOut events for QLabel objects, and resets their ‘textInt...
Definition: guiutil.h:207
GUIUtil::ThemedLabel::m_pixmap_width
int m_pixmap_width
Definition: guiutil.h:266
SendCoinsRecipient
Definition: sendcoinsrecipient.h:19
GUIUtil::ConnectionTypeToQString
QString ConnectionTypeToQString(ConnectionType conn_type, bool prepend_direction)
Convert enum ConnectionType to QString.
Definition: guiutil.cpp:685
GUIUtil::ShowModalDialogAsynchronously
void ShowModalDialogAsynchronously(QDialog *dialog)
Shows a QDialog instance asynchronously, and deletes it on close.
Definition: guiutil.cpp:988
GUIUtil::ThemedLabel
Definition: guiutil.h:252
GUIUtil::formatTimeOffset
QString formatTimeOffset(int64_t nTimeOffset)
Format a CNodeCombinedStats.nTimeOffset into a user-readable string.
Definition: guiutil.cpp:761
GUIUtil::formatDurationStr
QString formatDurationStr(std::chrono::seconds dur)
Convert seconds into a QString with days, hours, mins, secs.
Definition: guiutil.cpp:714
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:344
GUIUtil::formatNiceTimeOffset
QString formatNiceTimeOffset(qint64 secs)
Definition: guiutil.cpp:766
GUIUtil::StartOfDay
QDateTime StartOfDay(const QDate &date)
Returns the start-moment of the day in local time.
Definition: guiutil.cpp:939
fs::path
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
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:977
GUIUtil::ClickableLabel::mouseReleaseEvent
void mouseReleaseEvent(QMouseEvent *event) override
Definition: guiutil.cpp:860
netaddress.h
GUIUtil::LabelOutOfFocusEventFilter::eventFilter
bool eventFilter(QObject *watched, QEvent *event) override
Definition: guiutil.cpp:483
GUIUtil::ThemedLabel::changeEvent
void changeEvent(QEvent *e) override
Definition: guiutil.cpp:841
GUIUtil::PolishProgressDialog
void PolishProgressDialog(QProgressDialog *dialog)
Definition: guiutil.cpp:880
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:135
ConnectionType
ConnectionType
Different types of connections to a peer.
Definition: connection_types.h:17
GUIUtil::formatBytes
QString formatBytes(uint64_t bytes)
Definition: guiutil.cpp:803
GUIUtil::formatServicesStr
QString formatServicesStr(quint64 mask)
Format CNodeStats.nServices bitmask into a user-readable string.
Definition: guiutil.cpp:740
GUIUtil::fixedPitchFont
QFont fixedPitchFont(bool use_embedded_font)
Definition: guiutil.cpp:96
GUIUtil::MakeHtmlLink
QString MakeHtmlLink(const QString &source, const QString &link)
Replaces a plain text link with an HTML tagged one.
Definition: guiutil.cpp:970
GUIUtil::getDefaultDataDirectory
QString getDefaultDataDirectory()
Determine default data directory for operating system.
Definition: guiutil.cpp:288
interfaces::Node
Top-level interface for a bitcoin node (bitcoind process).
Definition: node.h:69
GUIUtil::HasPixmap
bool HasPixmap(const QLabel *label)
Returns true if pixmap has been set.
Definition: guiutil.cpp:948
GUIUtil::ToolTipToRichTextFilter::eventFilter
bool eventFilter(QObject *obj, QEvent *evt) override
Definition: guiutil.cpp:460
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:304
GUIUtil::ThemedLabel::m_pixmap_height
int m_pixmap_height
Definition: guiutil.h:267
GUIUtil::LabelOutOfFocusEventFilter::LabelOutOfFocusEventFilter
LabelOutOfFocusEventFilter(QObject *parent)
Definition: guiutil.cpp:478
GUIUtil::GetStartOnSystemStartup
bool GetStartOnSystemStartup()
Definition: guiutil.cpp:646
GUIUtil::ThemedLabel::m_image_filename
QString m_image_filename
Definition: guiutil.h:265
GUIUtil::HtmlEscape
QString HtmlEscape(const QString &str, bool fMultiLine)
Definition: guiutil.cpp:240
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:255
GUIUtil::ThemedLabel::ThemedLabel
ThemedLabel(const PlatformStyle *platform_style, QWidget *parent=nullptr)
Definition: guiutil.cpp:827
GUIUtil::IsEscapeOrBack
bool IsEscapeOrBack(int key)
Definition: guiutil.h:430
GUIUtil::ToolTipToRichTextFilter::size_threshold
int size_threshold
Definition: guiutil.h:198
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:363
GUIUtil::blockingGUIThreadConnection
Qt::ConnectionType blockingGUIThreadConnection()
Get connection type to call object slot in GUI thread with invokeMethod.
Definition: guiutil.cpp:369
GUIUtil::NetworkToQString
QString NetworkToQString(Network net)
Convert enum Network to QString.
Definition: guiutil.cpp:670
GUIUtil::LogQtInfo
void LogQtInfo()
Writes to debug.log short info about the used Qt and the host system.
Definition: guiutil.cpp:899
node
Definition: init.h:25
GUIUtil::ClickableProgressBar::mouseReleaseEvent
void mouseReleaseEvent(QMouseEvent *event) override
Definition: guiutil.cpp:865
GUIUtil::calculateIdealFontSize
qreal calculateIdealFontSize(int width, const QString &text, QFont font, qreal minPointSize, qreal font_size)
Definition: guiutil.cpp:815
GUIUtil::isDust
bool isDust(interfaces::Node &node, const QString &address, const CAmount &amount)
Definition: guiutil.cpp:232
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:894
GUIUtil::dateTimeStr
QString dateTimeStr(const QDateTime &date)
Definition: guiutil.cpp:86
GUIUtil::handleCloseWindowShortcut
void handleCloseWindowShortcut(QWidget *w)
Definition: guiutil.cpp:415
GUIUtil::getEntryData
QList< QModelIndex > getEntryData(const QAbstractItemView *view, int column)
Return a field of the currently selected entry as a QString.
Definition: guiutil.cpp:268
GUIUtil::ThemedLabel::setThemedPixmap
void setThemedPixmap(const QString &image_filename, int width, int height)
Definition: guiutil.cpp:833
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:282
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:754
GUIUtil::setupAddressWidget
void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent)
Definition: guiutil.cpp:122
amount.h
GUIUtil::ThemedLabel::m_platform_style
const PlatformStyle * m_platform_style
Definition: guiutil.h:264
GUIUtil::ProgressBar
ClickableProgressBar ProgressBar
Definition: guiutil.h:300
GUIUtil::ThemedLabel::updateThemedPixmap
void updateThemedPixmap()
Definition: guiutil.cpp:850
args
ArgsManager args
Definition: notifications.cpp:36
GUIUtil::FormatPeerAge
QString FormatPeerAge(std::chrono::seconds time_connected)
Convert peer connection time to a QString denominated in the most relevant unit.
Definition: guiutil.cpp:730
NonFatalCheckError
Definition: check.h:16