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 <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 QFont;
45 class QKeySequence;
46 class QLineEdit;
47 class QMenu;
48 class QPoint;
49 class QProgressDialog;
50 class QUrl;
51 class QWidget;
52 QT_END_NAMESPACE
53 
56 namespace GUIUtil
57 {
58  // Use this flags to prevent a "What's This" button in the title bar of the dialog on Windows.
59  constexpr auto dialog_flags = Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
60 
61  // Create human-readable string from date
62  QString dateTimeStr(const QDateTime &datetime);
63  QString dateTimeStr(qint64 nTime);
64 
65  // Return a monospace font
66  QFont fixedPitchFont(bool use_embedded_font = false);
67 
68  // Set up widget for address
69  void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent);
70 
77  void AddButtonShortcut(QAbstractButton* button, const QKeySequence& shortcut);
78 
79  // Parse "bitcoin:" URI into recipient object, return true on successful parsing
80  bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out);
81  bool parseBitcoinURI(QString uri, SendCoinsRecipient *out);
82  QString formatBitcoinURI(const SendCoinsRecipient &info);
83 
84  // Returns true if given address+amount meets "dust" definition
85  bool isDust(interfaces::Node& node, const QString& address, const CAmount& amount);
86 
87  // HTML escaping for rich text controls
88  QString HtmlEscape(const QString& str, bool fMultiLine=false);
89  QString HtmlEscape(const std::string& str, bool fMultiLine=false);
90 
97  void copyEntryData(const QAbstractItemView *view, int column, int role=Qt::EditRole);
98 
104  QList<QModelIndex> getEntryData(const QAbstractItemView *view, int column);
105 
111  bool hasEntryData(const QAbstractItemView *view, int column, int role);
112 
113  void setClipboard(const QString& str);
114 
118  QString getDefaultDataDirectory();
119 
130  QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir,
131  const QString &filter,
132  QString *selectedSuffixOut);
133 
143  QString getOpenFileName(QWidget *parent, const QString &caption, const QString &dir,
144  const QString &filter,
145  QString *selectedSuffixOut);
146 
153 
154  // Determine whether a widget is hidden behind other windows
155  bool isObscured(QWidget *w);
156 
157  // Activate, show and raise the widget
158  void bringToFront(QWidget* w);
159 
160  // Set shortcut to close window
161  void handleCloseWindowShortcut(QWidget* w);
162 
163  // Open debug.log
164  void openDebugLogfile();
165 
166  // Open the config file
167  bool openBitcoinConf();
168 
173  class ToolTipToRichTextFilter : public QObject
174  {
175  Q_OBJECT
176 
177  public:
178  explicit ToolTipToRichTextFilter(int size_threshold, QObject *parent = nullptr);
179 
180  protected:
181  bool eventFilter(QObject *obj, QEvent *evt) override;
182 
183  private:
185  };
186 
193  class LabelOutOfFocusEventFilter : public QObject
194  {
195  Q_OBJECT
196 
197  public:
198  explicit LabelOutOfFocusEventFilter(QObject* parent);
199  bool eventFilter(QObject* watched, QEvent* event) override;
200  };
201 
203  bool SetStartOnSystemStartup(bool fAutoStart);
204 
206  fs::path qstringToBoostPath(const QString &path);
207 
209  QString boostPathToQString(const fs::path &path);
210 
212  QString NetworkToQString(Network net);
213 
215  QString ConnectionTypeToQString(ConnectionType conn_type, bool prepend_direction);
216 
218  QString formatDurationStr(int secs);
219 
221  QString formatServicesStr(quint64 mask);
222 
224  QString formatPingTime(std::chrono::microseconds ping_time);
225 
227  QString formatTimeOffset(int64_t nTimeOffset);
228 
229  QString formatNiceTimeOffset(qint64 secs);
230 
231  QString formatBytes(uint64_t bytes);
232 
233  qreal calculateIdealFontSize(int width, const QString& text, QFont font, qreal minPointSize = 4, qreal startPointSize = 14);
234 
235  class ThemedLabel : public QLabel
236  {
237  Q_OBJECT
238 
239  public:
240  explicit ThemedLabel(const PlatformStyle* platform_style, QWidget* parent = nullptr);
241  void setThemedPixmap(const QString& image_filename, int width, int height);
242 
243  protected:
244  void changeEvent(QEvent* e) override;
245 
246  private:
251  void updateThemedPixmap();
252  };
253 
255  {
256  Q_OBJECT
257 
258  public:
259  explicit ClickableLabel(const PlatformStyle* platform_style, QWidget* parent = nullptr);
260 
261  Q_SIGNALS:
265  void clicked(const QPoint& point);
266  protected:
267  void mouseReleaseEvent(QMouseEvent *event) override;
268  };
269 
270  class ClickableProgressBar : public QProgressBar
271  {
272  Q_OBJECT
273 
274  Q_SIGNALS:
278  void clicked(const QPoint& point);
279  protected:
280  void mouseReleaseEvent(QMouseEvent *event) override;
281  };
282 
284 
285  class ItemDelegate : public QItemDelegate
286  {
287  Q_OBJECT
288  public:
289  ItemDelegate(QObject* parent) : QItemDelegate(parent) {}
290 
291  Q_SIGNALS:
292  void keyEscapePressed();
293 
294  private:
295  bool eventFilter(QObject *object, QEvent *event) override;
296  };
297 
298  // Fix known bugs in QProgressDialog class.
299  void PolishProgressDialog(QProgressDialog* dialog);
300 
307  int TextWidth(const QFontMetrics& fm, const QString& text);
308 
312  void LogQtInfo();
313 
317  void PopupMenu(QMenu* menu, const QPoint& point, QAction* at_action = nullptr);
318 
325  QDateTime StartOfDay(const QDate& date);
326 
332  bool HasPixmap(const QLabel* label);
333  QImage GetImage(const QLabel* label);
334 
345  template <typename SeparatorType>
346  QStringList SplitSkipEmptyParts(const QString& string, const SeparatorType& separator)
347  {
348  #if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
349  return string.split(separator, Qt::SkipEmptyParts);
350  #else
351  return string.split(separator, QString::SkipEmptyParts);
352  #endif
353  }
354 
361  template <typename Fn>
362  void ObjectInvoke(QObject* object, Fn&& function, Qt::ConnectionType connection = Qt::QueuedConnection)
363  {
364  QObject source;
365  QObject::connect(&source, &QObject::destroyed, object, std::forward<Fn>(function), connection);
366  }
367 
371  QString MakeHtmlLink(const QString& source, const QString& link);
372 
373  void PrintSlotException(
374  const std::exception* exception,
375  const QObject* sender,
376  const QObject* receiver);
377 
385  template <typename Sender, typename Signal, typename Receiver, typename Slot>
387  Sender sender, Signal signal, Receiver receiver, Slot method,
388  Qt::ConnectionType type = Qt::AutoConnection)
389  {
390  return QObject::connect(
391  sender, signal, receiver,
392  [sender, receiver, method](auto&&... args) {
393  bool ok{true};
394  try {
395  (receiver->*method)(std::forward<decltype(args)>(args)...);
396  } catch (const NonFatalCheckError& e) {
397  PrintSlotException(&e, sender, receiver);
398  ok = QMetaObject::invokeMethod(
399  qApp, "handleNonFatalException",
401  Q_ARG(QString, QString::fromStdString(e.what())));
402  } catch (const std::exception& e) {
403  PrintSlotException(&e, sender, receiver);
404  ok = QMetaObject::invokeMethod(
405  qApp, "handleRunawayException",
407  Q_ARG(QString, QString::fromStdString(e.what())));
408  } catch (...) {
409  PrintSlotException(nullptr, sender, receiver);
410  ok = QMetaObject::invokeMethod(
411  qApp, "handleRunawayException",
413  Q_ARG(QString, "Unknown failure occurred."));
414  }
415  assert(ok);
416  },
417  type);
418  }
419 
420 } // namespace GUIUtil
421 
422 #endif // BITCOIN_QT_GUIUTIL_H
interfaces
Definition: dummywallet.cpp:10
GUIUtil::ToolTipToRichTextFilter
Qt event filter that intercepts ToolTipChange events, and replaces the tooltip with a rich text repre...
Definition: guiutil.h:173
GUIUtil::boostPathToQString
QString boostPathToQString(const fs::path &path)
Convert OS specific boost path to QString through UTF-8.
Definition: guiutil.cpp:652
GUIUtil::openBitcoinConf
bool openBitcoinConf()
Definition: guiutil.cpp:416
GUIUtil::PopupMenu
void PopupMenu(QMenu *menu, const QPoint &point, QAction *at_action)
Call QMenu::popup() only on supported QT_QPA_PLATFORM.
Definition: guiutil.cpp:905
assert
assert(!tx.IsCoinBase())
check.h
GUIUtil::ClickableLabel
Definition: guiutil.h:254
fs.h
GUIUtil::ToolTipToRichTextFilter::ToolTipToRichTextFilter
ToolTipToRichTextFilter(int size_threshold, QObject *parent=nullptr)
Definition: guiutil.cpp:440
GUIUtil::SetStartOnSystemStartup
bool SetStartOnSystemStartup(bool fAutoStart)
Definition: guiutil.cpp:634
GUIUtil::ItemDelegate::ItemDelegate
ItemDelegate(QObject *parent)
Definition: guiutil.h:289
GUIUtil::ItemDelegate::eventFilter
bool eventFilter(QObject *object, QEvent *event) override
Definition: guiutil.cpp:839
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:270
GUIUtil
Utility functions used by the Bitcoin Qt UI.
Definition: bitcoingui.h:59
GUIUtil::openDebugLogfile
void openDebugLogfile()
Definition: guiutil.cpp:407
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:267
GUIUtil::parseBitcoinURI
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
Definition: guiutil.cpp:131
GUIUtil::formatBitcoinURI
QString formatBitcoinURI(const SendCoinsRecipient &info)
Definition: guiutil.cpp:194
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:386
GUIUtil::ItemDelegate
Definition: guiutil.h:285
GUIUtil::bringToFront
void bringToFront(QWidget *w)
Definition: guiutil.cpp:384
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:647
GUIUtil::ItemDelegate::keyEscapePressed
void keyEscapePressed()
GUIUtil::dialog_flags
constexpr auto dialog_flags
Definition: guiutil.h:59
GUIUtil::isObscured
bool isObscured(QWidget *w)
Definition: guiutil.cpp:375
GUIUtil::setClipboard
void setClipboard(const QString &str)
Definition: guiutil.cpp:638
GUIUtil::ClickableLabel::ClickableLabel
ClickableLabel(const PlatformStyle *platform_style, QWidget *parent=nullptr)
Definition: guiutil.cpp:824
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:362
GUIUtil::GetImage
QImage GetImage(const QLabel *label)
Definition: guiutil.cpp:930
GUIUtil::LabelOutOfFocusEventFilter
Qt event filter that intercepts QEvent::FocusOut events for QLabel objects, and resets their ‘textInt...
Definition: guiutil.h:193
GUIUtil::ThemedLabel::m_pixmap_width
int m_pixmap_width
Definition: guiutil.h:249
SendCoinsRecipient
Definition: sendcoinsrecipient.h:19
GUIUtil::ConnectionTypeToQString
QString ConnectionTypeToQString(ConnectionType conn_type, bool prepend_direction)
Convert enum ConnectionType to QString.
Definition: guiutil.cpp:672
GUIUtil::ThemedLabel
Definition: guiutil.h:235
GUIUtil::formatTimeOffset
QString formatTimeOffset(int64_t nTimeOffset)
Format a CNodeCombinedStats.nTimeOffset into a user-readable string.
Definition: guiutil.cpp:730
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:325
GUIUtil::formatNiceTimeOffset
QString formatNiceTimeOffset(qint64 secs)
Definition: guiutil.cpp:735
GUIUtil::StartOfDay
QDateTime StartOfDay(const QDate &date)
Returns the start-moment of the day in local time.
Definition: guiutil.cpp:912
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:950
GUIUtil::ClickableLabel::mouseReleaseEvent
void mouseReleaseEvent(QMouseEvent *event) override
Definition: guiutil.cpp:829
netaddress.h
GUIUtil::LabelOutOfFocusEventFilter::eventFilter
bool eventFilter(QObject *watched, QEvent *event) override
Definition: guiutil.cpp:470
GUIUtil::ThemedLabel::changeEvent
void changeEvent(QEvent *e) override
Definition: guiutil.cpp:810
GUIUtil::PolishProgressDialog
void PolishProgressDialog(QProgressDialog *dialog)
Definition: guiutil.cpp:849
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:126
GUIUtil::formatBytes
QString formatBytes(uint64_t bytes)
Definition: guiutil.cpp:772
GUIUtil::formatServicesStr
QString formatServicesStr(quint64 mask)
Format CNodeStats.nServices bitmask into a user-readable string.
Definition: guiutil.cpp:709
GUIUtil::fixedPitchFont
QFont fixedPitchFont(bool use_embedded_font)
Definition: guiutil.cpp:87
GUIUtil::MakeHtmlLink
QString MakeHtmlLink(const QString &source, const QString &link)
Replaces a plain text link with an HTML tagged one.
Definition: guiutil.cpp:943
GUIUtil::getDefaultDataDirectory
QString getDefaultDataDirectory()
Determine default data directory for operating system.
Definition: guiutil.cpp:274
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:921
GUIUtil::ToolTipToRichTextFilter::eventFilter
bool eventFilter(QObject *obj, QEvent *evt) override
Definition: guiutil.cpp:447
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:279
GUIUtil::ThemedLabel::m_pixmap_height
int m_pixmap_height
Definition: guiutil.h:250
GUIUtil::LabelOutOfFocusEventFilter::LabelOutOfFocusEventFilter
LabelOutOfFocusEventFilter(QObject *parent)
Definition: guiutil.cpp:465
GUIUtil::GetStartOnSystemStartup
bool GetStartOnSystemStartup()
Definition: guiutil.cpp:633
GUIUtil::ThemedLabel::m_image_filename
QString m_image_filename
Definition: guiutil.h:248
GUIUtil::HtmlEscape
QString HtmlEscape(const QString &str, bool fMultiLine)
Definition: guiutil.cpp:232
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:247
GUIUtil::ThemedLabel::ThemedLabel
ThemedLabel(const PlatformStyle *platform_style, QWidget *parent=nullptr)
Definition: guiutil.cpp:796
GUIUtil::ToolTipToRichTextFilter::size_threshold
int size_threshold
Definition: guiutil.h:184
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:346
GUIUtil::blockingGUIThreadConnection
Qt::ConnectionType blockingGUIThreadConnection()
Get connection type to call object slot in GUI thread with invokeMethod.
Definition: guiutil.cpp:356
GUIUtil::NetworkToQString
QString NetworkToQString(Network net)
Convert enum Network to QString.
Definition: guiutil.cpp:657
GUIUtil::LogQtInfo
void LogQtInfo()
Writes to debug.log short info about the used Qt and the host system.
Definition: guiutil.cpp:872
node
Definition: interfaces.cpp:68
GUIUtil::ClickableProgressBar::mouseReleaseEvent
void mouseReleaseEvent(QMouseEvent *event) override
Definition: guiutil.cpp:834
GUIUtil::calculateIdealFontSize
qreal calculateIdealFontSize(int width, const QString &text, QFont font, qreal minPointSize, qreal font_size)
Definition: guiutil.cpp:784
GUIUtil::isDust
bool isDust(interfaces::Node &node, const QString &address, const CAmount &amount)
Definition: guiutil.cpp:224
GUIUtil::formatDurationStr
QString formatDurationStr(int secs)
Convert seconds into a QString with days, hours, mins, secs.
Definition: guiutil.cpp:689
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:863
GUIUtil::dateTimeStr
QString dateTimeStr(const QDateTime &date)
Definition: guiutil.cpp:77
GUIUtil::handleCloseWindowShortcut
void handleCloseWindowShortcut(QWidget *w)
Definition: guiutil.cpp:402
GUIUtil::getEntryData
QList< QModelIndex > getEntryData(const QAbstractItemView *view, int column)
Return a field of the currently selected entry as a QString.
Definition: guiutil.cpp:260
GUIUtil::ThemedLabel::setThemedPixmap
void setThemedPixmap(const QString &image_filename, int width, int height)
Definition: guiutil.cpp:802
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:723
GUIUtil::setupAddressWidget
void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent)
Definition: guiutil.cpp:113
amount.h
GUIUtil::ThemedLabel::m_platform_style
const PlatformStyle * m_platform_style
Definition: guiutil.h:247
ConnectionType
ConnectionType
Different types of connections to a peer.
Definition: net.h:121
GUIUtil::ProgressBar
ClickableProgressBar ProgressBar
Definition: guiutil.h:283
GUIUtil::ThemedLabel::updateThemedPixmap
void updateThemedPixmap()
Definition: guiutil.cpp:819
NonFatalCheckError
Definition: check.h:16