Bitcoin Core 28.99.0
P2P Digital Currency
guiutil.h
Go to the documentation of this file.
1// Copyright (c) 2011-2022 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 <net.h>
10#include <netaddress.h>
11#include <util/check.h>
12#include <util/fs.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
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 time_offset);
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:
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
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 QString WalletDisplayName(const std::string& name);
440 QString WalletDisplayName(const QString& name);
441
442} // namespace GUIUtil
443
444#endif // BITCOIN_QT_GUIUTIL_H
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
ArgsManager & args
Definition: bitcoind.cpp:277
void mouseReleaseEvent(QMouseEvent *event) override
Definition: guiutil.cpp:881
ClickableLabel(const PlatformStyle *platform_style, QWidget *parent=nullptr)
Definition: guiutil.cpp:876
void clicked(const QPoint &point)
Emitted when the label is clicked.
void mouseReleaseEvent(QMouseEvent *event) override
Definition: guiutil.cpp:886
void clicked(const QPoint &point)
Emitted when the progressbar is clicked.
ItemDelegate(QObject *parent)
Definition: guiutil.h:306
bool eventFilter(QObject *object, QEvent *event) override
Definition: guiutil.cpp:891
Qt event filter that intercepts QEvent::FocusOut events for QLabel objects, and resets their ‘textInt...
Definition: guiutil.h:208
bool eventFilter(QObject *watched, QEvent *event) override
Definition: guiutil.cpp:499
LabelOutOfFocusEventFilter(QObject *parent)
Definition: guiutil.cpp:494
QString m_image_filename
Definition: guiutil.h:265
const PlatformStyle * m_platform_style
Definition: guiutil.h:264
void changeEvent(QEvent *e) override
Definition: guiutil.cpp:862
ThemedLabel(const PlatformStyle *platform_style, QWidget *parent=nullptr)
Definition: guiutil.cpp:848
void setThemedPixmap(const QString &image_filename, int width, int height)
Definition: guiutil.cpp:854
void updateThemedPixmap()
Definition: guiutil.cpp:871
Qt event filter that intercepts ToolTipChange events, and replaces the tooltip with a rich text repre...
Definition: guiutil.h:188
bool eventFilter(QObject *obj, QEvent *evt) override
Definition: guiutil.cpp:476
ToolTipToRichTextFilter(int size_threshold, QObject *parent=nullptr)
Definition: guiutil.cpp:469
Line edit that can be marked as "invalid" to show input validation feedback.
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:33
Top-level interface for a bitcoin node (bitcoind process).
Definition: node.h:71
ConnectionType
Different types of connections to a peer.
Utility functions used by the Bitcoin Qt UI.
Definition: bitcoingui.h:58
QString NetworkToQString(Network net)
Convert enum Network to QString.
Definition: guiutil.cpp:687
bool isObscured(QWidget *w)
Definition: guiutil.cpp:397
QImage GetImage(const QLabel *label)
Definition: guiutil.cpp:973
bool openBitcoinConf()
Definition: guiutil.cpp:445
Qt::ConnectionType blockingGUIThreadConnection()
Get connection type to call object slot in GUI thread with invokeMethod.
Definition: guiutil.cpp:378
QString WalletDisplayName(const QString &name)
Definition: guiutil.cpp:1011
QString HtmlEscape(const QString &str, bool fMultiLine)
Definition: guiutil.cpp:249
void PopupMenu(QMenu *menu, const QPoint &point, QAction *at_action)
Call QMenu::popup() only on supported QT_QPA_PLATFORM.
Definition: guiutil.cpp:948
QList< QModelIndex > getEntryData(const QAbstractItemView *view, int column)
Return a field of the currently selected entry as a QString.
Definition: guiutil.cpp:277
QFont fixedPitchFont(bool use_embedded_font)
Definition: guiutil.cpp:100
QString formatBytes(uint64_t bytes)
Definition: guiutil.cpp:824
void ShowModalDialogAsynchronously(QDialog *dialog)
Shows a QDialog instance asynchronously, and deletes it on close.
Definition: guiutil.cpp:1004
QString formatDurationStr(std::chrono::seconds dur)
Convert seconds into a QString with days, hours, mins, secs.
Definition: guiutil.cpp:736
void AddButtonShortcut(QAbstractButton *button, const QKeySequence &shortcut)
Connects an additional shortcut to a QAbstractButton.
Definition: guiutil.cpp:144
QString MakeHtmlLink(const QString &source, const QString &link)
Replaces a plain text link with an HTML tagged one.
Definition: guiutil.cpp:986
void handleCloseWindowShortcut(QWidget *w)
Definition: guiutil.cpp:431
QString ExtractFirstSuffixFromFilter(const QString &filter)
Extract first suffix from filter pattern "Description (*.foo)" or "Description (*....
Definition: guiutil.cpp:302
void PolishProgressDialog(QProgressDialog *dialog)
Definition: guiutil.cpp:901
bool isDust(interfaces::Node &node, const QString &address, const CAmount &amount)
Definition: guiutil.cpp:241
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:353
QString getDefaultDataDirectory()
Determine default data directory for operating system.
Definition: guiutil.cpp:297
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:264
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:313
QDateTime StartOfDay(const QDate &date)
Returns the start-moment of the day in local time.
Definition: guiutil.cpp:955
bool SetStartOnSystemStartup(bool fAutoStart)
Definition: guiutil.cpp:664
ClickableProgressBar ProgressBar
Definition: guiutil.h:300
void bringToFront(QWidget *w)
Definition: guiutil.cpp:406
bool HasPixmap(const QLabel *label)
Returns true if pixmap has been set.
Definition: guiutil.cpp:964
void LogQtInfo()
Writes to debug.log short info about the used Qt and the host system.
Definition: guiutil.cpp:920
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:775
QString PathToQString(const fs::path &path)
Convert OS specific boost path to QString through UTF-8.
Definition: guiutil.cpp:682
void openDebugLogfile()
Definition: guiutil.cpp:436
QString dateTimeStr(const QDateTime &date)
Definition: guiutil.cpp:90
void LoadFont(const QString &file_name)
Loads the font from the file specified by file_name, aborts if it fails.
Definition: guiutil.cpp:291
void PrintSlotException(const std::exception *exception, const QObject *sender, const QObject *receiver)
Definition: guiutil.cpp:993
QString formatBitcoinURI(const SendCoinsRecipient &info)
Definition: guiutil.cpp:211
QString ConnectionTypeToQString(ConnectionType conn_type, bool prepend_direction)
Convert enum ConnectionType to QString.
Definition: guiutil.cpp:707
QString formatServicesStr(quint64 mask)
Format CNodeStats.nServices bitmask into a user-readable string.
Definition: guiutil.cpp:761
QString formatNiceTimeOffset(qint64 secs)
Definition: guiutil.cpp:787
constexpr auto dialog_flags
Definition: guiutil.h:60
QString FormatPeerAge(std::chrono::seconds time_connected)
Convert peer connection time to a QString denominated in the most relevant unit.
Definition: guiutil.cpp:751
QString formatTimeOffset(int64_t time_offset)
Format a CNodeStateStats.time_offset into a user-readable string.
Definition: guiutil.cpp:782
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
Definition: guiutil.cpp:149
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
bool GetStartOnSystemStartup()
Definition: guiutil.cpp:663
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
int TextWidth(const QFontMetrics &fm, const QString &text)
Returns the distance in pixels appropriate for drawing a subsequent character after text.
Definition: guiutil.cpp:915
void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent)
Definition: guiutil.cpp:131
void setClipboard(const QString &str)
Definition: guiutil.cpp:668
bool IsEscapeOrBack(int key)
Definition: guiutil.h:430
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:284
fs::path QStringToPath(const QString &path)
Convert QString to OS specific boost path through UTF-8.
Definition: guiutil.cpp:677
qreal calculateIdealFontSize(int width, const QString &text, QFont font, qreal minPointSize, qreal font_size)
Definition: guiutil.cpp:836
Definition: messages.h:20
Network
A network type.
Definition: netaddress.h:32
const char * name
Definition: rest.cpp:49
const char * source
Definition: rpcconsole.cpp:62
assert(!tx.IsCoinBase())