swift
Loading...
Searching...
No Matches
statusmessage.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2013 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
5
6#include <algorithm>
7
8#include <QMetaEnum>
9#include <QStringBuilder>
10#include <QThreadStorage>
11
13#include "misc/iconlist.h"
15#include "misc/stringutils.h"
16#include "misc/verify.h"
17
19
20namespace swift::misc
21{
22 namespace private_ns
23 {
24 QThreadStorage<QString> t_tempBuffer; // thread_local would be destroyed before function-scope statics, see T495
25
26 QString arg(QStringView format, const QStringList &args)
27 {
28 if (format.isEmpty())
29 {
30 return args.join(u' ');
31 }
32
33 QString &temp = t_tempBuffer.localData();
34 temp.resize(
35 0); // unlike clear(), resize(0) doesn't release the capacity if there are no implicitly shared copies
36
37 quint64 unusedArgs = (1ULL << std::min(qsizetype(63), args.size())) - 1;
38 for (auto it = format.begin();;)
39 {
40 const auto pc = std::find(it, format.end(), u'%');
41 temp.append(&*it, std::distance(it, pc));
42 if (it = pc; it == format.end())
43 {
44 break;
45 }
46 if (++it == format.end())
47 {
48 temp += u'%';
49 break;
50 }
51
52 if (*it == u'%')
53 {
54 temp += u'%';
55 ++it;
56 continue;
57 }
58 if (is09(*it))
59 {
60 int n = it->unicode() - u'0';
61 SWIFT_VERIFY(n >= 0 && n <= 9);
62 if (++it != format.end() && is09(*it))
63 {
64 n = n * 10 + it->unicode() - u'0';
65 ++it;
66 }
67 SWIFT_VERIFY(n > 0 && n <= 99);
68 if (n > 0 && n <= args.size())
69 {
70 temp += args[n - 1];
71 unusedArgs &= ~(1ULL << (n - 1));
72 }
73 else
74 {
75 temp += u'%' % QString::number(n);
76 }
77 }
78 else
79 {
80 temp += u'%';
81 }
82 }
83 if (unusedArgs)
84 {
85 temp += QStringLiteral(" [SOME MESSAGE ARGUMENT(S) UNUSED]");
86 }
87
88 QString result = temp;
89 result.squeeze(); // release unused capacity and implicitly detach so temp keeps its capacity for next time
90 return result;
91 }
92 } // namespace private_ns
93
95 : CMessageBase(category), ITimestampBased(QDateTime::currentMSecsSinceEpoch())
96 {}
97
99 : CMessageBase(categories), ITimestampBased(QDateTime::currentMSecsSinceEpoch())
100 {}
101
103 : CMessageBase(categories, extra), ITimestampBased(QDateTime::currentMSecsSinceEpoch())
104 {}
105
107 : CMessageBase(categories, extra), ITimestampBased(QDateTime::currentMSecsSinceEpoch())
108 {}
109
111
113 : CValueObject(other), CMessageBase(other), ITimestampBased(other), IOrderable(other)
114 {
115 QReadLocker lock(&other.m_lock);
116 m_handledByObjects = other.m_handledByObjects;
117 }
118
120 {
121 if (this == &other)
122 {
123 return *this;
124 }
125
126 static_cast<CMessageBase &>(*this) = other;
127 static_cast<ITimestampBased &>(*this) = other;
128 static_cast<IOrderable &>(*this) = other;
129
130 // locks because of mutable member
131 QReadLocker readLock(&other.m_lock);
132 const auto handledBy = other.m_handledByObjects;
133 readLock.unlock(); // avoid deadlock
134
135 QWriteLocker writeLock(&m_lock);
136 m_handledByObjects = handledBy;
137 return *this;
138 }
139
140 CStatusMessage::CStatusMessage(QStringView message) : ITimestampBased(QDateTime::currentMSecsSinceEpoch())
141 {
143 }
144
146 {
147 m_message = message.trimmed();
148 }
149
151 {
152 m_severity = severity;
153 }
154
159
161 bool validation)
162 : CStatusMessage(severity, message)
163 {
164 m_categories = categories;
165 if (validation)
166 {
167 this->addValidationCategory();
168 }
169 }
170
172 bool validation)
173 : CStatusMessage(severity, message)
174 {
175 m_categories = categories;
176 if (validation)
177 {
178 this->addValidationCategory();
179 }
180 }
181
182 CStatusMessage::CStatusMessage(QtMsgType type, const QMessageLogContext &context, const QString &message)
183 : CStatusMessage(message.trimmed())
184 {
186
187 switch (type)
188 {
189 default:
190 case QtDebugMsg: m_severity = SeverityDebug; break;
191 case QtInfoMsg: m_severity = SeverityInfo; break;
192 case QtWarningMsg: m_severity = SeverityWarning; break;
193 case QtCriticalMsg:
194 case QtFatalMsg: m_severity = SeverityError; break;
195 }
196 }
197
198 void CStatusMessage::toQtLogTriple(QtMsgType *o_type, QString *o_category, QString *o_message) const
199 {
200 *o_category = m_categories.toQString();
201 *o_message = this->getMessage();
202
203 switch (m_severity)
204 {
205 default:
206 case SeverityDebug: *o_type = QtDebugMsg; break;
207 case SeverityInfo: *o_type = QtInfoMsg; break;
208 case SeverityWarning: *o_type = QtWarningMsg; break;
209 case SeverityError: *o_type = QtCriticalMsg; break;
210 }
211 }
212
214
216 {
217 if (this->getSeverity() <= severity)
218 {
219 return false;
220 }
221 this->setSeverity(severity);
222 return true;
223 }
224
226 {
227 return this->getSeverity() >= severity;
228 }
229
230 bool CStatusMessage::isSuccess() const { return !this->isFailure(); }
231
232 bool CStatusMessage::isFailure() const { return this->getSeverity() == SeverityError; }
233
235 {
236 const QString m = this->getMessage();
238 {
239 return m;
240 } // by far most messages will NOT contain tabs/CR
241 return removeLineBreakAndTab(m);
242 }
243
245 {
246 if (msg.isEmpty())
247 {
248 return;
249 }
250 m_message = QString(msg % m_message.view());
251 }
252
254 {
255 if (msg.isEmpty())
256 {
257 return;
258 }
259 m_message = QString(m_message.view() % msg);
260 }
261
262 void CStatusMessage::markAsHandledBy(const QObject *object) const
263 {
264 QWriteLocker lock(&m_lock);
265 m_handledByObjects.push_back(quintptr(object));
266 }
267
268 bool CStatusMessage::wasHandledBy(const QObject *object) const
269 {
270 QReadLocker lock(&m_lock);
271 return m_handledByObjects.contains(quintptr(object));
272 }
273
275 {
276 return u"Category: " % m_categories.toQString() %
277
278 u" Severity: " % severityToString(m_severity) %
279
280 u" when: " % this->getFormattedUtcTimestampYmdhms() %
281
282 u' ' % this->getMessage();
283 }
284
286 {
287 return convertToIcon(statusMessage.getSeverity());
288 }
289
291 {
292 switch (severity)
293 {
294 case SeverityDebug: return CIcon::iconByIndex(CIcons::StandardIconUnknown16); // TODO
295 case SeverityInfo: return CIcon::iconByIndex(CIcons::StandardIconInfo16);
296 case SeverityWarning: return CIcon::iconByIndex(CIcons::StandardIconWarning16);
297 case SeverityError: return CIcon::iconByIndex(CIcons::StandardIconError16);
298 default: return CIcon::iconByIndex(CIcons::StandardIconInfo16);
299 }
300 }
301
303 {
304 static const QString d;
305 static const QString i(":/pastel/icons/pastel/16/infomation.png");
306 static const QString w(":/pastel/icons/pastel/16/bullet-error.png");
307 static const QString e(":/pastel/icons/pastel/16/close-red.png");
308
309 switch (severity)
310 {
311 case SeverityDebug: return d;
312 case SeverityInfo: return i;
313 case SeverityWarning: return w;
314 case SeverityError: return e;
315 default: return d;
316 }
317 }
318
320 {
321 const QString msgText(json.value("text").toString());
322 const QString severityText(json.value("severity").toString());
323 QString typeText(json.value("type").toString());
324 StatusSeverity severity = stringToSeverity(severityText);
325
326 typeText = u"swift.db.type." % typeText.toLower().remove(' ');
327 const CStatusMessage m({ CLogCategories::swiftDbWebservice(), typeText }, severity, msgText);
328 return m;
329 }
330
332 const QString &prefix)
333 {
334 return CStatusMessage(categories).validationError(ex.toString(prefix));
335 }
336
338 {
340 qRegisterMetaType<CStatusMessage::StatusSeverity>();
341 qDBusRegisterMetaType<CStatusMessage::StatusSeverity>();
342 }
343
345 {
346 // pre-check
347 QString severityString(severity.trimmed().toLower());
348 if (severityString.isEmpty())
349 {
350 return SeverityInfo;
351 }
352
353 // hard check
355 {
356 return SeverityDebug;
357 }
358 if (severityString.compare(severityToString(SeverityInfo), Qt::CaseInsensitive) == 0)
359 {
360 return SeverityInfo;
361 }
363 {
364 return SeverityWarning;
365 }
367 {
368 return SeverityError;
369 }
370
371 // not found yet, lenient checks
372 QChar s = severityString.at(0);
373 if (s == 'd')
374 {
375 return SeverityDebug;
376 }
377 if (s == 'i')
378 {
379 return SeverityInfo;
380 }
381 if (s == 'w')
382 {
383 return SeverityWarning;
384 }
385 if (s == 'e')
386 {
387 return SeverityError;
388 }
389
390 return SeverityInfo;
391 }
392
394 {
395 switch (severity)
396 {
397 case SeverityDebug:
398 {
399 static const QString d("debug");
400 return d;
401 }
402 case SeverityInfo:
403 {
404 static const QString i("info");
405 return i;
406 }
407 case SeverityWarning:
408 {
409 static const QString w("warning");
410 return w;
411 }
412 case SeverityError:
413 {
414 static const QString e("error");
415 return e;
416 }
417 default:
418 {
419 static const QString x("unknown severity");
420 qFatal("Unknown severity");
421 return x; // just for compiler warning
422 }
423 }
424 }
425
427 {
428 if (severities.isEmpty())
429 {
430 return {};
431 }
432 auto minmax = std::ranges::minmax_element(severities);
433 auto min = *minmax.min;
434 auto max = *minmax.max;
435 if (min == SeverityDebug && max == SeverityError)
436 {
437 static const QString all("all severities");
438 return all;
439 }
440 if (min == SeverityDebug)
441 {
442 return u"at or below " % severityToString(max);
443 }
444 if (max == SeverityError)
445 {
446 return u"at or above " % severityToString(min);
447 }
448 auto list = severities.values();
449 std::ranges::sort(list);
450 QStringList ret;
451 std::ranges::transform(list, std::back_inserter(ret), severityToString);
452 return ret.join("|");
453 }
454
456
458
465
467 {
468 if (index.isMyself())
469 {
470 return QVariant::fromValue(*this);
471 }
473 {
475 }
477 {
478 return IOrderable::propertyByIndex(index);
479 }
480 const auto i = index.frontCasted<ColumnIndex>();
481 switch (i)
482 {
483 case IndexMessage: return QVariant::fromValue(this->getMessage());
484 case IndexSeverity: return QVariant::fromValue(m_severity);
485 case IndexSeverityAsString: return QVariant::fromValue(this->getSeverityAsString());
486 case IndexSeverityAsIcon: return QVariant::fromValue(this->getSeverityAsIcon());
487 case IndexCategoriesAsString: return QVariant::fromValue(m_categories.toQString());
488 case IndexMessageAsHtml: return QVariant::fromValue(this->toHtml(false, true));
489 default: return CValueObject::propertyByIndex(index);
490 }
491 }
492
494 {
495 if (index.isMyself())
496 {
497 (*this) = variant.value<CStatusMessage>();
498 return;
499 }
501 {
503 return;
504 }
506 {
507 IOrderable::setPropertyByIndex(index, variant);
508 return;
509 }
510 const auto i = index.frontCasted<ColumnIndex>();
511 switch (i)
512 {
513 case IndexMessage:
514 m_message = variant.value<QString>();
515 m_args.clear();
516 break;
517 case IndexSeverity: m_severity = variant.value<StatusSeverity>(); break;
518 case IndexCategoriesAsString: m_categories = variant.value<CLogCategoryList>(); break;
519 default: CValueObject::setPropertyByIndex(index, variant); break;
520 }
521 }
522
524 {
525 if (index.isMyself())
526 {
527 return Compare::compare(this->getSeverity(), compareValue.getSeverity());
528 }
530 {
531 return ITimestampBased::comparePropertyByIndex(index, compareValue);
532 }
534 {
535 return IOrderable::comparePropertyByIndex(index, compareValue);
536 }
537 const auto i = index.frontCasted<ColumnIndex>();
538 switch (i)
539 {
540 case IndexMessageAsHtml:
541 case IndexMessage: return this->getMessage().compare(compareValue.getMessage());
542 case IndexSeverityAsString:
543 case IndexSeverityAsIcon:
544 case IndexSeverity: return Compare::compare(this->getSeverity(), compareValue.getSeverity());
545 case IndexCategoriesAsString:
546 return this->getCategoriesAsString().compare(compareValue.getCategoriesAsString());
547 default: break;
548 }
549 return CValueObject::comparePropertyByIndex(index, compareValue);
550 }
551
552 QString CStatusMessage::toHtml(bool withIcon, bool withColors) const
553 {
554 QString img;
555 if (withIcon)
556 {
557 const QString r = convertToIconResource(this->getSeverity());
558 if (!r.isEmpty())
559 {
560 img = QStringLiteral("<img src=\"%1\"> ").arg(r);
561 }
562 }
563
564 if (withColors)
565 {
566 switch (this->getSeverity())
567 {
568 case SeverityWarning: return img % u"<font color=\"yellow\">" % this->getMessage() % u"</font>";
569 case SeverityError: return img % u"<font color=\"red\">" % this->getMessage() % u"</font>";
570 case SeverityDebug: break;
571 default: break;
572 }
573 }
574 return img % this->getMessage();
575 }
576} // namespace swift::misc
Value object for icons. An icon is stored in the global icon repository and identified by its index....
Definition icon.h:39
static const CIcon & iconByIndex(CIcons::IconIndex index)
Icon for given index.
Definition icon.cpp:63
Thrown when a convertFromJson method encounters an unrecoverable error in JSON data.
QString toString(const QString &prefix) const
As string info.
static const QString & swiftDbWebservice()
Webservice with swift DB.
A log category is an arbitrary string tag which can be attached to log messages.
Definition logcategory.h:28
A sequence of log categories.
static CLogCategoryList fromQString(const QString &string)
Convert a string, such as that returned by toQString(), into a CLogCategoryList.
Derived & validationError(const char16_t(&format)[N])
Set the severity to error, providing a format string, and adding the validation category.
CStatusMessage & validation(StatusSeverity s, const char16_t(&format)[N])
Non-owning reference to a CPropertyIndex with a subset of its features.
CastType frontCasted() const
First element casted to given type, usually the PropertIndex enum.
bool isMyself() const
Myself index, used with nesting.
Streamable status message, e.g.
void markAsHandledBy(const QObject *object) const
Mark the message as having been handled by the given object.
QString getCategoriesAsString() const
Message categories as string.
static CStatusMessage fromJsonException(const CJsonException &ex, const CLogCategoryList &categories, const QString &prefix)
Object from JSON exception message.
bool isSuccess() const
Operation considered successful.
static const QString & convertToIconResource(CStatusMessage::StatusSeverity severity)
Representing icon.
const QString & getSeverityAsString() const
Severity as string.
const CIcon & getSeverityAsIcon() const
Severity as icon.
void appendMessage(const QString &msg)
Append message.
static constexpr auto SeverityInfo
Status severities.
static constexpr auto SeverityError
Status severities.
CStatusMessage(const CLogCategory &category)
Construct a message with some specific category.
bool isSeverityHigherOrEqual(CStatusMessage::StatusSeverity severity) const
Is this message's severity higher or equal.
void toQtLogTriple(QtMsgType *o_type, QString *o_category, QString *o_message) const
Convert to a Qt logging triple.
QVariant propertyByIndex(swift::misc::CPropertyIndexRef index) const
Property by index.
void addValidationCategory()
Adds validation as category.
static void registerMetadata()
Register metadata.
static const QString & severityToString(StatusSeverity severity)
Severity as string.
static const CIcon & convertToIcon(const CStatusMessage &statusMessage)
Representing icon.
static StatusSeverity stringToSeverity(const QString &severity)
Severity as string, if not possible to convert.
bool clampSeverity(StatusSeverity severity)
Clip/reduce severity if higher (more critical).
StatusSeverity getSeverity() const
Message severity.
void setSeverity(StatusSeverity severity)
Severity.
QString getMessage() const
Message.
CStatusMessage & operator=(const CStatusMessage &other)
Copy assignment (because of mutex).
static const QStringList & allSeverityStrings()
Severities as strings.
ColumnIndex
Properties by index.
QString convertToQString(bool i18n=false) const
Cast as QString.
int comparePropertyByIndex(CPropertyIndexRef index, const CStatusMessage &compareValue) const
Compare for index.
void prependMessage(const QString &msg)
Prepend message.
bool wasHandledBy(const QObject *object) const
Returns true if the message was marked as having been handled by the given object.
swift::misc::StatusSeverity StatusSeverity
Status severities.
void setPropertyByIndex(swift::misc::CPropertyIndexRef index, const QVariant &variant)
Set property by index.
bool isFailure() const
Operation considered unsuccessful.
static CStatusMessage fromDatabaseJson(const QJsonObject &json)
Object from JSON.
QString toHtml(bool withIcon, bool withColors) const
To HTML.
static constexpr auto SeverityDebug
Status severities.
static QString severitiesToString(const QSet< StatusSeverity > &severities)
Severity set as string.
QString getMessageNoLineBreaks() const
Message without line breaks.
static constexpr auto SeverityWarning
Status severities.
Special-purpose string class used by CMessageBase.
static bool canHandleIndex(CPropertyIndexRef index)
Can given index be handled.
Definition orderable.cpp:34
IOrderable()=default
Constructor.
int comparePropertyByIndex(CPropertyIndexRef index, const IOrderable &compareValue) const
Compare for index.
Definition orderable.cpp:77
void setPropertyByIndex(CPropertyIndexRef index, const QVariant &variant)
Set property by index.
Definition orderable.cpp:61
QVariant propertyByIndex(CPropertyIndexRef index) const
Property by index.
Definition orderable.cpp:44
Entity with timestamp.
void setPropertyByIndex(CPropertyIndexRef index, const QVariant &variant)
Set property by index.
int comparePropertyByIndex(CPropertyIndexRef index, const ITimestampBased &compareValue) const
Compare for index.
QString getFormattedUtcTimestampYmdhms() const
As yyyy MM dd HH mm ss.
ITimestampBased()=default
Constructor.
static bool canHandleIndex(CPropertyIndexRef index)
Can given index be handled.
QVariant propertyByIndex(CPropertyIndexRef index) const
Property by index.
int comparePropertyByIndex(CPropertyIndexRef index, const Derived &compareValue) const
Compare for index.
Definition mixinindex.h:203
void setPropertyByIndex(CPropertyIndexRef index, const QVariant &variant)
Set property by index.
Definition mixinindex.h:167
QVariant propertyByIndex(CPropertyIndexRef index) const
Property by index.
Definition mixinindex.h:180
static void registerMetadata()
Register metadata.
int compare(T a, T b)
Compare arithmetic values.
Free functions in swift::misc.
bool is09(const QChar &c)
Is 0-9 char, isDigit allows a bunch of more characters.
bool containsLineBreakOrTab(const QString &s)
Contains a line break or tab.
Definition stringutils.h:70
StatusSeverity
Status severities.
QString removeLineBreakAndTab(const QString &s)
Remove line breaks and tabs.
Definition stringutils.h:54
qsizetype size() const const
void unlock()
bool isEmpty() const const
QList< T > values() const const
QString & append(QChar ch)
QString arg(Args &&... args) const const
const QChar at(qsizetype position) const const
int compare(QLatin1StringView s1, const QString &s2, Qt::CaseSensitivity cs)
bool isEmpty() const const
QString number(double n, char format, int precision)
QString & remove(QChar ch, Qt::CaseSensitivity cs)
void resize(qsizetype newSize, QChar fillChar)
void squeeze()
QString toLower() const const
QString trimmed() const const
QString join(QChar separator) const const
QStringView::const_iterator begin() const const
QStringView::const_iterator end() const const
bool isEmpty() const const
CaseInsensitive
QVariant fromValue(T &&value)
T value() const &const
#define SWIFT_DEFINE_VALUEOBJECT_MIXINS(Namespace, Class)
Explicit template definition of mixins for a CValueObject subclass.
Definition valueobject.h:67
#define SWIFT_VERIFY(COND)
A weaker kind of assert.
Definition verify.h:29