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
30class PlatformStyle;
33
34namespace interfaces
35{
36 class Node;
37}
38
39QT_BEGIN_NAMESPACE
40class QAbstractButton;
41class QAbstractItemView;
42class QAction;
43class QDateTime;
44class QDialog;
45class QFont;
46class QKeySequence;
47class QLineEdit;
48class QMenu;
49class QPoint;
50class QProgressDialog;
51class QUrl;
52class QWidget;
53QT_END_NAMESPACE
54
57namespace 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
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
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
void mouseReleaseEvent(QMouseEvent *event) override
Definition: guiutil.cpp:848
ClickableLabel(const PlatformStyle *platform_style, QWidget *parent=nullptr)
Definition: guiutil.cpp:843
void clicked(const QPoint &point)
Emitted when the label is clicked.
void mouseReleaseEvent(QMouseEvent *event) override
Definition: guiutil.cpp:853
void clicked(const QPoint &point)
Emitted when the progressbar is clicked.
ItemDelegate(QObject *parent)
Definition: guiutil.h:295
bool eventFilter(QObject *object, QEvent *event) override
Definition: guiutil.cpp:858
Qt event filter that intercepts QEvent::FocusOut events for QLabel objects, and resets their ‘textInt...
Definition: guiutil.h:200
bool eventFilter(QObject *watched, QEvent *event) override
Definition: guiutil.cpp:477
LabelOutOfFocusEventFilter(QObject *parent)
Definition: guiutil.cpp:472
QString m_image_filename
Definition: guiutil.h:254
const PlatformStyle * m_platform_style
Definition: guiutil.h:253
void changeEvent(QEvent *e) override
Definition: guiutil.cpp:829
ThemedLabel(const PlatformStyle *platform_style, QWidget *parent=nullptr)
Definition: guiutil.cpp:815
void setThemedPixmap(const QString &image_filename, int width, int height)
Definition: guiutil.cpp:821
void updateThemedPixmap()
Definition: guiutil.cpp:838
Qt event filter that intercepts ToolTipChange events, and replaces the tooltip with a rich text repre...
Definition: guiutil.h:180
bool eventFilter(QObject *obj, QEvent *evt) override
Definition: guiutil.cpp:454
ToolTipToRichTextFilter(int size_threshold, QObject *parent=nullptr)
Definition: guiutil.cpp:447
Line edit that can be marked as "invalid" to show input validation feedback.
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
Definition: fs.h:34
Top-level interface for a bitcoin node (bitcoind process).
Definition: node.h:55
Utility functions used by the Bitcoin Qt UI.
Definition: bitcoingui.h:59
QString NetworkToQString(Network net)
Convert enum Network to QString.
Definition: guiutil.cpp:664
fs::path qstringToBoostPath(const QString &path)
Convert QString to OS specific boost path through UTF-8.
Definition: guiutil.cpp:654
bool isObscured(QWidget *w)
Definition: guiutil.cpp:382
QImage GetImage(const QLabel *label)
Definition: guiutil.cpp:949
bool openBitcoinConf()
Definition: guiutil.cpp:423
Qt::ConnectionType blockingGUIThreadConnection()
Get connection type to call object slot in GUI thread with invokeMethod.
Definition: guiutil.cpp:363
QString HtmlEscape(const QString &str, bool fMultiLine)
Definition: guiutil.cpp:233
void PopupMenu(QMenu *menu, const QPoint &point, QAction *at_action)
Call QMenu::popup() only on supported QT_QPA_PLATFORM.
Definition: guiutil.cpp:924
QList< QModelIndex > getEntryData(const QAbstractItemView *view, int column)
Return a field of the currently selected entry as a QString.
Definition: guiutil.cpp:261
QFont fixedPitchFont(bool use_embedded_font)
Definition: guiutil.cpp:88
QString formatBytes(uint64_t bytes)
Definition: guiutil.cpp:791
void AddButtonShortcut(QAbstractButton *button, const QKeySequence &shortcut)
Connects an additional shortcut to a QAbstractButton.
Definition: guiutil.cpp:127
QString MakeHtmlLink(const QString &source, const QString &link)
Replaces a plain text link with an HTML tagged one.
Definition: guiutil.cpp:962
void handleCloseWindowShortcut(QWidget *w)
Definition: guiutil.cpp:409
void PolishProgressDialog(QProgressDialog *dialog)
Definition: guiutil.cpp:868
bool isDust(interfaces::Node &node, const QString &address, const CAmount &amount)
Definition: guiutil.cpp:225
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
QString getDefaultDataDirectory()
Determine default data directory for operating system.
Definition: guiutil.cpp:281
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
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
QDateTime StartOfDay(const QDate &date)
Returns the start-moment of the day in local time.
Definition: guiutil.cpp:931
QString boostPathToQString(const fs::path &path)
Convert OS specific boost path to QString through UTF-8.
Definition: guiutil.cpp:659
bool SetStartOnSystemStartup(bool fAutoStart)
Definition: guiutil.cpp:641
ClickableProgressBar ProgressBar
Definition: guiutil.h:289
void bringToFront(QWidget *w)
Definition: guiutil.cpp:391
bool HasPixmap(const QLabel *label)
Returns true if pixmap has been set.
Definition: guiutil.cpp:940
void LogQtInfo()
Writes to debug.log short info about the used Qt and the host system.
Definition: guiutil.cpp:891
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
void openDebugLogfile()
Definition: guiutil.cpp:414
QString dateTimeStr(const QDateTime &date)
Definition: guiutil.cpp:78
QString formatDurationStr(int secs)
Convert seconds into a QString with days, hours, mins, secs.
Definition: guiutil.cpp:708
void LoadFont(const QString &file_name)
Loads the font from the file specified by file_name, aborts if it fails.
Definition: guiutil.cpp:275
void PrintSlotException(const std::exception *exception, const QObject *sender, const QObject *receiver)
Definition: guiutil.cpp:969
QString formatBitcoinURI(const SendCoinsRecipient &info)
Definition: guiutil.cpp:195
QString formatTimeOffset(int64_t nTimeOffset)
Format a CNodeCombinedStats.nTimeOffset into a user-readable string.
Definition: guiutil.cpp:749
QString ConnectionTypeToQString(ConnectionType conn_type, bool prepend_direction)
Convert enum ConnectionType to QString.
Definition: guiutil.cpp:679
QString formatServicesStr(quint64 mask)
Format CNodeStats.nServices bitmask into a user-readable string.
Definition: guiutil.cpp:728
QString formatNiceTimeOffset(qint64 secs)
Definition: guiutil.cpp:754
constexpr auto dialog_flags
Definition: guiutil.h:60
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
Definition: guiutil.cpp:132
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
bool GetStartOnSystemStartup()
Definition: guiutil.cpp:640
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
void ShowModalDialogAndDeleteOnClose(QDialog *dialog)
Shows a QDialog instance asynchronously, and deletes it on close.
Definition: guiutil.cpp:980
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
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
void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent)
Definition: guiutil.cpp:114
void setClipboard(const QString &str)
Definition: guiutil.cpp:645
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
qreal calculateIdealFontSize(int width, const QString &text, QFont font, qreal minPointSize, qreal font_size)
Definition: guiutil.cpp:803
ConnectionType
Different types of connections to a peer.
Definition: net.h:120
Network
A network type.
Definition: netaddress.h:45
const char * source
Definition: rpcconsole.cpp:63
assert(!tx.IsCoinBase())