Update string literals

Since _ls is now deprecated this is removed in favour of L1, I've also taken the oportunity to replace QStringLiteral and QLatin1String with their shortened form while we're at it.

There are also a few instances where the string literal type has been switch, the general rule being to use the one that matches the function type or value being compared to avoid conversions.
This commit is contained in:
James Graham
2024-12-22 18:23:55 +00:00
parent 314f86007e
commit 6bdb67f504
88 changed files with 5017 additions and 5046 deletions

View File

@@ -57,7 +57,7 @@ QString ChatBarCache::formatMentions() const
}
formattedText = formattedText.replace(mention.cursor.anchor(),
mention.cursor.position() - mention.cursor.anchor(),
QStringLiteral("[%1](https://matrix.to/#/%2)").arg(mention.text.toHtmlEscaped(), mention.id));
u"[%1](https://matrix.to/#/%2)"_s.arg(mention.text.toHtmlEscaped(), mention.id));
}
return formattedText;
@@ -256,7 +256,7 @@ void ChatBarCache::updateMentions(QQuickTextDocument *document, ChatDocumentHand
if (auto event = room->findInTimeline(m_relationId); event != room->historyEdge()) {
if (const auto &roomMessageEvent = &*event->viewAs<Quotient::RoomMessageEvent>()) {
// Replaces the mentions that are baked into the HTML but plaintext in the original markdown
const QRegularExpression re(QStringLiteral(R"lit(<a\shref="https:\/\/matrix.to\/#\/([\S]*)"\s?>([\S]*)<\/a>)lit"));
const QRegularExpression re(uR"lit(<a\shref="https:\/\/matrix.to\/#\/([\S]*)"\s?>([\S]*)<\/a>)lit"_s);
m_mentions.clear();

View File

@@ -16,6 +16,8 @@
#include "chatdocumenthandler_logging.h"
using namespace Qt::StringLiterals;
class SyntaxHighlighter : public QSyntaxHighlighter
{
public:
@@ -228,7 +230,7 @@ void ChatDocumentHandler::complete(int index)
QTextCursor cursor(document()->textDocument());
cursor.setPosition(at);
cursor.setPosition(cursorPosition(), QTextCursor::KeepAnchor);
cursor.insertText(name + QStringLiteral(" "));
cursor.insertText(name + u" "_s);
cursor.setPosition(at);
cursor.setPosition(cursor.position() + name.size(), QTextCursor::KeepAnchor);
cursor.setKeepPositionOnInsert(true);
@@ -241,7 +243,7 @@ void ChatDocumentHandler::complete(int index)
QTextCursor cursor(document()->textDocument());
cursor.setPosition(at);
cursor.setPosition(cursorPosition(), QTextCursor::KeepAnchor);
cursor.insertText(QStringLiteral("/%1 ").arg(command));
cursor.insertText(u"/%1 "_s.arg(command));
} else if (m_completionModel->autoCompletionType() == CompletionModel::Room) {
auto alias = m_completionModel->data(m_completionModel->index(index, 0), CompletionModel::SubtitleRole).toString();
auto text = getText();
@@ -249,7 +251,7 @@ void ChatDocumentHandler::complete(int index)
QTextCursor cursor(document()->textDocument());
cursor.setPosition(at);
cursor.setPosition(cursorPosition(), QTextCursor::KeepAnchor);
cursor.insertText(alias + QStringLiteral(" "));
cursor.insertText(alias + u" "_s);
cursor.setPosition(at);
cursor.setPosition(cursor.position() + alias.size(), QTextCursor::KeepAnchor);
cursor.setKeepPositionOnInsert(true);

View File

@@ -14,6 +14,8 @@
#include <QStandardPaths>
#include <QUrl>
using namespace Qt::StringLiterals;
Clipboard::Clipboard(QObject *parent)
: QObject(parent)
, m_clipboard(QGuiApplication::clipboard())
@@ -33,14 +35,14 @@ QImage Clipboard::image() const
QString Clipboard::saveImage(QString localPath) const
{
QString imageDir(QStringLiteral("%1/screenshots").arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)));
QString imageDir(u"%1/screenshots"_s.arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)));
if (!QDir().exists(imageDir)) {
QDir().mkdir(imageDir);
}
if (localPath.isEmpty()) {
localPath = QStringLiteral("file://%1/%2.png").arg(imageDir, QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd-hh-mm-ss")));
localPath = u"file://%1/%2.png"_s.arg(imageDir, QDateTime::currentDateTime().toString(u"yyyy-MM-dd-hh-mm-ss"_s));
}
QUrl url(localPath);
if (!url.isLocalFile()) {
@@ -61,7 +63,7 @@ QString Clipboard::saveImage(QString localPath) const
void Clipboard::saveText(QString message)
{
static QRegularExpression re(QStringLiteral("<[^>]*>"));
static QRegularExpression re(u"<[^>]*>"_s);
auto *mimeData = new QMimeData; // ownership is transferred to clipboard
mimeData->setHtml(message);
mimeData->setText(message.replace(re, QString()));

View File

@@ -63,7 +63,7 @@ Controller::Controller(QObject *parent)
});
} else {
auto c = new NeoChatConnection(this);
c->assumeIdentity(QStringLiteral("@user:localhost:1234"), QStringLiteral("device_1234"), QStringLiteral("token_1234"));
c->assumeIdentity(u"@user:localhost:1234"_s, u"device_1234"_s, u"token_1234"_s);
connect(c, &Connection::connected, this, [c, this]() {
m_accountRegistry.add(c);
c->syncLoop();
@@ -117,7 +117,7 @@ Controller::Controller(QObject *parent)
});
#ifdef HAVE_KUNIFIEDPUSH
auto connector = new KUnifiedPush::Connector(QStringLiteral("org.kde.neochat"));
auto connector = new KUnifiedPush::Connector(u"org.kde.neochat"_s);
connect(connector, &KUnifiedPush::Connector::endpointChanged, this, [this](const QString &endpoint) {
m_endpoint = endpoint;
for (auto &quotientConnection : m_accountRegistry) {
@@ -187,7 +187,7 @@ void Controller::dropConnection(NeoChatConnection *c)
void Controller::invokeLogin()
{
const auto accounts = SettingsGroup("Accounts"_ls).childGroups();
const auto accounts = SettingsGroup("Accounts"_L1).childGroups();
for (const auto &accountId : accounts) {
AccountSettings account{accountId};
m_accountsLoading += accountId;
@@ -288,7 +288,7 @@ bool Controller::supportSystemTray() const
return false;
#else
auto de = QString::fromLatin1(qgetenv("XDG_CURRENT_DESKTOP"));
return de != QStringLiteral("GNOME") && de != QStringLiteral("Pantheon");
return de != u"GNOME"_s && de != u"Pantheon"_s;
#endif
}
@@ -341,7 +341,7 @@ void Controller::setActiveConnection(NeoChatConnection *connection)
void Controller::listenForNotifications()
{
#ifdef HAVE_KUNIFIEDPUSH
auto connector = new KUnifiedPush::Connector(QStringLiteral("org.kde.neochat"));
auto connector = new KUnifiedPush::Connector(u"org.kde.neochat"_s);
auto timer = new QTimer();
connect(timer, &QTimer::timeout, qGuiApp, &QGuiApplication::quit);
@@ -370,19 +370,19 @@ void Controller::updateBadgeNotificationCount(NeoChatConnection *connection, int
#if QT_VERSION < QT_VERSION_CHECK(6, 6, 0)
#ifndef Q_OS_ANDROID
// copied from Telegram desktop
const auto launcherUrl = "application://org.kde.neochat.desktop"_ls;
const auto launcherUrl = "application://org.kde.neochat.desktop"_L1;
// Gnome requires that count is a 64bit integer
const qint64 counterSlice = std::min(count, 9999);
QVariantMap dbusUnityProperties;
if (counterSlice > 0) {
dbusUnityProperties["count"_ls] = counterSlice;
dbusUnityProperties["count-visible"_ls] = true;
dbusUnityProperties["count"_L1] = counterSlice;
dbusUnityProperties["count-visible"_L1] = true;
} else {
dbusUnityProperties["count-visible"_ls] = false;
dbusUnityProperties["count-visible"_L1] = false;
}
auto signal = QDBusMessage::createSignal("/com/canonical/unity/launcherentry/neochat"_ls, "com.canonical.Unity.LauncherEntry"_ls, "Update"_ls);
auto signal = QDBusMessage::createSignal("/com/canonical/unity/launcherentry/neochat"_L1, "com.canonical.Unity.LauncherEntry"_L1, "Update"_L1);
signal.setArguments({launcherUrl, dbusUnityProperties});
@@ -431,7 +431,7 @@ void Controller::removeConnection(const QString &userId)
}
if (m_connectionsLoading.contains(userId) && m_connectionsLoading[userId]) {
auto connection = m_connectionsLoading[userId];
SettingsGroup("Accounts"_ls).remove(userId);
SettingsGroup("Accounts"_L1).remove(userId);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -4,6 +4,8 @@
#include "emojitones.h"
#include "models/emojimodel.h"
using namespace Qt::StringLiterals;
QMultiHash<QString, QVariant> EmojiTones::_tones = {
#include "emojitones_data.h"
};

File diff suppressed because it is too large Load Diff

View File

@@ -13,6 +13,8 @@
#include "events/pollevent.h"
using namespace Qt::StringLiterals;
/**
* @class DelegateType
*
@@ -58,7 +60,7 @@ public:
return Message;
}
if (event.isStateEvent()) {
if (event.matrixType() == QStringLiteral("org.matrix.msc3672.beacon_info")) {
if (event.matrixType() == u"org.matrix.msc3672.beacon_info"_s) {
return Message;
}
return State;

View File

@@ -13,6 +13,8 @@
#include "events/pollevent.h"
using namespace Qt::StringLiterals;
/**
* @class MessageComponentType
*
@@ -92,7 +94,7 @@ public:
return MessageComponentType::Image;
}
if (event.isStateEvent()) {
if (event.matrixType() == QStringLiteral("org.matrix.msc3672.beacon_info")) {
if (event.matrixType() == u"org.matrix.msc3672.beacon_info"_s) {
return MessageComponentType::LiveLocation;
}
return MessageComponentType::Other;
@@ -120,10 +122,10 @@ public:
*/
static Type typeForTag(const QString &tag)
{
if (tag == QLatin1String("pre") || tag == QLatin1String("pre")) {
if (tag == u"pre"_s || tag == u"pre"_s) {
return Code;
}
if (tag == QLatin1String("blockquote")) {
if (tag == u"blockquote"_s) {
return Quote;
}
return Text;

View File

@@ -10,6 +10,8 @@
#include <KLocalizedString>
using namespace Qt::StringLiterals;
class NeoChatRoomType : public QObject
{
Q_OBJECT
@@ -75,19 +77,19 @@ public:
{
switch (category) {
case NeoChatRoomType::Invited:
return QStringLiteral("user-invisible");
return u"user-invisible"_s;
case NeoChatRoomType::Favorite:
return QStringLiteral("favorite");
return u"favorite"_s;
case NeoChatRoomType::Direct:
return QStringLiteral("dialog-messages");
return u"dialog-messages"_s;
case NeoChatRoomType::Normal:
return QStringLiteral("group");
return u"group"_s;
case NeoChatRoomType::Deprioritized:
return QStringLiteral("object-order-lower");
return u"object-order-lower"_s;
case NeoChatRoomType::Space:
return QStringLiteral("group");
return u"group"_s;
default:
return QStringLiteral("tools-report-bug");
return u"tools-report-bug"_s;
}
}
};

View File

@@ -6,6 +6,8 @@
#include <QObject>
#include <QQmlEngine>
using namespace Qt::StringLiterals;
/**
* @class PushRuleKind
*
@@ -42,15 +44,15 @@ public:
{
switch (kind) {
case Kind::Override:
return QLatin1String("override");
return u"override"_s;
case Kind::Content:
return QLatin1String("content");
return u"content"_s;
case Kind::Room:
return QLatin1String("room");
return u"room"_s;
case Kind::Sender:
return QLatin1String("sender");
return u"sender"_s;
case Kind::Underride:
return QLatin1String("underride");
return u"underride"_s;
default:
return {};
}
@@ -170,15 +172,15 @@ public:
{
switch (section) {
case Section::Master:
return QLatin1String("Master");
return u"Master"_s;
case Section::Room:
return QLatin1String("Room Notifications");
return u"Room Notifications"_s;
case Section::Mentions:
return QLatin1String("@Mentions");
return u"@Mentions"_s;
case Section::Keywords:
return QLatin1String("Keywords");
return u"Keywords"_s;
case Section::Invites:
return QLatin1String("Invites");
return u"Invites"_s;
default:
return {};
}

View File

@@ -60,9 +60,9 @@ QString EventHandler::authorDisplayName(const NeoChatRoom *room, const Quotient:
return {};
}
if (is<RoomMemberEvent>(*event) && event->unsignedJson()[QStringLiteral("prev_content")].toObject().contains("displayname"_L1)
if (is<RoomMemberEvent>(*event) && event->unsignedJson()["prev_content"_L1].toObject().contains("displayname"_L1)
&& event->stateKey() == event->senderId()) {
auto previousDisplayName = event->unsignedJson()[QStringLiteral("prev_content")][QStringLiteral("displayname")].toString().toHtmlEscaped();
auto previousDisplayName = event->unsignedJson()["prev_content"_L1]["displayname"_L1].toString().toHtmlEscaped();
if (previousDisplayName.isEmpty()) {
previousDisplayName = event->senderId();
}
@@ -86,12 +86,12 @@ QString EventHandler::singleLineAuthorDisplayname(const NeoChatRoom *room, const
const auto author = isPending ? room->localMember() : room->member(event->senderId());
auto displayName = author.displayName();
displayName.replace(QStringLiteral("<br>\n"), QStringLiteral(" "));
displayName.replace(QStringLiteral("<br>"), QStringLiteral(" "));
displayName.replace(QStringLiteral("<br />\n"), QStringLiteral(" "));
displayName.replace(QStringLiteral("<br />"), QStringLiteral(" "));
displayName.replace(u'\n', QStringLiteral(" "));
displayName.replace(u'\u2028', QStringLiteral(" "));
displayName.replace(u"<br>\n"_s, u" "_s);
displayName.replace(u"<br>"_s, u" "_s);
displayName.replace(u"<br />\n"_s, u" "_s);
displayName.replace(u"<br />"_s, u" "_s);
displayName.replace(u'\n', u" "_s);
displayName.replace(u'\u2028', u" "_s);
return displayName;
}
@@ -195,7 +195,7 @@ bool EventHandler::isHidden(const NeoChatRoom *room, const Quotient::RoomEvent *
}
// hide ending live location beacons
if (event->isStateEvent() && event->matrixType() == "org.matrix.msc3672.beacon_info"_ls && !event->contentJson()["live"_ls].toBool()) {
if (event->isStateEvent() && event->matrixType() == "org.matrix.msc3672.beacon_info"_L1 && !event->contentJson()["live"_L1].toBool()) {
return true;
}
@@ -204,7 +204,7 @@ bool EventHandler::isHidden(const NeoChatRoom *room, const Quotient::RoomEvent *
Qt::TextFormat EventHandler::messageBodyInputFormat(const Quotient::RoomMessageEvent &event)
{
if (event.mimeType().name() == "text/plain"_ls) {
if (event.mimeType().name() == "text/plain"_L1) {
return Qt::PlainText;
} else {
return Qt::RichText;
@@ -309,8 +309,8 @@ QString EventHandler::getBody(const NeoChatRoom *room, const Quotient::RoomEvent
}
if (prettyPrint) {
subjectName = QStringLiteral("<a href=\"https://matrix.to/#/%1\" style=\"color: %2\">%3</a>")
.arg(e.userId(), room->member(e.userId()).color().name(), subjectName);
subjectName =
u"<a href=\"https://matrix.to/#/%1\" style=\"color: %2\">%3</a>"_s.arg(e.userId(), room->member(e.userId()).color().name(), subjectName);
}
// The below code assumes senderName output in AuthorRole
@@ -376,7 +376,7 @@ QString EventHandler::getBody(const NeoChatRoom *room, const Quotient::RoomEvent
if (e.senderId() == e.userId()) {
return i18n("left the room");
}
if (const auto &reason = e.contentJson()["reason"_ls].toString().toHtmlEscaped(); !reason.isEmpty()) {
if (const auto &reason = e.contentJson()["reason"_L1].toString().toHtmlEscaped(); !reason.isEmpty()) {
return i18n("has put %1 out of the room: %2", subjectName, reason);
}
return i18n("has put %1 out of the room", subjectName);
@@ -391,7 +391,7 @@ QString EventHandler::getBody(const NeoChatRoom *room, const Quotient::RoomEvent
return i18n("self-banned from the room");
}
case Membership::Knock: {
QString reason(e.contentJson()["reason"_ls].toString().toHtmlEscaped());
QString reason(e.contentJson()["reason"_L1].toString().toHtmlEscaped());
return reason.isEmpty() ? i18n("requested an invite") : i18n("requested an invite with reason: %1", reason);
}
default:;
@@ -419,26 +419,26 @@ QString EventHandler::getBody(const NeoChatRoom *room, const Quotient::RoomEvent
},
[prettyPrint](const RoomCreateEvent &e) {
return e.isUpgrade()
? i18n("upgraded the room to version %1", e.version().isEmpty() ? "1"_ls : (prettyPrint ? e.version().toHtmlEscaped() : e.version()))
: i18n("created the room, version %1", e.version().isEmpty() ? "1"_ls : (prettyPrint ? e.version().toHtmlEscaped() : e.version()));
? i18n("upgraded the room to version %1", e.version().isEmpty() ? "1"_L1 : (prettyPrint ? e.version().toHtmlEscaped() : e.version()))
: i18n("created the room, version %1", e.version().isEmpty() ? "1"_L1 : (prettyPrint ? e.version().toHtmlEscaped() : e.version()));
},
[](const RoomPowerLevelsEvent &) {
return i18nc("'power level' means permission level", "changed the power levels for this room");
},
[](const LocationBeaconEvent &e) {
return e.contentJson()["description"_ls].toString();
return e.contentJson()["description"_L1].toString();
},
[](const RoomServerAclEvent &) {
return i18n("changed the server access control lists for this room");
},
[](const WidgetEvent &e) {
if (e.fullJson()["unsigned"_ls]["prev_content"_ls].toObject().isEmpty()) {
return i18nc("[User] added <name> widget", "added %1 widget", e.contentJson()["name"_ls].toString());
if (e.fullJson()["unsigned"_L1]["prev_content"_L1].toObject().isEmpty()) {
return i18nc("[User] added <name> widget", "added %1 widget", e.contentJson()["name"_L1].toString());
}
if (e.contentJson().isEmpty()) {
return i18nc("[User] removed <name> widget", "removed %1 widget", e.fullJson()["unsigned"_ls]["prev_content"_ls]["name"_ls].toString());
return i18nc("[User] removed <name> widget", "removed %1 widget", e.fullJson()["unsigned"_L1]["prev_content"_L1]["name"_L1].toString());
}
return i18nc("[User] configured <name> widget", "configured %1 widget", e.contentJson()["name"_ls].toString());
return i18nc("[User] configured <name> widget", "configured %1 widget", e.contentJson()["name"_L1].toString());
},
[prettyPrint](const StateEvent &e) {
return e.stateKey().isEmpty() ? i18n("updated %1 state", e.matrixType())
@@ -459,7 +459,7 @@ QString EventHandler::getMessageBody(const NeoChatRoom *room, const RoomMessageE
if (fileCaption.isEmpty()) {
fileCaption = event.plainBody();
} else if (fileCaption != event.plainBody()) {
fileCaption = event.plainBody() + " | "_ls + fileCaption;
fileCaption = event.plainBody() + " | "_L1 + fileCaption;
}
textHandler.setData(fileCaption);
return !fileCaption.isEmpty() ? textHandler.handleRecievePlainText(Qt::PlainText, stripNewlines) : i18n("a file");
@@ -475,7 +475,7 @@ QString EventHandler::getMessageBody(const NeoChatRoom *room, const RoomMessageE
textHandler.setData(body);
Qt::TextFormat inputFormat;
if (event.mimeType().name() == "text/plain"_ls) {
if (event.mimeType().name() == "text/plain"_L1) {
inputFormat = Qt::PlainText;
} else {
inputFormat = Qt::RichText;
@@ -503,7 +503,7 @@ QString EventHandler::genericBody(const NeoChatRoom *room, const Quotient::RoomE
}
const auto sender = room->member(event->senderId());
const auto senderString = QStringLiteral("<a href=\"https://matrix.to/#/%1\">%2</a>").arg(sender.id(), sender.htmlSafeDisplayName());
const auto senderString = u"<a href=\"https://matrix.to/#/%1\">%2</a>"_s.arg(sender.id(), sender.htmlSafeDisplayName());
return switchOnType(
*event,
@@ -632,7 +632,7 @@ QString EventHandler::genericBody(const NeoChatRoom *room, const Quotient::RoomE
return i18n("%1 changed the server access control lists for this room", senderString);
},
[senderString](const WidgetEvent &e) {
if (e.fullJson()["unsigned"_ls]["prev_content"_ls].toObject().isEmpty()) {
if (e.fullJson()["unsigned"_L1]["prev_content"_L1].toObject().isEmpty()) {
return i18n("%1 added a widget", senderString);
}
if (e.contentJson().isEmpty()) {
@@ -659,7 +659,7 @@ QString EventHandler::subtitleText(const NeoChatRoom *room, const Quotient::Room
qCWarning(EventHandling) << "subtitleText called with event set to nullptr.";
return {};
}
return singleLineAuthorDisplayname(room, event) + (event->isStateEvent() ? QLatin1String(" ") : QLatin1String(": ")) + plainBody(room, event, true);
return singleLineAuthorDisplayname(room, event) + (event->isStateEvent() ? u" "_s : u": "_s) + plainBody(room, event, true);
}
QVariantMap EventHandler::mediaInfo(const NeoChatRoom *room, const Quotient::RoomEvent *event)
@@ -690,7 +690,7 @@ QVariantMap EventHandler::getMediaInfoForEvent(const NeoChatRoom *room, const Qu
QVariantMap mediaInfo = getMediaInfoFromFileInfo(room, content.get(), eventId, false, false);
// if filename isn't specifically given, it is in body
// https://spec.matrix.org/latest/client-server-api/#mfile
mediaInfo["filename"_ls] = content->commonInfo().originalName.isEmpty() ? roomMessageEvent->plainBody() : content->commonInfo().originalName;
mediaInfo["filename"_L1] = content->commonInfo().originalName.isEmpty() ? roomMessageEvent->plainBody() : content->commonInfo().originalName;
return mediaInfo;
} else if (event->is<StickerEvent>()) {
@@ -712,80 +712,80 @@ QVariantMap EventHandler::getMediaInfoFromFileInfo(const NeoChatRoom *room,
QVariantMap mediaInfo;
// Get the mxc URL for the media.
if (!fileContent->url().isValid() || fileContent->url().scheme() != QStringLiteral("mxc") || eventId.isEmpty()) {
mediaInfo["source"_ls] = QUrl();
if (!fileContent->url().isValid() || fileContent->url().scheme() != u"mxc"_s || eventId.isEmpty()) {
mediaInfo["source"_L1] = QUrl();
} else {
QUrl source = room->makeMediaUrl(eventId, fileContent->url());
if (source.isValid()) {
mediaInfo["source"_ls] = source;
mediaInfo["source"_L1] = source;
} else {
mediaInfo["source"_ls] = QUrl();
mediaInfo["source"_L1] = QUrl();
}
}
auto mimeType = fileContent->type();
// Add the MIME type for the media if available.
mediaInfo["mimeType"_ls] = mimeType.name();
mediaInfo["mimeType"_L1] = mimeType.name();
// Add the MIME type icon if available.
mediaInfo["mimeIcon"_ls] = mimeType.iconName();
mediaInfo["mimeIcon"_L1] = mimeType.iconName();
// Add media size if available.
mediaInfo["size"_ls] = fileContent->commonInfo().payloadSize;
mediaInfo["size"_L1] = fileContent->commonInfo().payloadSize;
mediaInfo["isSticker"_ls] = isSticker;
mediaInfo["isSticker"_L1] = isSticker;
// Add parameter depending on media type.
if (mimeType.name().contains(QStringLiteral("image"))) {
if (mimeType.name().contains(u"image"_s)) {
if (auto castInfo = static_cast<const EventContent::ImageContent *>(fileContent)) {
mediaInfo["width"_ls] = castInfo->imageSize.width();
mediaInfo["height"_ls] = castInfo->imageSize.height();
mediaInfo["width"_L1] = castInfo->imageSize.width();
mediaInfo["height"_L1] = castInfo->imageSize.height();
// TODO: Images in certain formats (e.g. WebP) will be erroneously marked as animated, even if they are static.
mediaInfo["animated"_ls] = QMovie::supportedFormats().contains(mimeType.preferredSuffix().toUtf8());
mediaInfo["animated"_L1] = QMovie::supportedFormats().contains(mimeType.preferredSuffix().toUtf8());
QVariantMap tempInfo;
auto thumbnailInfo = getMediaInfoFromTumbnail(room, castInfo->thumbnail, eventId);
if (thumbnailInfo["source"_ls].toUrl().scheme() == "mxc"_ls) {
if (thumbnailInfo["source"_L1].toUrl().scheme() == "mxc"_L1) {
tempInfo = thumbnailInfo;
} else {
QString blurhash = castInfo->originalInfoJson["xyz.amorgan.blurhash"_ls].toString();
QString blurhash = castInfo->originalInfoJson["xyz.amorgan.blurhash"_L1].toString();
if (blurhash.isEmpty()) {
tempInfo["source"_ls] = QUrl();
tempInfo["source"_L1] = QUrl();
} else {
tempInfo["source"_ls] = QUrl("image://blurhash/"_ls + blurhash);
tempInfo["source"_L1] = QUrl("image://blurhash/"_L1 + blurhash);
}
}
mediaInfo["tempInfo"_ls] = tempInfo;
mediaInfo["tempInfo"_L1] = tempInfo;
}
}
if (mimeType.name().contains(QStringLiteral("video"))) {
if (mimeType.name().contains(u"video"_s)) {
if (auto castInfo = static_cast<const EventContent::VideoContent *>(fileContent)) {
mediaInfo["width"_ls] = castInfo->imageSize.width();
mediaInfo["height"_ls] = castInfo->imageSize.height();
mediaInfo["duration"_ls] = castInfo->duration;
mediaInfo["width"_L1] = castInfo->imageSize.width();
mediaInfo["height"_L1] = castInfo->imageSize.height();
mediaInfo["duration"_L1] = castInfo->duration;
if (!isThumbnail) {
QVariantMap tempInfo;
auto thumbnailInfo = getMediaInfoFromTumbnail(room, castInfo->thumbnail, eventId);
if (thumbnailInfo["source"_ls].toUrl().scheme() == "mxc"_ls) {
if (thumbnailInfo["source"_L1].toUrl().scheme() == "mxc"_L1) {
tempInfo = thumbnailInfo;
} else {
QString blurhash = castInfo->originalInfoJson["xyz.amorgan.blurhash"_ls].toString();
QString blurhash = castInfo->originalInfoJson["xyz.amorgan.blurhash"_L1].toString();
if (blurhash.isEmpty()) {
tempInfo["source"_ls] = QUrl();
tempInfo["source"_L1] = QUrl();
} else {
tempInfo["source"_ls] = QUrl("image://blurhash/"_ls + blurhash);
tempInfo["source"_L1] = QUrl("image://blurhash/"_L1 + blurhash);
}
}
mediaInfo["tempInfo"_ls] = tempInfo;
mediaInfo["tempInfo"_L1] = tempInfo;
}
}
}
if (mimeType.name().contains(QStringLiteral("audio"))) {
if (mimeType.name().contains(u"audio"_s)) {
if (auto castInfo = static_cast<const EventContent::AudioContent *>(fileContent)) {
mediaInfo["duration"_ls] = castInfo->duration;
mediaInfo["duration"_L1] = castInfo->duration;
}
}
@@ -796,30 +796,30 @@ QVariantMap EventHandler::getMediaInfoFromTumbnail(const NeoChatRoom *room, cons
{
QVariantMap thumbnailInfo;
if (!thumbnail.url().isValid() || thumbnail.url().scheme() != QStringLiteral("mxc") || eventId.isEmpty()) {
thumbnailInfo["source"_ls] = QUrl();
if (!thumbnail.url().isValid() || thumbnail.url().scheme() != u"mxc"_s || eventId.isEmpty()) {
thumbnailInfo["source"_L1] = QUrl();
} else {
QUrl source = room->makeMediaUrl(eventId, thumbnail.url());
if (source.isValid()) {
thumbnailInfo["source"_ls] = source;
thumbnailInfo["source"_L1] = source;
} else {
thumbnailInfo["source"_ls] = QUrl();
thumbnailInfo["source"_L1] = QUrl();
}
}
auto mimeType = thumbnail.mimeType;
// Add the MIME type for the media if available.
thumbnailInfo["mimeType"_ls] = mimeType.name();
thumbnailInfo["mimeType"_L1] = mimeType.name();
// Add the MIME type icon if available.
thumbnailInfo["mimeIcon"_ls] = mimeType.iconName();
thumbnailInfo["mimeIcon"_L1] = mimeType.iconName();
// Add media size if available.
thumbnailInfo["size"_ls] = thumbnail.payloadSize;
thumbnailInfo["size"_L1] = thumbnail.payloadSize;
thumbnailInfo["width"_ls] = thumbnail.imageSize.width();
thumbnailInfo["height"_ls] = thumbnail.imageSize.height();
thumbnailInfo["width"_L1] = thumbnail.imageSize.width();
thumbnailInfo["height"_L1] = thumbnail.imageSize.height();
return thumbnailInfo;
}
@@ -849,7 +849,7 @@ float EventHandler::latitude(const Quotient::RoomEvent *event)
return -100.0;
}
const auto geoUri = event->contentJson()["geo_uri"_ls].toString();
const auto geoUri = event->contentJson()["geo_uri"_L1].toString();
if (geoUri.isEmpty()) {
return -100.0; // latitude runs from -90deg to +90deg so -100 is out of range.
}
@@ -864,7 +864,7 @@ float EventHandler::longitude(const Quotient::RoomEvent *event)
return -200.0;
}
const auto geoUri = event->contentJson()["geo_uri"_ls].toString();
const auto geoUri = event->contentJson()["geo_uri"_L1].toString();
if (geoUri.isEmpty()) {
return -200.0; // longitude runs from -180deg to +180deg so -200 is out of range.
}
@@ -879,7 +879,7 @@ QString EventHandler::locationAssetType(const Quotient::RoomEvent *event)
return {};
}
const auto assetType = event->contentJson()["org.matrix.msc3488.asset"_ls].toObject()["type"_ls].toString();
const auto assetType = event->contentJson()["org.matrix.msc3488.asset"_L1].toObject()["type"_L1].toString();
if (assetType.isEmpty()) {
return {};
}

View File

@@ -8,31 +8,31 @@ using namespace Quotient;
ImagePackEventContent::ImagePackEventContent(const QJsonObject &json)
{
if (json.contains(QStringLiteral("pack"))) {
if (json.contains("pack"_L1)) {
pack = ImagePackEventContent::Pack{
fromJson<std::optional<QString>>(json["pack"_ls].toObject()["display_name"_ls]),
fromJson<std::optional<QUrl>>(json["pack"_ls].toObject()["avatar_url"_ls]),
fromJson<std::optional<QStringList>>(json["pack"_ls].toObject()["usage"_ls]),
fromJson<std::optional<QString>>(json["pack"_ls].toObject()["attribution"_ls]),
fromJson<std::optional<QString>>(json["pack"_L1].toObject()["display_name"_L1]),
fromJson<std::optional<QUrl>>(json["pack"_L1].toObject()["avatar_url"_L1]),
fromJson<std::optional<QStringList>>(json["pack"_L1].toObject()["usage"_L1]),
fromJson<std::optional<QString>>(json["pack"_L1].toObject()["attribution"_L1]),
};
} else {
pack = std::nullopt;
}
const auto &keys = json["images"_ls].toObject().keys();
const auto &keys = json["images"_L1].toObject().keys();
for (const auto &k : keys) {
std::optional<EventContent::ImageInfo> info;
if (json["images"_ls][k].toObject().contains(QStringLiteral("info"))) {
info = EventContent::ImageInfo(QUrl(json["images"_ls][k]["url"_ls].toString()), json["images"_ls][k]["info"_ls].toObject(), k);
if (json["images"_L1][k].toObject().contains("info"_L1)) {
info = EventContent::ImageInfo(QUrl(json["images"_L1][k]["url"_L1].toString()), json["images"_L1][k]["info"_L1].toObject(), k);
} else {
info = std::nullopt;
}
images += ImagePackImage{
k,
fromJson<QUrl>(json["images"_ls][k]["url"_ls].toString()),
fromJson<std::optional<QString>>(json["images"_ls][k]["body"_ls]),
fromJson<QUrl>(json["images"_L1][k]["url"_L1].toString()),
fromJson<std::optional<QString>>(json["images"_L1][k]["body"_L1]),
info,
fromJson<std::optional<QStringList>>(json["images"_ls][k]["usage"_ls]),
fromJson<std::optional<QStringList>>(json["images"_L1][k]["usage"_L1]),
};
}
}
@@ -42,42 +42,42 @@ void ImagePackEventContent::fillJson(QJsonObject *o) const
if (pack) {
QJsonObject packJson;
if (pack->displayName) {
packJson["display_name"_ls] = *pack->displayName;
packJson["display_name"_L1] = *pack->displayName;
}
if (pack->usage) {
QJsonArray usageJson;
for (const auto &usage : *pack->usage) {
usageJson += usage;
}
packJson["usage"_ls] = usageJson;
packJson["usage"_L1] = usageJson;
}
if (pack->avatarUrl) {
packJson["avatar_url"_ls] = pack->avatarUrl->toString();
packJson["avatar_url"_L1] = pack->avatarUrl->toString();
}
if (pack->attribution) {
packJson["attribution"_ls] = *pack->attribution;
packJson["attribution"_L1] = *pack->attribution;
}
(*o)["pack"_ls] = packJson;
(*o)["pack"_L1] = packJson;
}
QJsonObject imagesJson;
for (const auto &image : images) {
QJsonObject imageJson;
imageJson["url"_ls] = image.url.toString();
imageJson["url"_L1] = image.url.toString();
if (image.body) {
imageJson["body"_ls] = *image.body;
imageJson["body"_L1] = *image.body;
}
if (image.usage) {
QJsonArray usageJson;
for (const auto &usage : *image.usage) {
usageJson += usage;
}
imageJson["usage"_ls] = usageJson;
imageJson["usage"_L1] = usageJson;
}
if (image.info.has_value()) {
imageJson["info"_ls] = Quotient::EventContent::toInfoJson(*image.info);
imageJson["info"_L1] = Quotient::EventContent::toInfoJson(*image.info);
}
imagesJson[image.shortcode] = imageJson;
}
(*o)["images"_ls] = imagesJson;
(*o)["images"_L1] = imagesJson;
}

View File

@@ -7,10 +7,10 @@ using namespace Quotient;
QString JoinRulesEvent::joinRule() const
{
return fromJson<QString>(contentJson()["join_rule"_ls]);
return fromJson<QString>(contentJson()["join_rule"_L1]);
}
QJsonArray JoinRulesEvent::allow() const
{
return contentJson()["allow"_ls].toArray();
return contentJson()["allow"_L1].toArray();
}

View File

@@ -12,12 +12,12 @@ PollStartEvent::PollStartEvent(const QJsonObject &obj)
int PollStartEvent::maxSelections() const
{
return contentJson()["org.matrix.msc3381.poll.start"_ls]["max_selections"_ls].toInt();
return contentJson()["org.matrix.msc3381.poll.start"_L1]["max_selections"_L1].toInt();
}
QString PollStartEvent::question() const
{
return contentJson()["org.matrix.msc3381.poll.start"_ls]["question"_ls]["body"_ls].toString();
return contentJson()["org.matrix.msc3381.poll.start"_L1]["question"_L1]["body"_L1].toString();
}
PollResponseEvent::PollResponseEvent(const QJsonObject &obj)
@@ -32,7 +32,7 @@ PollEndEvent::PollEndEvent(const QJsonObject &obj)
PollResponseEvent::PollResponseEvent(const QString &pollStartEventId, QStringList responses)
: RoomEvent(basicJson(TypeId,
{{"org.matrix.msc3381.poll.response"_ls, QJsonObject{{"answers"_ls, QJsonArray::fromStringList(responses)}}},
{"m.relates_to"_ls, QJsonObject{{"rel_type"_ls, "m.reference"_ls}, {"event_id"_ls, pollStartEventId}}}}))
{{"org.matrix.msc3381.poll.response"_L1, QJsonObject{{"answers"_L1, QJsonArray::fromStringList(responses)}}},
{"m.relates_to"_L1, QJsonObject{{"rel_type"_L1, "m.reference"_L1}, {"event_id"_L1, pollStartEventId}}}}))
{
}

View File

@@ -11,6 +11,8 @@
#include "neochatconnection.h"
using namespace Qt::StringLiterals;
IdentityServerHelper::IdentityServerHelper(QObject *parent)
: QObject(parent)
{
@@ -75,8 +77,8 @@ void IdentityServerHelper::checkUrl()
return;
}
const auto requestUrl = QUrl(m_url + QStringLiteral("/_matrix/identity/v2"));
if (!(requestUrl.scheme() == QStringLiteral("https") || requestUrl.scheme() == QStringLiteral("http"))) {
const auto requestUrl = QUrl(m_url + u"/_matrix/identity/v2"_s);
if (!(requestUrl.scheme() == u"https"_s || requestUrl.scheme() == u"http"_s)) {
m_status = Invalid;
Q_EMIT statusChanged();
return;
@@ -101,7 +103,7 @@ void IdentityServerHelper::setIdentityServer()
return;
}
m_connection->setAccountData(QLatin1String("m.identity_server"), {{QLatin1String("base_url"), m_url}});
m_connection->setAccountData(u"m.identity_server"_s, {{"base_url"_L1, m_url}});
m_status = Ready;
Q_EMIT statusChanged();
}
@@ -111,7 +113,7 @@ void IdentityServerHelper::clearIdentityServer()
if (m_connection->identityServer().isEmpty()) {
return;
}
m_connection->setAccountData(QLatin1String("m.identity_server"), {{QLatin1String("base_url"), QString()}});
m_connection->setAccountData(u"m.identity_server"_s, {{"base_url"_L1, QString()}});
m_status = Ready;
Q_EMIT statusChanged();
}

View File

@@ -6,11 +6,11 @@
using namespace Quotient;
NeochatAdd3PIdJob::NeochatAdd3PIdJob(const QString &clientSecret, const QString &sid, const std::optional<QJsonObject> &auth)
: BaseJob(HttpVerb::Post, QStringLiteral("Add3PIDJob"), makePath("/_matrix/client/v3", "/account/3pid/add"))
: BaseJob(HttpVerb::Post, u"Add3PIDJob"_s, makePath("/_matrix/client/v3", "/account/3pid/add"))
{
QJsonObject _dataJson;
addParam<IfNotEmpty>(_dataJson, QStringLiteral("auth"), auth);
addParam<>(_dataJson, QStringLiteral("client_secret"), clientSecret);
addParam<>(_dataJson, QStringLiteral("sid"), sid);
addParam<IfNotEmpty>(_dataJson, u"auth"_s, auth);
addParam<>(_dataJson, u"client_secret"_s, clientSecret);
addParam<>(_dataJson, u"sid"_s, sid);
setRequestData({_dataJson});
}

View File

@@ -6,11 +6,11 @@
using namespace Quotient;
NeochatChangePasswordJob::NeochatChangePasswordJob(const QString &newPassword, bool logoutDevices, const std::optional<QJsonObject> &auth)
: BaseJob(HttpVerb::Post, QStringLiteral("ChangePasswordJob"), "/_matrix/client/r0/account/password")
: BaseJob(HttpVerb::Post, u"ChangePasswordJob"_s, "/_matrix/client/r0/account/password")
{
QJsonObject _data;
addParam<>(_data, QStringLiteral("new_password"), newPassword);
addParam<IfNotEmpty>(_data, QStringLiteral("logout_devices"), logoutDevices);
addParam<IfNotEmpty>(_data, QStringLiteral("auth"), auth);
addParam<>(_data, u"new_password"_s, newPassword);
addParam<IfNotEmpty>(_data, u"logout_devices"_s, logoutDevices);
addParam<IfNotEmpty>(_data, u"auth"_s, auth);
setRequestData(_data);
}

View File

@@ -6,9 +6,9 @@
using namespace Quotient;
NeoChatDeactivateAccountJob::NeoChatDeactivateAccountJob(const std::optional<QJsonObject> &auth)
: BaseJob(HttpVerb::Post, QStringLiteral("DisableDeviceJob"), "_matrix/client/v3/account/deactivate")
: BaseJob(HttpVerb::Post, u"DisableDeviceJob"_s, "_matrix/client/v3/account/deactivate")
{
QJsonObject data;
addParam<IfNotEmpty>(data, QStringLiteral("auth"), auth);
addParam<IfNotEmpty>(data, u"auth"_s, auth);
setRequestData(data);
}

View File

@@ -6,9 +6,9 @@
using namespace Quotient;
NeochatDeleteDeviceJob::NeochatDeleteDeviceJob(const QString &deviceId, const std::optional<QJsonObject> &auth)
: BaseJob(HttpVerb::Delete, QStringLiteral("DeleteDeviceJob"), QStringLiteral("/_matrix/client/r0/devices/%1").arg(deviceId).toLatin1())
: BaseJob(HttpVerb::Delete, u"DeleteDeviceJob"_s, u"/_matrix/client/r0/devices/%1"_s.arg(deviceId).toLatin1())
{
QJsonObject _data;
addParam<IfNotEmpty>(_data, QStringLiteral("auth"), auth);
addParam<IfNotEmpty>(_data, u"auth"_s, auth);
setRequestData(std::move(_data));
}

View File

@@ -6,9 +6,6 @@
using namespace Quotient;
NeochatGetCommonRoomsJob::NeochatGetCommonRoomsJob(const QString &userId)
: BaseJob(HttpVerb::Get,
QStringLiteral("GetCommonRoomsJob"),
QStringLiteral("/_matrix/client/unstable/uk.half-shot.msc2666/user/mutual_rooms").toLatin1(),
QUrlQuery({{QStringLiteral("user_id"), userId}}))
: BaseJob(HttpVerb::Get, u"GetCommonRoomsJob"_s, "/_matrix/client/unstable/uk.half-shot.msc2666/user/mutual_rooms", QUrlQuery({{u"user_id"_s, userId}}))
{
}

View File

@@ -54,7 +54,7 @@ QUrl LinkPreviewer::url() const
void LinkPreviewer::loadUrlPreview()
{
if (m_url.scheme() == QStringLiteral("https")) {
if (m_url.scheme() == u"https"_s) {
m_loaded = false;
Q_EMIT loadedChanged();
@@ -72,11 +72,11 @@ void LinkPreviewer::loadUrlPreview()
connect(job, &BaseJob::success, this, [this, job, conn]() {
const auto json = job->jsonData();
m_title = json["og:title"_ls].toString().trimmed();
m_description = json["og:description"_ls].toString().trimmed().replace("\n"_ls, " "_ls);
m_title = json["og:title"_L1].toString().trimmed();
m_description = json["og:description"_L1].toString().trimmed().replace("\n"_L1, " "_L1);
auto imageUrl = QUrl(json["og:image"_ls].toString());
if (imageUrl.isValid() && imageUrl.scheme() == QStringLiteral("mxc")) {
auto imageUrl = QUrl(json["og:image"_L1].toString());
if (imageUrl.isValid() && imageUrl.scheme() == u"mxc"_s) {
m_imageSource = conn->makeMediaUrl(imageUrl);
} else {
m_imageSource = QUrl();
@@ -103,7 +103,7 @@ QList<QUrl> LinkPreviewer::linkPreviews(QString string)
QList<QUrl> links;
while (linksMatch.hasNext()) {
auto link = linksMatch.next().captured();
if (!link.contains(QStringLiteral("matrix.to")) && !links.contains(QUrl(link))) {
if (!link.contains(u"matrix.to"_s) && !links.contains(QUrl(link))) {
links += QUrl(link);
}
}

View File

@@ -13,6 +13,8 @@
#include <QMutex>
#include <QStandardPaths>
using namespace Qt::StringLiterals;
static QLoggingCategory::CategoryFilter oldCategoryFilter = nullptr;
static QtMessageHandler oldHandler = nullptr;
static bool e2eeDebugEnabled = false;
@@ -87,32 +89,32 @@ public:
QMutexLocker locker(&mutex);
QByteArray buf;
QTextStream str(&buf);
str << QDateTime::currentDateTime().toString(Qt::ISODate) << QStringLiteral(" [");
str << QDateTime::currentDateTime().toString(Qt::ISODate) << u" ["_s;
switch (type) {
case QtDebugMsg:
str << QStringLiteral("DEBUG");
str << u"DEBUG"_s;
break;
case QtInfoMsg:
str << QStringLiteral("INFO ");
str << u"INFO "_s;
break;
case QtWarningMsg:
str << QStringLiteral("WARN ");
str << u"WARN "_s;
break;
case QtFatalMsg:
str << QStringLiteral("FATAL");
str << u"FATAL"_s;
break;
case QtCriticalMsg:
str << QStringLiteral("CRITICAL");
str << u"CRITICAL"_s;
break;
}
str << QStringLiteral("] ") << context.category << QStringLiteral(": ");
str << u"] "_s << context.category << u": "_s;
if (context.file && *context.file && context.line) {
str << context.file << QStringLiteral(":") << context.line << QStringLiteral(": ");
str << context.file << u":"_s << context.line << u": "_s;
}
if (context.function && *context.function) {
str << context.function << QStringLiteral(": ");
str << context.function << u": "_s;
}
str << message << QStringLiteral("\n");
str << message << u"\n"_s;
str.flush();
file.write(buf.constData(), buf.size());
file.flush();
@@ -129,18 +131,18 @@ public:
if (file.isOpen()) {
file.close();
}
const auto &filePath = QStringLiteral("%1%2%3").arg(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation), QDir::separator(), appName);
const auto &filePath = u"%1%2%3"_s.arg(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation), QDir::separator(), appName);
QDir dir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QDir::separator());
auto entryList = dir.entryList({appName + QStringLiteral(".*")});
auto entryList = dir.entryList({appName + u".*"_s});
std::sort(entryList.begin(), entryList.end(), [](const auto &left, const auto &right) {
auto leftIndex = left.split(QStringLiteral(".")).last().toInt();
auto rightIndex = right.split(QStringLiteral(".")).last().toInt();
auto leftIndex = left.split(u"."_s).last().toInt();
auto rightIndex = right.split(u"."_s).last().toInt();
return leftIndex > rightIndex;
});
for (const auto &entry : entryList) {
bool ok = false;
const auto index = entry.split(QStringLiteral(".")).last().toInt(&ok);
const auto index = entry.split(u"."_s).last().toInt(&ok);
if (!ok) {
continue;
}
@@ -151,7 +153,7 @@ public:
file.remove();
continue;
}
const auto &newName = QStringLiteral("%1.%2").arg(filePath, QString::number(index + 1));
const auto &newName = u"%1.%2"_s.arg(filePath, QString::number(index + 1));
const auto success = file.copy(newName);
if (success) {
file.remove();
@@ -168,7 +170,7 @@ public:
if (!finfo.absoluteDir().exists()) {
QDir().mkpath(finfo.absolutePath());
}
file.setFileName(filePath + QStringLiteral(".0"));
file.setFileName(filePath + u".0"_s);
file.open(QIODevice::WriteOnly | QIODevice::Unbuffered);
}
@@ -215,7 +217,7 @@ void initLogging()
oldCategoryFilter = QLoggingCategory::installFilter(filter);
oldHandler = qInstallMessageHandler(messageHandler);
sInstance->setOrigHandler(oldHandler);
sInstance->setName(QStringLiteral("neochat.log"));
sInstance->setName(u"neochat.log"_s);
}
#include "logger.moc"

View File

@@ -25,14 +25,14 @@ void LoginHelper::init()
m_connection = new NeoChatConnection();
m_matrixId = QString();
m_password = QString();
m_deviceName = QStringLiteral("NeoChat");
m_deviceName = u"NeoChat"_s;
m_supportsSso = false;
m_supportsPassword = false;
m_ssoUrl = QUrl();
connect(this, &LoginHelper::matrixIdChanged, this, [this]() {
setHomeserverReachable(false);
QRegularExpression validator(QStringLiteral("^\\@?[a-zA-Z0-9\\._=\\-/]+\\:[a-zA-Z0-9\\-]+(\\.[a-zA-Z0-9\\-]+)*(\\:[0-9]+)?$"));
QRegularExpression validator(u"^\\@?[a-zA-Z0-9\\._=\\-/]+\\:[a-zA-Z0-9\\-]+(\\.[a-zA-Z0-9\\-]+)*(\\:[0-9]+)?$"_s);
if (!validator.match(m_matrixId).hasMatch()) {
return;
}
@@ -89,7 +89,7 @@ void LoginHelper::init()
Q_EMIT isLoggingInChanged();
});
connect(m_connection, &Connection::loginError, this, [this](QString error, const QString &) {
if (error == QStringLiteral("Invalid username or password")) {
if (error == u"Invalid username or password"_s) {
setInvalidPassword(true);
} else {
Q_EMIT loginErrorOccured(i18n("Login Failed: %1", error));

View File

@@ -77,11 +77,11 @@ class NetworkAccessManagerFactory : public QQmlNetworkAccessManagerFactory
auto nam = NetworkAccessManager::instance();
nam->setRedirectPolicy(QNetworkRequest::NoLessSafeRedirectPolicy);
nam->enableStrictTransportSecurityStore(true, QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QLatin1String("/hsts/"));
nam->enableStrictTransportSecurityStore(true, QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + u"/hsts/"_s);
nam->setStrictTransportSecurityEnabled(true);
auto namDiskCache = new QNetworkDiskCache(nam);
namDiskCache->setCacheDirectory(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QLatin1String("/nam/"));
namDiskCache->setCacheDirectory(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + u"/nam/"_s);
nam->setCache(namDiskCache);
return nam;
@@ -111,13 +111,13 @@ int main(int argc, char *argv[])
#ifdef Q_OS_ANDROID
QGuiApplication app(argc, argv);
QQuickStyle::setStyle(QStringLiteral("org.kde.breeze"));
QQuickStyle::setStyle(u"org.kde.breeze"_s);
#else
QIcon::setFallbackThemeName("breeze"_ls);
QIcon::setFallbackThemeName("breeze"_L1);
QApplication app(argc, argv);
// Default to org.kde.desktop style unless the user forces another style
if (qEnvironmentVariableIsEmpty("QT_QUICK_CONTROLS_STYLE")) {
QQuickStyle::setStyle(QStringLiteral("org.kde.desktop"));
QQuickStyle::setStyle(u"org.kde.desktop"_s);
}
#endif
@@ -127,45 +127,41 @@ int main(int argc, char *argv[])
freopen("CONOUT$", "w", stderr);
}
QApplication::setStyle(QStringLiteral("breeze"));
QFont font(QStringLiteral("Segoe UI Emoji"));
QApplication::setStyle(u"breeze"_s);
QFont font(u"Segoe UI Emoji"_s);
font.setPointSize(10);
font.setHintingPreference(QFont::PreferNoHinting);
app.setFont(font);
#endif
KLocalizedString::setApplicationDomain(QByteArrayLiteral("neochat"));
QGuiApplication::setOrganizationName("KDE"_ls);
QGuiApplication::setOrganizationName("KDE"_L1);
KAboutData about(QStringLiteral("neochat"),
KAboutData about(u"neochat"_s,
i18n("NeoChat"),
QStringLiteral(NEOCHAT_VERSION_STRING),
i18n("Chat on Matrix"),
KAboutLicense::GPL_V3,
i18n("© 2018-2020 Black Hat, 2020-2024 KDE Community"));
about.addAuthor(i18n("Carl Schwan"),
i18n("Maintainer"),
QStringLiteral("carl@carlschwan.eu"),
QStringLiteral("https://carlschwan.eu"),
QUrl(QStringLiteral("https://carlschwan.eu/avatar.png")));
about.addAuthor(i18n("Tobias Fella"), i18n("Maintainer"), QStringLiteral("tobias.fella@kde.org"), QStringLiteral("https://tobiasfella.de"));
about.addAuthor(i18n("James Graham"), i18n("Maintainer"), QStringLiteral("james.h.graham@protonmail.com"));
about.addCredit(i18n("Black Hat"), i18n("Original author of Spectral"), QStringLiteral("bhat@encom.eu.org"));
about.addCredit(i18n("Alexey Rusakov"), i18n("Maintainer of libQuotient"), QStringLiteral("Kitsune-Ral@users.sf.net"));
about.addAuthor(i18n("Carl Schwan"), i18n("Maintainer"), u"carl@carlschwan.eu"_s, u"https://carlschwan.eu"_s, QUrl(u"https://carlschwan.eu/avatar.png"_s));
about.addAuthor(i18n("Tobias Fella"), i18n("Maintainer"), u"tobias.fella@kde.org"_s, u"https://tobiasfella.de"_s);
about.addAuthor(i18n("James Graham"), i18n("Maintainer"), u"james.h.graham@protonmail.com"_s);
about.addCredit(i18n("Black Hat"), i18n("Original author of Spectral"), u"bhat@encom.eu.org"_s);
about.addCredit(i18n("Alexey Rusakov"), i18n("Maintainer of libQuotient"), u"Kitsune-Ral@users.sf.net"_s);
about.setTranslator(i18nc("NAME OF TRANSLATORS", "Your names"), i18nc("EMAIL OF TRANSLATORS", "Your emails"));
about.setOrganizationDomain("kde.org");
about.addComponent(QStringLiteral("libQuotient"),
about.addComponent(u"libQuotient"_s,
i18n("A Qt library to write cross-platform clients for Matrix"),
i18nc("<version number> (built against <possibly different version number>)",
"%1 (built against %2)",
Quotient::versionString(),
QStringLiteral(Quotient_VERSION_STRING)),
QStringLiteral("https://github.com/quotient-im/libquotient"),
u"https://github.com/quotient-im/libquotient"_s,
KAboutLicense::LGPL_V2_1);
KAboutData::setApplicationData(about);
QGuiApplication::setWindowIcon(QIcon::fromTheme(QStringLiteral("org.kde.neochat")));
QGuiApplication::setWindowIcon(QIcon::fromTheme(u"org.kde.neochat"_s));
#if __has_include("KCrash")
KCrash::initialize();
@@ -179,34 +175,33 @@ int main(int argc, char *argv[])
#ifdef NEOCHAT_FLATPAK
// Copy over the included FontConfig configuration to the
// app's config dir:
QFile::copy(QStringLiteral("/app/etc/fonts/conf.d/99-noto-mono-color-emoji.conf"),
QStringLiteral("/var/config/fontconfig/conf.d/99-noto-mono-color-emoji.conf"));
QFile::copy(u"/app/etc/fonts/conf.d/99-noto-mono-color-emoji.conf"_s, u"/var/config/fontconfig/conf.d/99-noto-mono-color-emoji.conf"_s);
#endif
ColorSchemer colorScheme;
QCommandLineParser parser;
parser.setApplicationDescription(i18n("Client for the matrix communication protocol"));
parser.addPositionalArgument(QStringLiteral("urls"), i18n("Supports matrix: url scheme"));
parser.addOption(QCommandLineOption("ignore-ssl-errors"_ls, i18n("Ignore all SSL Errors, e.g., unsigned certificates.")));
parser.addPositionalArgument(u"urls"_s, i18n("Supports matrix: url scheme"));
parser.addOption(QCommandLineOption("ignore-ssl-errors"_L1, i18n("Ignore all SSL Errors, e.g., unsigned certificates.")));
QCommandLineOption testOption("test"_ls, i18n("Only used for autotests"));
QCommandLineOption testOption("test"_L1, i18n("Only used for autotests"));
testOption.setFlags(QCommandLineOption::HiddenFromHelp);
parser.addOption(testOption);
#ifdef HAVE_KUNIFIEDPUSH
QCommandLineOption dbusActivatedOption(QStringLiteral("dbus-activated"), i18n("Internal usage only."));
QCommandLineOption dbusActivatedOption(u"dbus-activated"_s, i18n("Internal usage only."));
dbusActivatedOption.setFlags(QCommandLineOption::Flag::HiddenFromHelp);
parser.addOption(dbusActivatedOption);
#endif
QCommandLineOption shareOption(QStringLiteral("share"), i18n("Share a URL to Matrix"), QStringLiteral("text"));
QCommandLineOption shareOption(u"share"_s, i18n("Share a URL to Matrix"), u"text"_s);
parser.addOption(shareOption);
about.setupCommandLine(&parser);
parser.process(app);
about.processCommandLine(&parser);
Controller::setTestMode(parser.isSet("test"_ls));
Controller::setTestMode(parser.isSet("test"_L1));
#ifdef HAVE_KUNIFIEDPUSH
if (parser.isSet(dbusActivatedOption)) {
@@ -218,7 +213,7 @@ int main(int argc, char *argv[])
// Because KRunner may call us on the D-Bus (under the same service name org.kde.neochat) then it may
// accidentally activate us for push notifications instead. If this happens, then immediately quit if the fake
// runner is called.
QDBusConnection::sessionBus().registerObject("/RoomRunner"_ls, new FakeRunner(), QDBusConnection::ExportScriptableContents);
QDBusConnection::sessionBus().registerObject("/RoomRunner"_L1, new FakeRunner(), QDBusConnection::ExportScriptableContents);
#endif
Controller::listenForNotifications();
@@ -259,7 +254,7 @@ int main(int argc, char *argv[])
auto args = arguments;
args.removeFirst();
if (args.length() == 2 && args[0] == "--share"_ls) {
if (args.length() == 2 && args[0] == "--share"_L1) {
ShareHandler::instance().setText(args[1]);
return;
}
@@ -273,30 +268,30 @@ int main(int argc, char *argv[])
engine.rootContext()->setContextObject(new KLocalizedContext(&engine));
engine.setNetworkAccessManagerFactory(new NetworkAccessManagerFactory());
if (parser.isSet("ignore-ssl-errors"_ls)) {
if (parser.isSet("ignore-ssl-errors"_L1)) {
QObject::connect(NetworkAccessManager::instance(), &QNetworkAccessManager::sslErrors, NetworkAccessManager::instance(), [](QNetworkReply *reply) {
reply->ignoreSslErrors();
});
}
if (parser.isSet("share"_ls)) {
if (parser.isSet("share"_L1)) {
ShareHandler::instance().setText(parser.value(shareOption));
}
engine.addImageProvider(QLatin1String("blurhash"), new BlurhashImageProvider);
engine.addImageProvider(u"blurhash"_s, new BlurhashImageProvider);
engine.loadFromModule("org.kde.neochat", "Main");
if (engine.rootObjects().isEmpty()) {
return -1;
}
if (!parser.positionalArguments().isEmpty() && !parser.isSet("share"_ls)) {
if (!parser.positionalArguments().isEmpty() && !parser.isSet("share"_L1)) {
RoomManager::instance().setUrlArgument(parser.positionalArguments()[0]);
}
#ifdef HAVE_RUNNER
auto runner = Runner::create(&engine, &engine);
QDBusConnection::sessionBus().registerObject("/RoomRunner"_ls, runner, QDBusConnection::ExportScriptableContents);
QDBusConnection::sessionBus().registerObject("/RoomRunner"_L1, runner, QDBusConnection::ExportScriptableContents);
#endif
QWindow *window = windowFromEngine(&engine);

View File

@@ -49,19 +49,19 @@ QVariant AccountEmoticonModel::data(const QModelIndex &index, int role) const
}
if (role == IsStickerRole) {
if (image.usage) {
return image.usage->isEmpty() || image.usage->contains("sticker"_ls);
return image.usage->isEmpty() || image.usage->contains("sticker"_L1);
}
if (m_images->pack && m_images->pack->usage) {
return m_images->pack->usage->isEmpty() || m_images->pack->usage->contains("sticker"_ls);
return m_images->pack->usage->isEmpty() || m_images->pack->usage->contains("sticker"_L1);
}
return true;
}
if (role == IsEmojiRole) {
if (image.usage) {
return image.usage->isEmpty() || image.usage->contains("emoticon"_ls);
return image.usage->isEmpty() || image.usage->contains("emoticon"_L1);
}
if (m_images->pack && m_images->pack->usage) {
return m_images->pack->usage->isEmpty() || m_images->pack->usage->contains("emoticon"_ls);
return m_images->pack->usage->isEmpty() || m_images->pack->usage->contains("emoticon"_L1);
}
return true;
}
@@ -93,7 +93,7 @@ void AccountEmoticonModel::setConnection(NeoChatConnection *connection)
m_connection = connection;
Q_EMIT connectionChanged();
connect(m_connection, &Connection::accountDataChanged, this, [this](QString type) {
if (type == QStringLiteral("im.ponies.user_emotes")) {
if (type == u"im.ponies.user_emotes"_s) {
reloadEmoticons();
}
});
@@ -107,8 +107,8 @@ void AccountEmoticonModel::reloadEmoticons()
}
QJsonObject json;
if (m_connection->hasAccountData("im.ponies.user_emotes"_ls)) {
json = m_connection->accountData("im.ponies.user_emotes"_ls)->contentJson();
if (m_connection->hasAccountData("im.ponies.user_emotes"_L1)) {
json = m_connection->accountData("im.ponies.user_emotes"_L1)->contentJson();
}
const auto &content = ImagePackEventContent(json);
beginResetModel();
@@ -125,7 +125,7 @@ void AccountEmoticonModel::deleteEmoticon(int index)
QJsonObject data;
m_images->images.removeAt(index);
m_images->fillJson(&data);
m_connection->setAccountData("im.ponies.user_emotes"_ls, data);
m_connection->setAccountData("im.ponies.user_emotes"_L1, data);
}
void AccountEmoticonModel::setEmoticonBody(int index, const QString &text)
@@ -137,7 +137,7 @@ void AccountEmoticonModel::setEmoticonBody(int index, const QString &text)
m_images->images[index].body = text;
QJsonObject data;
m_images->fillJson(&data);
m_connection->setAccountData("im.ponies.user_emotes"_ls, data);
m_connection->setAccountData("im.ponies.user_emotes"_L1, data);
}
void AccountEmoticonModel::setEmoticonShortcode(int index, const QString &shortcode)
@@ -149,7 +149,7 @@ void AccountEmoticonModel::setEmoticonShortcode(int index, const QString &shortc
m_images->images[index].shortcode = shortcode;
QJsonObject data;
m_images->fillJson(&data);
m_connection->setAccountData("im.ponies.user_emotes"_ls, data);
m_connection->setAccountData("im.ponies.user_emotes"_L1, data);
}
void AccountEmoticonModel::setEmoticonImage(int index, const QUrl &source)
@@ -169,17 +169,17 @@ QCoro::Task<void> AccountEmoticonModel::doSetEmoticonImage(int index, QUrl sourc
}
m_images->images[index].url = job->contentUri();
auto mime = QMimeDatabase().mimeTypeForUrl(source);
source.setScheme("file"_ls);
source.setScheme("file"_L1);
QFileInfo fileInfo(source.isLocalFile() ? source.toLocalFile() : source.toString());
EventContent::ImageInfo info;
if (mime.name().startsWith("image/"_ls)) {
if (mime.name().startsWith("image/"_L1)) {
QImage image(source.toLocalFile());
info = EventContent::ImageInfo(source, fileInfo.size(), mime, image.size(), fileInfo.fileName());
}
m_images->images[index].info = info;
QJsonObject data;
m_images->fillJson(&data);
m_connection->setAccountData("im.ponies.user_emotes"_ls, data);
m_connection->setAccountData("im.ponies.user_emotes"_L1, data);
}
QCoro::Task<void> AccountEmoticonModel::doAddEmoticon(QUrl source, QString shortcode, QString description, QString type)
@@ -191,10 +191,10 @@ QCoro::Task<void> AccountEmoticonModel::doAddEmoticon(QUrl source, QString short
}
auto mime = QMimeDatabase().mimeTypeForUrl(source);
source.setScheme("file"_ls);
source.setScheme("file"_L1);
QFileInfo fileInfo(source.isLocalFile() ? source.toLocalFile() : source.toString());
EventContent::ImageInfo info;
if (mime.name().startsWith("image/"_ls)) {
if (mime.name().startsWith("image/"_L1)) {
QImage image(source.toLocalFile());
info = EventContent::ImageInfo(source, fileInfo.size(), mime, image.size(), fileInfo.fileName());
}
@@ -208,7 +208,7 @@ QCoro::Task<void> AccountEmoticonModel::doAddEmoticon(QUrl source, QString short
});
QJsonObject data;
m_images->fillJson(&data);
m_connection->setAccountData("im.ponies.user_emotes"_ls, data);
m_connection->setAccountData("im.ponies.user_emotes"_L1, data);
}
void AccountEmoticonModel::addEmoticon(const QUrl &source, const QString &shortcode, const QString &description, const QString &type)

View File

@@ -20,17 +20,17 @@ using Action = ActionsModel::Action;
using namespace Quotient;
using namespace Qt::StringLiterals;
QStringList rainbowColors{"#ff2b00"_ls, "#ff5500"_ls, "#ff8000"_ls, "#ffaa00"_ls, "#ffd500"_ls, "#ffff00"_ls, "#d4ff00"_ls, "#aaff00"_ls, "#80ff00"_ls,
"#55ff00"_ls, "#2bff00"_ls, "#00ff00"_ls, "#00ff2b"_ls, "#00ff55"_ls, "#00ff80"_ls, "#00ffaa"_ls, "#00ffd5"_ls, "#00ffff"_ls,
"#00d4ff"_ls, "#00aaff"_ls, "#007fff"_ls, "#0055ff"_ls, "#002bff"_ls, "#0000ff"_ls, "#2a00ff"_ls, "#5500ff"_ls, "#7f00ff"_ls,
"#aa00ff"_ls, "#d400ff"_ls, "#ff00ff"_ls, "#ff00d4"_ls, "#ff00aa"_ls, "#ff0080"_ls, "#ff0055"_ls, "#ff002b"_ls, "#ff0000"_ls};
QStringList rainbowColors{"#ff2b00"_L1, "#ff5500"_L1, "#ff8000"_L1, "#ffaa00"_L1, "#ffd500"_L1, "#ffff00"_L1, "#d4ff00"_L1, "#aaff00"_L1, "#80ff00"_L1,
"#55ff00"_L1, "#2bff00"_L1, "#00ff00"_L1, "#00ff2b"_L1, "#00ff55"_L1, "#00ff80"_L1, "#00ffaa"_L1, "#00ffd5"_L1, "#00ffff"_L1,
"#00d4ff"_L1, "#00aaff"_L1, "#007fff"_L1, "#0055ff"_L1, "#002bff"_L1, "#0000ff"_L1, "#2a00ff"_L1, "#5500ff"_L1, "#7f00ff"_L1,
"#aa00ff"_L1, "#d400ff"_L1, "#ff00ff"_L1, "#ff00d4"_L1, "#ff00aa"_L1, "#ff0080"_L1, "#ff0055"_L1, "#ff002b"_L1, "#ff0000"_L1};
auto leaveRoomLambda = [](const QString &text, NeoChatRoom *room, ChatBarCache *) {
if (text.isEmpty()) {
Q_EMIT room->showMessage(MessageType::Information, i18n("Leaving this room."));
room->connection()->leaveRoom(room);
} else {
QRegularExpression roomRegex(QStringLiteral(R"(^[#!][^:]+:\w(?:\w|\.|-)*\.\w+(?::\d{1,5})?)"));
QRegularExpression roomRegex(uR"(^[#!][^:]+:\w(?:\w|\.|-)*\.\w+(?::\d{1,5})?)"_s);
auto regexMatch = roomRegex.match(text);
if (!regexMatch.hasMatch()) {
Q_EMIT room->showMessage(MessageType::Error,
@@ -62,9 +62,9 @@ auto roomNickLambda = [](const QString &text, NeoChatRoom *room, ChatBarCache *)
QList<ActionsModel::Action> actions{
Action{
QStringLiteral("shrug"),
u"shrug"_s,
[](const QString &message, NeoChatRoom *, ChatBarCache *) {
return QStringLiteral("¯\\\\_(ツ)_/¯ %1").arg(message);
return u"¯\\\\_(ツ)_/¯ %1"_s.arg(message);
},
true,
std::nullopt,
@@ -72,9 +72,9 @@ QList<ActionsModel::Action> actions{
kli18n("Prepends ¯\\_(ツ)_/¯ to a plain-text message"),
},
Action{
QStringLiteral("lenny"),
u"lenny"_s,
[](const QString &message, NeoChatRoom *, ChatBarCache *) {
return QStringLiteral("( ͡° ͜ʖ ͡°) %1").arg(message);
return u"( ͡° ͜ʖ ͡°) %1"_s.arg(message);
},
true,
std::nullopt,
@@ -82,9 +82,9 @@ QList<ActionsModel::Action> actions{
kli18n("Prepends ( ͡° ͜ʖ ͡°) to a plain-text message"),
},
Action{
QStringLiteral("tableflip"),
u"tableflip"_s,
[](const QString &message, NeoChatRoom *, ChatBarCache *) {
return QStringLiteral("(╯°□°)╯︵ ┻━┻ %1").arg(message);
return u"(╯°□°)╯︵ ┻━┻ %1"_s.arg(message);
},
true,
std::nullopt,
@@ -92,9 +92,9 @@ QList<ActionsModel::Action> actions{
kli18n("Prepends (╯°□°)╯︵ ┻━┻ to a plain-text message"),
},
Action{
QStringLiteral("unflip"),
u"unflip"_s,
[](const QString &message, NeoChatRoom *, ChatBarCache *) {
return QStringLiteral("┬──┬ ( ゜-゜ノ) %1").arg(message);
return u"┬──┬ ( ゜-゜ノ) %1"_s.arg(message);
},
true,
std::nullopt,
@@ -102,11 +102,11 @@ QList<ActionsModel::Action> actions{
kli18n("Prepends ┬──┬ ( ゜-゜ノ) to a plain-text message"),
},
Action{
QStringLiteral("rainbow"),
u"rainbow"_s,
[](const QString &text, NeoChatRoom *room, ChatBarCache *chatBarCache) {
QString rainbowText;
for (int i = 0; i < text.length(); i++) {
rainbowText += QStringLiteral("<font color='%2'>%3</font>").arg(rainbowColors[i % rainbowColors.length()], text.at(i));
rainbowText += u"<font color='%2'>%3</font>"_s.arg(rainbowColors[i % rainbowColors.length()], text.at(i));
}
// Ideally, we would just return rainbowText and let that do the rest, but the colors don't survive markdownToHTML.
auto content = std::make_unique<Quotient::EventContent::TextContent>(rainbowText, u"text/html"_s);
@@ -121,11 +121,11 @@ QList<ActionsModel::Action> actions{
kli18n("Sends the given message colored as a rainbow"),
},
Action{
QStringLiteral("rainbowme"),
u"rainbowme"_s,
[](const QString &text, NeoChatRoom *room, ChatBarCache *chatBarCache) {
QString rainbowText;
for (int i = 0; i < text.length(); i++) {
rainbowText += QStringLiteral("<font color='%2'>%3</font>").arg(rainbowColors[i % rainbowColors.length()], text.at(i));
rainbowText += u"<font color='%2'>%3</font>"_s.arg(rainbowColors[i % rainbowColors.length()], text.at(i));
}
// Ideally, we would just return rainbowText and let that do the rest, but the colors don't survive markdownToHTML.
auto content = std::make_unique<Quotient::EventContent::TextContent>(rainbowText, u"text/html"_s);
@@ -140,7 +140,7 @@ QList<ActionsModel::Action> actions{
kli18n("Sends the given emote colored as a rainbow"),
},
Action{
QStringLiteral("plain"),
u"plain"_s,
[](const QString &text, NeoChatRoom *room, ChatBarCache *) {
room->postPlainText(text.toHtmlEscaped());
return QString();
@@ -151,7 +151,7 @@ QList<ActionsModel::Action> actions{
kli18n("Sends the given message as plain text"),
},
Action{
QStringLiteral("spoiler"),
u"spoiler"_s,
[](const QString &text, NeoChatRoom *room, ChatBarCache *chatBarCache) {
// Ideally, we would just return rainbowText and let that do the rest, but the colors don't survive markdownToHTML.
auto content = std::make_unique<Quotient::EventContent::TextContent>(u"<span data-mx-spoiler>%1</span>"_s.arg(text), u"text/html"_s);
@@ -166,7 +166,7 @@ QList<ActionsModel::Action> actions{
kli18n("Sends the given message as a spoiler"),
},
Action{
QStringLiteral("me"),
u"me"_s,
[](const QString &text, NeoChatRoom *, ChatBarCache *) {
return text;
},
@@ -176,7 +176,7 @@ QList<ActionsModel::Action> actions{
kli18n("Sends the given emote"),
},
Action{
QStringLiteral("notice"),
u"notice"_s,
[](const QString &text, NeoChatRoom *, ChatBarCache *) {
return text;
},
@@ -186,10 +186,9 @@ QList<ActionsModel::Action> actions{
kli18n("Sends the given message as a notice"),
},
Action{
QStringLiteral("invite"),
u"invite"_s,
[](const QString &text, NeoChatRoom *room, ChatBarCache *) {
static const QRegularExpression mxidRegex(
QStringLiteral(R"((^|[][[:space:](){}`'";])([!#@][-a-z0-9_=#/.]{1,252}:\w(?:\w|\.|-)*\.\w+(?::\d{1,5})?))"));
static const QRegularExpression mxidRegex(uR"((^|[][[:space:](){}`'";])([!#@][-a-z0-9_=#/.]{1,252}:\w(?:\w|\.|-)*\.\w+(?::\d{1,5})?))"_s);
auto regexMatch = mxidRegex.match(text);
if (!regexMatch.hasMatch()) {
Q_EMIT room->showMessage(MessageType::Error, i18nc("'<text>' does not look like a matrix id.", "'%1' does not look like a matrix id.", text));
@@ -223,9 +222,9 @@ QList<ActionsModel::Action> actions{
kli18n("Invites the user to this room"),
},
Action{
QStringLiteral("join"),
u"join"_s,
[](const QString &text, NeoChatRoom *room, ChatBarCache *) {
QRegularExpression roomRegex(QStringLiteral(R"(^[#!][^:]+:\w(?:\w|\.|-)*\.\w+(?::\d{1,5})?)"));
QRegularExpression roomRegex(uR"(^[#!][^:]+:\w(?:\w|\.|-)*\.\w+(?::\d{1,5})?)"_s);
auto regexMatch = roomRegex.match(text);
if (!regexMatch.hasMatch()) {
Q_EMIT room->showMessage(MessageType::Error,
@@ -238,7 +237,7 @@ QList<ActionsModel::Action> actions{
return QString();
}
Q_EMIT room->showMessage(MessageType::Information, i18nc("Joining room <roomname>.", "Joining room %1.", text));
RoomManager::instance().resolveResource(text, "join"_ls);
RoomManager::instance().resolveResource(text, "join"_L1);
return QString();
},
false,
@@ -247,11 +246,11 @@ QList<ActionsModel::Action> actions{
kli18n("Joins the given room"),
},
Action{
QStringLiteral("knock"),
u"knock"_s,
[](const QString &text, NeoChatRoom *room, ChatBarCache *) {
auto parts = text.split(QLatin1String(" "));
auto parts = text.split(u" "_s);
QString roomName = parts[0];
QRegularExpression roomRegex(QStringLiteral(R"(^[#!][^:]+:\w(?:\w|\.|-)*\.\w+(?::\d{1,5})?)"));
QRegularExpression roomRegex(uR"(^[#!][^:]+:\w(?:\w|\.|-)*\.\w+(?::\d{1,5})?)"_s);
auto regexMatch = roomRegex.match(roomName);
if (!regexMatch.hasMatch()) {
Q_EMIT room->showMessage(MessageType::Error,
@@ -265,7 +264,7 @@ QList<ActionsModel::Action> actions{
}
Q_EMIT room->showMessage(MessageType::Information, i18nc("Knocking room <roomname>.", "Knocking room %1.", text));
auto connection = dynamic_cast<NeoChatConnection *>(room->connection());
const auto knownServer = roomName.mid(roomName.indexOf(":"_ls) + 1);
const auto knownServer = roomName.mid(roomName.indexOf(":"_L1) + 1);
if (parts.length() >= 2) {
RoomManager::instance().knockRoom(connection, roomName, parts[1], QStringList{knownServer});
} else {
@@ -279,9 +278,9 @@ QList<ActionsModel::Action> actions{
kli18n("Requests to join the given room"),
},
Action{
QStringLiteral("j"),
u"j"_s,
[](const QString &text, NeoChatRoom *room, ChatBarCache *) {
QRegularExpression roomRegex(QStringLiteral(R"(^[#!][^:]+:\w(?:\w|\.|-)*\.\w+(?::\d{1,5})?)"));
QRegularExpression roomRegex(uR"(^[#!][^:]+:\w(?:\w|\.|-)*\.\w+(?::\d{1,5})?)"_s);
auto regexMatch = roomRegex.match(text);
if (!regexMatch.hasMatch()) {
Q_EMIT room->showMessage(MessageType::Error,
@@ -293,7 +292,7 @@ QList<ActionsModel::Action> actions{
return QString();
}
Q_EMIT room->showMessage(MessageType::Information, i18nc("Joining room <roomname>.", "Joining room %1.", text));
RoomManager::instance().resolveResource(text, "join"_ls);
RoomManager::instance().resolveResource(text, "join"_L1);
return QString();
},
false,
@@ -302,7 +301,7 @@ QList<ActionsModel::Action> actions{
kli18n("Joins the given room"),
},
Action{
QStringLiteral("part"),
u"part"_s,
leaveRoomLambda,
false,
std::nullopt,
@@ -310,7 +309,7 @@ QList<ActionsModel::Action> actions{
kli18n("Leaves the given room or this room, if there is none given"),
},
Action{
QStringLiteral("leave"),
u"leave"_s,
leaveRoomLambda,
false,
std::nullopt,
@@ -318,7 +317,7 @@ QList<ActionsModel::Action> actions{
kli18n("Leaves the given room or this room, if there is none given"),
},
Action{
QStringLiteral("nick"),
u"nick"_s,
[](const QString &text, NeoChatRoom *room, ChatBarCache *) {
if (text.isEmpty()) {
Q_EMIT room->showMessage(MessageType::Error, i18n("No new nickname provided, no changes will happen."));
@@ -333,7 +332,7 @@ QList<ActionsModel::Action> actions{
kli18n("Changes your global display name"),
},
Action{
QStringLiteral("roomnick"),
u"roomnick"_s,
roomNickLambda,
false,
std::nullopt,
@@ -341,7 +340,7 @@ QList<ActionsModel::Action> actions{
kli18n("Changes your display name in this room"),
},
Action{
QStringLiteral("myroomnick"),
u"myroomnick"_s,
roomNickLambda,
false,
std::nullopt,
@@ -349,10 +348,9 @@ QList<ActionsModel::Action> actions{
kli18n("Changes your display name in this room"),
},
Action{
QStringLiteral("ignore"),
u"ignore"_s,
[](const QString &text, NeoChatRoom *room, ChatBarCache *) {
static const QRegularExpression mxidRegex(
QStringLiteral(R"((^|[][[:space:](){}`'";])([!#@][-a-z0-9_=#/.]{1,252}:\w(?:\w|\.|-)*\.\w+(?::\d{1,5})?))"));
static const QRegularExpression mxidRegex(uR"((^|[][[:space:](){}`'";])([!#@][-a-z0-9_=#/.]{1,252}:\w(?:\w|\.|-)*\.\w+(?::\d{1,5})?))"_s);
auto regexMatch = mxidRegex.match(text);
if (!regexMatch.hasMatch()) {
Q_EMIT room->showMessage(MessageType::Error, i18nc("'<text>' does not look like a matrix id.", "'%1' does not look like a matrix id.", text));
@@ -373,10 +371,9 @@ QList<ActionsModel::Action> actions{
kli18n("Ignores the given user"),
},
Action{
QStringLiteral("unignore"),
u"unignore"_s,
[](const QString &text, NeoChatRoom *room, ChatBarCache *) {
static const QRegularExpression mxidRegex(
QStringLiteral(R"((^|[][[:space:](){}`'";])([!#@][-a-z0-9_=#/.]{1,252}:\w(?:\w|\.|-)*\.\w+(?::\d{1,5})?))"));
static const QRegularExpression mxidRegex(uR"((^|[][[:space:](){}`'";])([!#@][-a-z0-9_=#/.]{1,252}:\w(?:\w|\.|-)*\.\w+(?::\d{1,5})?))"_s);
auto regexMatch = mxidRegex.match(text);
if (!regexMatch.hasMatch()) {
Q_EMIT room->showMessage(MessageType::Error, i18nc("'<text>' does not look like a matrix id.", "'%1' does not look like a matrix id.", text));
@@ -396,7 +393,7 @@ QList<ActionsModel::Action> actions{
kli18n("Unignores the given user"),
},
Action{
QStringLiteral("react"),
u"react"_s,
[](const QString &text, NeoChatRoom *room, ChatBarCache *chatBarCache) {
if (chatBarCache->replyId().isEmpty()) {
for (auto it = room->messageEvents().crbegin(); it != room->messageEvents().crend(); it++) {
@@ -416,11 +413,10 @@ QList<ActionsModel::Action> actions{
kli18n("React to the message with the given text"),
},
Action{
QStringLiteral("ban"),
u"ban"_s,
[](const QString &text, NeoChatRoom *room, ChatBarCache *) {
auto parts = text.split(QLatin1String(" "));
static const QRegularExpression mxidRegex(
QStringLiteral(R"((^|[][[:space:](){}`'";])([!#@][-a-z0-9_=#/.]{1,252}:\w(?:\w|\.|-)*\.\w+(?::\d{1,5})?))"));
auto parts = text.split(u" "_s);
static const QRegularExpression mxidRegex(uR"((^|[][[:space:](){}`'";])([!#@][-a-z0-9_=#/.]{1,252}:\w(?:\w|\.|-)*\.\w+(?::\d{1,5})?))"_s);
auto regexMatch = mxidRegex.match(parts[0]);
if (!regexMatch.hasMatch()) {
Q_EMIT room->showMessage(MessageType::Error, i18nc("'<text>' does not look like a matrix id.", "'%1' does not look like a matrix id.", text));
@@ -456,10 +452,9 @@ QList<ActionsModel::Action> actions{
kli18n("Bans the given user"),
},
Action{
QStringLiteral("unban"),
u"unban"_s,
[](const QString &text, NeoChatRoom *room, ChatBarCache *) {
static const QRegularExpression mxidRegex(
QStringLiteral(R"((^|[][[:space:](){}`'";])([!#@][-a-z0-9_=#/.]{1,252}:\w(?:\w|\.|-)*\.\w+(?::\d{1,5})?))"));
static const QRegularExpression mxidRegex(uR"((^|[][[:space:](){}`'";])([!#@][-a-z0-9_=#/.]{1,252}:\w(?:\w|\.|-)*\.\w+(?::\d{1,5})?))"_s);
auto regexMatch = mxidRegex.match(text);
if (!regexMatch.hasMatch()) {
Q_EMIT room->showMessage(MessageType::Error, i18nc("'<text>' does not look like a matrix id.", "'%1' does not look like a matrix id.", text));
@@ -489,11 +484,10 @@ QList<ActionsModel::Action> actions{
kli18n("Removes the ban of the given user"),
},
Action{
QStringLiteral("kick"),
u"kick"_s,
[](const QString &text, NeoChatRoom *room, ChatBarCache *) {
auto parts = text.split(QLatin1String(" "));
static const QRegularExpression mxidRegex(
QStringLiteral(R"((^|[][[:space:](){}`'";])([!#@][-a-z0-9_=#/.]{1,252}:\w(?:\w|\.|-)*\.\w+(?::\d{1,5})?))"));
auto parts = text.split(u" "_s);
static const QRegularExpression mxidRegex(uR"((^|[][[:space:](){}`'";])([!#@][-a-z0-9_=#/.]{1,252}:\w(?:\w|\.|-)*\.\w+(?::\d{1,5})?))"_s);
auto regexMatch = mxidRegex.match(parts[0]);
if (!regexMatch.hasMatch()) {
Q_EMIT room->showMessage(MessageType::Error,
@@ -552,7 +546,7 @@ QVariant ActionsModel::data(const QModelIndex &index, int role) const
return actions[index.row()].description.toString();
}
if (role == CompletionType) {
return QStringLiteral("action");
return u"action"_s;
}
if (role == Parameters) {
return actions[index.row()].parameters.toString();
@@ -581,7 +575,7 @@ bool ActionsModel::handleQuickEditAction(NeoChatRoom *room, const QString &messa
}
if (NeoChatConfig::allowQuickEdit()) {
QRegularExpression sed(QStringLiteral("^s/([^/]*)/([^/]*)(/g)?$"));
QRegularExpression sed(u"^s/([^/]*)/([^/]*)(/g)?$"_s);
auto match = sed.match(messageText);
if (match.hasMatch()) {
const QString regex = match.captured(1);
@@ -632,7 +626,7 @@ std::pair<std::optional<QString>, std::optional<Quotient::RoomMessageEvent::MsgT
if (sendText.startsWith(QLatin1Char('/'))) {
for (const auto &action : ActionsModel::instance().allActions()) {
if (sendText.indexOf(action.prefix) == 1
&& (sendText.indexOf(" "_ls) == action.prefix.length() + 1 || sendText.length() == action.prefix.length() + 1)) {
&& (sendText.indexOf(" "_L1) == action.prefix.length() + 1 || sendText.length() == action.prefix.length() + 1)) {
sendText = action.handle(sendText.mid(action.prefix.length() + 1).trimmed(), room, chatBarCache);
if (action.messageType.has_value()) {
messageType = action.messageType;

View File

@@ -64,14 +64,14 @@ QVariant CompletionModel::data(const QModelIndex &index, int role) const
if (m_autoCompletionType == Command) {
if (role == DisplayNameRole) {
return QStringLiteral("%1 %2").arg(m_filterModel->data(filterIndex, ActionsModel::Prefix).toString(),
m_filterModel->data(filterIndex, ActionsModel::Parameters).toString());
return u"%1 %2"_s.arg(m_filterModel->data(filterIndex, ActionsModel::Prefix).toString(),
m_filterModel->data(filterIndex, ActionsModel::Parameters).toString());
}
if (role == SubtitleRole) {
return m_filterModel->data(filterIndex, ActionsModel::Description);
}
if (role == IconNameRole) {
return QStringLiteral("invalid");
return u"invalid"_s;
}
if (role == ReplacedTextRole) {
return m_filterModel->data(filterIndex, ActionsModel::Prefix);

View File

@@ -34,14 +34,14 @@ void CustomEmojiModel::fetchEmojis()
return;
}
const auto &data = m_connection->accountData("im.ponies.user_emotes"_ls);
const auto &data = m_connection->accountData("im.ponies.user_emotes"_L1);
if (data == nullptr) {
return;
}
QJsonObject emojis = data->contentJson()["images"_ls].toObject();
QJsonObject emojis = data->contentJson()["images"_L1].toObject();
// TODO: Remove with stable migration
const auto legacyEmojis = data->contentJson()["emoticons"_ls].toObject();
const auto legacyEmojis = data->contentJson()["emoticons"_L1].toObject();
for (const auto &emoji : legacyEmojis.keys()) {
if (!emojis.contains(emoji)) {
emojis[emoji] = legacyEmojis[emoji];
@@ -54,9 +54,9 @@ void CustomEmojiModel::fetchEmojis()
for (const auto &emoji : emojis.keys()) {
const auto &data = emojis[emoji];
const auto e = emoji.startsWith(":"_ls) ? emoji : (QStringLiteral(":") + emoji + QStringLiteral(":"));
const auto e = emoji.startsWith(":"_L1) ? emoji : (u":"_s + emoji + u":"_s);
m_emojis << CustomEmoji{e, data.toObject()["url"_ls].toString(), QRegularExpression(e)};
m_emojis << CustomEmoji{e, data.toObject()["url"_L1].toString(), QRegularExpression(e)};
}
endResetModel();
@@ -69,29 +69,29 @@ void CustomEmojiModel::addEmoji(const QString &name, const QUrl &location)
auto job = m_connection->uploadFile(location.toLocalFile());
connect(job, &BaseJob::success, this, [name, location, job, this] {
const auto &data = m_connection->accountData("im.ponies.user_emotes"_ls);
const auto &data = m_connection->accountData("im.ponies.user_emotes"_L1);
auto json = data != nullptr ? data->contentJson() : QJsonObject();
auto emojiData = json["images"_ls].toObject();
auto emojiData = json["images"_L1].toObject();
QString url;
url = job->contentUri().toString();
QImage image(location.toLocalFile());
QJsonObject imageInfo;
imageInfo["w"_ls] = image.width();
imageInfo["h"_ls] = image.height();
imageInfo["mimetype"_ls] = QMimeDatabase().mimeTypeForFile(location.toLocalFile()).name();
imageInfo["size"_ls] = image.sizeInBytes();
imageInfo["w"_L1] = image.width();
imageInfo["h"_L1] = image.height();
imageInfo["mimetype"_L1] = QMimeDatabase().mimeTypeForFile(location.toLocalFile()).name();
imageInfo["size"_L1] = image.sizeInBytes();
emojiData[QStringLiteral("%1").arg(name)] = QJsonObject({
{QStringLiteral("url"), url},
{QStringLiteral("info"), imageInfo},
{QStringLiteral("body"), location.fileName()},
{"usage"_ls, "emoticon"_ls},
emojiData["%1"_L1.arg(name)] = QJsonObject({
{u"url"_s, url},
{u"info"_s, imageInfo},
{u"body"_s, location.fileName()},
{u"usage"_s, "emoticon"_L1},
});
json["images"_ls] = emojiData;
m_connection->setAccountData("im.ponies.user_emotes"_ls, json);
json["images"_L1] = emojiData;
m_connection->setAccountData("im.ponies.user_emotes"_L1, json);
});
}
@@ -99,30 +99,30 @@ void CustomEmojiModel::removeEmoji(const QString &name)
{
using namespace Quotient;
const auto &data = m_connection->accountData("im.ponies.user_emotes"_ls);
const auto &data = m_connection->accountData("im.ponies.user_emotes"_L1);
Q_ASSERT(data);
auto json = data->contentJson();
const QString _name = name.mid(1).chopped(1);
auto emojiData = json["images"_ls].toObject();
auto emojiData = json["images"_L1].toObject();
if (emojiData.contains(name)) {
emojiData.remove(name);
json["images"_ls] = emojiData;
json["images"_L1] = emojiData;
}
if (emojiData.contains(_name)) {
emojiData.remove(_name);
json["images"_ls] = emojiData;
json["images"_L1] = emojiData;
}
emojiData = json["emoticons"_ls].toObject();
emojiData = json["emoticons"_L1].toObject();
if (emojiData.contains(name)) {
emojiData.remove(name);
json["emoticons"_ls] = emojiData;
json["emoticons"_L1] = emojiData;
}
if (emojiData.contains(_name)) {
emojiData.remove(_name);
json["emoticons"_ls] = emojiData;
json["emoticons"_L1] = emojiData;
}
m_connection->setAccountData("im.ponies.user_emotes"_ls, json);
m_connection->setAccountData("im.ponies.user_emotes"_L1, json);
}
CustomEmojiModel::CustomEmojiModel(QObject *parent)
@@ -134,7 +134,7 @@ CustomEmojiModel::CustomEmojiModel(QObject *parent)
}
CustomEmojiModel::fetchEmojis();
connect(m_connection, &Connection::accountDataChanged, this, [this](const QString &id) {
if (id != QStringLiteral("im.ponies.user_emotes")) {
if (id != u"im.ponies.user_emotes"_s) {
return;
}
fetchEmojis();
@@ -189,9 +189,8 @@ QHash<int, QByteArray> CustomEmojiModel::roleNames() const
QString CustomEmojiModel::preprocessText(QString text)
{
for (const auto &emoji : std::as_const(m_emojis)) {
text.replace(
emoji.regexp,
QStringLiteral(R"(<img data-mx-emoticon="" src="%1" alt="%2" title="%2" height="32" vertical-align="middle" />)").arg(emoji.url, emoji.name));
text.replace(emoji.regexp,
uR"(<img data-mx-emoticon="" src="%1" alt="%2" title="%2" height="32" vertical-align="middle" />)"_s.arg(emoji.url, emoji.name));
}
return text;
}

View File

@@ -123,11 +123,11 @@ void DevicesModel::logout(const QString &deviceId, const QString &password)
if (job->error() != BaseJob::Success) {
QJsonObject replyData = job->jsonData();
QJsonObject authData;
authData["session"_ls] = replyData["session"_ls];
authData["password"_ls] = password;
authData["type"_ls] = "m.login.password"_ls;
QJsonObject identifier = {{"type"_ls, "m.id.user"_ls}, {"user"_ls, m_connection->user()->id()}};
authData["identifier"_ls] = identifier;
authData["session"_L1] = replyData["session"_L1];
authData["password"_L1] = password;
authData["type"_L1] = "m.login.password"_L1;
QJsonObject identifier = {{"type"_L1, "m.id.user"_L1}, {"user"_L1, m_connection->user()->id()}};
authData["identifier"_L1] = identifier;
auto innerJob = m_connection->callApi<NeochatDeleteDeviceJob>(m_devices[index].deviceId, authData);
connect(innerJob.get(), &BaseJob::success, this, onSuccess);
} else {

View File

@@ -12,10 +12,12 @@
#include "customemojimodel.h"
#include <KLocalizedString>
using namespace Qt::StringLiterals;
EmojiModel::EmojiModel(QObject *parent)
: QAbstractListModel(parent)
, m_config(KSharedConfig::openStateConfig())
, m_configGroup(KConfigGroup(m_config, QStringLiteral("Editor")))
, m_configGroup(KConfigGroup(m_config, u"Editor"_s))
{
if (_emojis.isEmpty()) {
#include "emojis.h"
@@ -43,14 +45,14 @@ QVariant EmojiModel::data(const QModelIndex &index, int role) const
auto emoji = category[row].value<Emoji>();
switch (role) {
case ShortNameRole:
return QStringLiteral(":%1:").arg(emoji.shortName);
return u":%1:"_s.arg(emoji.shortName);
case UnicodeRole:
case ReplacedTextRole:
return emoji.unicode;
case InvalidRole:
return QStringLiteral("invalid");
return u"invalid"_s;
case DisplayRole:
return QStringLiteral("%2 :%1:").arg(emoji.shortName, emoji.unicode);
return u"%2 :%1:"_s.arg(emoji.shortName, emoji.unicode);
case DescriptionRole:
return emoji.description;
}
@@ -65,7 +67,7 @@ QHash<int, QByteArray> EmojiModel::roleNames() const
QStringList EmojiModel::lastUsedEmojis() const
{
return m_configGroup.readEntry(QStringLiteral("lastUsedEmojis"), QStringList());
return m_configGroup.readEntry(u"lastUsedEmojis"_s, QStringList());
}
QVariantList EmojiModel::filterModel(const QString &filter, bool limit)
@@ -110,7 +112,7 @@ void EmojiModel::emojiUsed(const QVariant &modelData)
list.push_front(emoji.shortName);
m_configGroup.writeEntry(QStringLiteral("lastUsedEmojis"), list);
m_configGroup.writeEntry(u"lastUsedEmojis"_s, list);
Q_EMIT historyChanged();
}
@@ -139,8 +141,8 @@ QVariantList EmojiModel::emojis(Category category) const
QVariantList EmojiModel::tones(const QString &baseEmoji) const
{
if (baseEmoji.endsWith(QStringLiteral("tone"))) {
return EmojiTones::_tones.values(baseEmoji.split(QStringLiteral(":"))[0]);
if (baseEmoji.endsWith(u"tone"_s)) {
return EmojiTones::_tones.values(baseEmoji.split(u":"_s)[0]);
}
return EmojiTones::_tones.values(baseEmoji);
}
@@ -151,54 +153,54 @@ QVariantList EmojiModel::categories() const
{
return QVariantList{
{QVariantMap{
{QStringLiteral("category"), EmojiModel::HistoryNoCustom},
{QStringLiteral("name"), i18nc("Previously used emojis", "History")},
{QStringLiteral("emoji"), QStringLiteral("⌛️")},
{u"category"_s, EmojiModel::HistoryNoCustom},
{u"name"_s, i18nc("Previously used emojis", "History")},
{u"emoji"_s, u"⌛️"_s},
}},
{QVariantMap{
{QStringLiteral("category"), EmojiModel::Smileys},
{QStringLiteral("name"), i18nc("'Smileys' is a category of emoji", "Smileys")},
{QStringLiteral("emoji"), QStringLiteral("😏")},
{u"category"_s, EmojiModel::Smileys},
{u"name"_s, i18nc("'Smileys' is a category of emoji", "Smileys")},
{u"emoji"_s, u"😏"_s},
}},
{QVariantMap{
{QStringLiteral("category"), EmojiModel::People},
{QStringLiteral("name"), i18nc("'People' is a category of emoji", "People")},
{QStringLiteral("emoji"), QStringLiteral("🙋‍♂️")},
{u"category"_s, EmojiModel::People},
{u"name"_s, i18nc("'People' is a category of emoji", "People")},
{u"emoji"_s, u"🙋‍♂️"_s},
}},
{QVariantMap{
{QStringLiteral("category"), EmojiModel::Nature},
{QStringLiteral("name"), i18nc("'Nature' is a category of emoji", "Nature")},
{QStringLiteral("emoji"), QStringLiteral("🌲")},
{u"category"_s, EmojiModel::Nature},
{u"name"_s, i18nc("'Nature' is a category of emoji", "Nature")},
{u"emoji"_s, u"🌲"_s},
}},
{QVariantMap{
{QStringLiteral("category"), EmojiModel::Food},
{QStringLiteral("name"), i18nc("'Food' is a category of emoji", "Food")},
{QStringLiteral("emoji"), QStringLiteral("🍛")},
{u"category"_s, EmojiModel::Food},
{u"name"_s, i18nc("'Food' is a category of emoji", "Food")},
{u"emoji"_s, u"🍛"_s},
}},
{QVariantMap{
{QStringLiteral("category"), EmojiModel::Activities},
{QStringLiteral("name"), i18nc("'Activities' is a category of emoji", "Activities")},
{QStringLiteral("emoji"), QStringLiteral("🚁")},
{u"category"_s, EmojiModel::Activities},
{u"name"_s, i18nc("'Activities' is a category of emoji", "Activities")},
{u"emoji"_s, u"🚁"_s},
}},
{QVariantMap{
{QStringLiteral("category"), EmojiModel::Travel},
{QStringLiteral("name"), i18nc("'Travel' is a category of emoji", "Travel")},
{QStringLiteral("emoji"), QStringLiteral("🚅")},
{u"category"_s, EmojiModel::Travel},
{u"name"_s, i18nc("'Travel' is a category of emoji", "Travel")},
{u"emoji"_s, u"🚅"_s},
}},
{QVariantMap{
{QStringLiteral("category"), EmojiModel::Objects},
{QStringLiteral("name"), i18nc("'Objects' is a category of emoji", "Objects")},
{QStringLiteral("emoji"), QStringLiteral("💡")},
{u"category"_s, EmojiModel::Objects},
{u"name"_s, i18nc("'Objects' is a category of emoji", "Objects")},
{u"emoji"_s, u"💡"_s},
}},
{QVariantMap{
{QStringLiteral("category"), EmojiModel::Symbols},
{QStringLiteral("name"), i18nc("'Symbols' is a category of emoji", "Symbols")},
{QStringLiteral("emoji"), QStringLiteral("🔣")},
{u"category"_s, EmojiModel::Symbols},
{u"name"_s, i18nc("'Symbols' is a category of emoji", "Symbols")},
{u"emoji"_s, u"🔣"_s},
}},
{QVariantMap{
{QStringLiteral("category"), EmojiModel::Flags},
{QStringLiteral("name"), i18nc("'Flags' is a category of emoji", "Flags")},
{QStringLiteral("emoji"), QStringLiteral("🏁")},
{u"category"_s, EmojiModel::Flags},
{u"name"_s, i18nc("'Flags' is a category of emoji", "Flags")},
{u"emoji"_s, u"🏁"_s},
}},
};
}
@@ -209,15 +211,15 @@ QVariantList EmojiModel::categoriesWithCustom() const
cats.removeAt(0);
cats.insert(0,
QVariantMap{
{QStringLiteral("category"), EmojiModel::History},
{QStringLiteral("name"), i18nc("Previously used emojis", "History")},
{QStringLiteral("emoji"), QStringLiteral("⌛️")},
{u"category"_s, EmojiModel::History},
{u"name"_s, i18nc("Previously used emojis", "History")},
{u"emoji"_s, u"⌛️"_s},
});
cats.insert(1,
QVariantMap{
{QStringLiteral("category"), EmojiModel::Custom},
{QStringLiteral("name"), i18nc("'Custom' is a category of emoji", "Custom")},
{QStringLiteral("emoji"), QStringLiteral("🖼️")},
{u"category"_s, EmojiModel::Custom},
{u"name"_s, i18nc("'Custom' is a category of emoji", "Custom")},
{u"emoji"_s, u"🖼️"_s},
});
;
return cats;

View File

@@ -66,7 +66,7 @@ void ImagePacksModel::setRoom(NeoChatRoom *room)
if (m_room) {
connect(m_room->connection(), &Connection::accountDataChanged, this, [this](const QString &type) {
if (type == "im.ponies.user_emotes"_ls) {
if (type == "im.ponies.user_emotes"_L1) {
reloadImages();
}
});
@@ -85,10 +85,10 @@ void ImagePacksModel::reloadImages()
m_events.clear();
// Load emoticons from the account data
if (m_room->connection()->hasAccountData("im.ponies.user_emotes"_ls)) {
auto json = m_room->connection()->accountData("im.ponies.user_emotes"_ls)->contentJson();
json["pack"_ls] = QJsonObject{
{"display_name"_ls,
if (m_room->connection()->hasAccountData("im.ponies.user_emotes"_L1)) {
auto json = m_room->connection()->accountData("im.ponies.user_emotes"_L1)->contentJson();
json["pack"_L1] = QJsonObject{
{"display_name"_L1,
m_showStickers ? i18nc("As in 'The user's own Stickers'", "Own Stickers") : i18nc("As in 'The user's own emojis", "Own Emojis")},
};
const auto &content = ImagePackEventContent(json);
@@ -98,9 +98,9 @@ void ImagePacksModel::reloadImages()
}
// Load emoticons from the saved rooms
const auto &accountData = m_room->connection()->accountData("im.ponies.emote_rooms"_ls);
const auto &accountData = m_room->connection()->accountData("im.ponies.emote_rooms"_L1);
if (accountData) {
const auto &rooms = accountData->contentJson()["rooms"_ls].toObject();
const auto &rooms = accountData->contentJson()["rooms"_L1].toObject();
for (const auto &roomId : rooms.keys()) {
if (roomId == m_room->id()) {
continue;
@@ -113,8 +113,8 @@ void ImagePacksModel::reloadImages()
for (const auto &packKey : packs.keys()) {
if (const auto &pack = stickerRoom->currentState().get<ImagePackEvent>(packKey)) {
const auto packContent = pack->content();
if ((!packContent.pack || !packContent.pack->usage || (packContent.pack->usage->contains("emoticon"_ls) && showEmoticons())
|| (packContent.pack->usage->contains("sticker"_ls) && showStickers()))
if ((!packContent.pack || !packContent.pack->usage || (packContent.pack->usage->contains("emoticon"_L1) && showEmoticons())
|| (packContent.pack->usage->contains("sticker"_L1) && showStickers()))
&& !packContent.images.isEmpty()) {
m_events += packContent;
}
@@ -124,12 +124,12 @@ void ImagePacksModel::reloadImages()
}
// Load emoticons from the current room
auto events = m_room->currentState().eventsOfType("im.ponies.room_emotes"_ls);
auto events = m_room->currentState().eventsOfType("im.ponies.room_emotes"_L1);
for (const auto &event : events) {
auto packContent = eventCast<const ImagePackEvent>(event)->content();
if (packContent.pack.has_value()) {
if (!packContent.pack->usage || (packContent.pack->usage->contains("emoticon"_ls) && showEmoticons())
|| (packContent.pack->usage->contains("sticker"_ls) && showStickers())) {
if (!packContent.pack->usage || (packContent.pack->usage->contains("emoticon"_L1) && showEmoticons())
|| (packContent.pack->usage->contains("sticker"_L1) && showStickers())) {
m_events += packContent;
}
}

View File

@@ -12,6 +12,8 @@
#include <KIO/ApplicationLauncherJob>
#endif
using namespace Qt::StringLiterals;
ItineraryModel::ItineraryModel(QObject *parent)
: QAbstractListModel(parent)
{
@@ -25,122 +27,114 @@ QVariant ItineraryModel::data(const QModelIndex &index, int role) const
auto row = index.row();
auto data = m_data[row];
if (role == NameRole) {
if (data[QStringLiteral("@type")] == QStringLiteral("TrainReservation")) {
auto trainName = QStringLiteral("%1 %2").arg(data[QStringLiteral("reservationFor")][QStringLiteral("trainName")].toString(),
data[QStringLiteral("reservationFor")][QStringLiteral("trainNumber")].toString());
if (data["@type"_L1] == u"TrainReservation"_s) {
auto trainName = u"%1 %2"_s.arg(data["reservationFor"_L1]["trainName"_L1].toString(), data["reservationFor"_L1]["trainNumber"_L1].toString());
if (trainName.trimmed().isEmpty()) {
return QStringLiteral("%1 to %2")
.arg(data[QStringLiteral("reservationFor")][QStringLiteral("departureStation")][QStringLiteral("name")].toString(),
data[QStringLiteral("reservationFor")][QStringLiteral("arrivalStation")][QStringLiteral("name")].toString());
return u"%1 to %2"_s.arg(data["reservationFor"_L1]["departureStation"_L1]["name"_L1].toString(),
data["reservationFor"_L1]["arrivalStation"_L1]["name"_L1].toString());
;
}
return trainName;
}
if (data[QStringLiteral("@type")] == QStringLiteral("LodgingReservation")) {
return data[QStringLiteral("reservationFor")][QStringLiteral("name")];
if (data["@type"_L1] == u"LodgingReservation"_s) {
return data["reservationFor"_L1]["name"_L1];
}
if (data[QStringLiteral("@type")] == QStringLiteral("FoodEstablishmentReservation")) {
return data[QStringLiteral("reservationFor")][QStringLiteral("name")];
if (data["@type"_L1] == u"FoodEstablishmentReservation"_s) {
return data["reservationFor"_L1]["name"_L1];
}
if (data[QStringLiteral("@type")] == QStringLiteral("FlightReservation")) {
return QStringLiteral("%1 %2 %3 → %4")
.arg(data[QStringLiteral("reservationFor")][QStringLiteral("airline")][QStringLiteral("iataCode")].toString(),
data[QStringLiteral("reservationFor")][QStringLiteral("flightNumber")].toString(),
data[QStringLiteral("reservationFor")][QStringLiteral("departureAirport")][QStringLiteral("iataCode")].toString(),
data[QStringLiteral("reservationFor")][QStringLiteral("arrivalAirport")][QStringLiteral("iataCode")].toString());
if (data["@type"_L1] == u"FlightReservation"_s) {
return u"%1 %2 %3 → %4"_s.arg(data["reservationFor"_L1]["airline"_L1]["iataCode"_L1].toString(),
data["reservationFor"_L1]["flightNumber"_L1].toString(),
data["reservationFor"_L1]["departureAirport"_L1]["iataCode"_L1].toString(),
data["reservationFor"_L1]["arrivalAirport"_L1]["iataCode"_L1].toString());
}
}
if (role == TypeRole) {
return data[QStringLiteral("@type")];
return data["@type"_L1];
}
if (role == DepartureLocationRole) {
if (data[QStringLiteral("@type")] == QStringLiteral("TrainReservation")) {
return data[QStringLiteral("reservationFor")][QStringLiteral("departureStation")][QStringLiteral("name")];
if (data["@type"_L1] == u"TrainReservation"_s) {
return data["reservationFor"_L1]["departureStation"_L1]["name"_L1];
}
if (data[QStringLiteral("@type")] == QStringLiteral("FlightReservation")) {
return data[QStringLiteral("reservationFor")][QStringLiteral("departureAirport")][QStringLiteral("iataCode")];
if (data["@type"_L1] == u"FlightReservation"_s) {
return data["reservationFor"_L1]["departureAirport"_L1]["iataCode"_L1];
}
}
if (role == DepartureAddressRole) {
if (data[QStringLiteral("@type")] == QStringLiteral("TrainReservation")) {
return data[QStringLiteral("reservationFor")][QStringLiteral("departureStation")][QStringLiteral("address")][QStringLiteral("addressCountry")]
.toString();
if (data["@type"_L1] == u"TrainReservation"_s) {
return data["reservationFor"_L1]["departureStation"_L1]["address"_L1]["addressCountry"_L1].toString();
}
if (data[QStringLiteral("@type")] == QStringLiteral("FlightReservation")) {
return data[QStringLiteral("reservationFor")][QStringLiteral("departureAirport")][QStringLiteral("address")][QStringLiteral("addressCountry")]
.toString();
if (data["@type"_L1] == u"FlightReservation"_s) {
return data["reservationFor"_L1]["departureAirport"_L1]["address"_L1]["addressCountry"_L1].toString();
}
}
if (role == ArrivalLocationRole) {
if (data[QStringLiteral("@type")] == QStringLiteral("TrainReservation")) {
return data[QStringLiteral("reservationFor")][QStringLiteral("arrivalStation")][QStringLiteral("name")];
if (data["@type"_L1] == u"TrainReservation"_s) {
return data["reservationFor"_L1]["arrivalStation"_L1]["name"_L1];
}
if (data[QStringLiteral("@type")] == QStringLiteral("FlightReservation")) {
return data[QStringLiteral("reservationFor")][QStringLiteral("arrivalAirport")][QStringLiteral("iataCode")];
if (data["@type"_L1] == u"FlightReservation"_s) {
return data["reservationFor"_L1]["arrivalAirport"_L1]["iataCode"_L1];
}
}
if (role == ArrivalAddressRole) {
if (data[QStringLiteral("@type")] == QStringLiteral("TrainReservation")) {
return data[QStringLiteral("reservationFor")][QStringLiteral("arrivalStation")][QStringLiteral("address")][QStringLiteral("addressCountry")]
.toString();
if (data["@type"_L1] == u"TrainReservation"_s) {
return data["reservationFor"_L1]["arrivalStation"_L1]["address"_L1]["addressCountry"_L1].toString();
}
if (data[QStringLiteral("@type")] == QStringLiteral("FlightReservation")) {
return data[QStringLiteral("reservationFor")][QStringLiteral("arrivalAirport")][QStringLiteral("address")][QStringLiteral("addressCountry")]
.toString();
if (data["@type"_L1] == u"FlightReservation"_s) {
return data["reservationFor"_L1]["arrivalAirport"_L1]["address"_L1]["addressCountry"_L1].toString();
}
}
if (role == DepartureTimeRole) {
const auto &time = data[QStringLiteral("reservationFor")][QStringLiteral("departureTime")];
auto dateTime = (time.isString() ? time : time[QStringLiteral("@value")]).toVariant().toDateTime();
if (const auto &timeZone = time[QStringLiteral("timezone")].toString(); timeZone.length() > 0) {
const auto &time = data["reservationFor"_L1]["departureTime"_L1];
auto dateTime = (time.isString() ? time : time["@value"_L1]).toVariant().toDateTime();
if (const auto &timeZone = time["timezone"_L1].toString(); timeZone.length() > 0) {
dateTime.setTimeZone(QTimeZone(timeZone.toLatin1().data()));
}
return dateTime.toString(QLocale::system().dateTimeFormat(QLocale::ShortFormat));
}
if (role == ArrivalTimeRole) {
const auto &time = data[QStringLiteral("reservationFor")][QStringLiteral("arrivalTime")];
auto dateTime = (time.isString() ? time : time[QStringLiteral("@value")]).toVariant().toDateTime();
if (const auto &timeZone = time[QStringLiteral("timezone")].toString(); timeZone.length() > 0) {
const auto &time = data["reservationFor"_L1]["arrivalTime"_L1];
auto dateTime = (time.isString() ? time : time["@value"_L1]).toVariant().toDateTime();
if (const auto &timeZone = time["timezone"_L1].toString(); timeZone.length() > 0) {
dateTime.setTimeZone(QTimeZone(timeZone.toLatin1().data()));
}
return dateTime.toString(QLocale::system().dateTimeFormat(QLocale::ShortFormat));
}
if (role == AddressRole) {
const auto &addressData = data[QStringLiteral("reservationFor")][QStringLiteral("address")];
return QStringLiteral("%1 - %2 %3 %4")
.arg(addressData[QStringLiteral("streetAddress")].toString(),
addressData[QStringLiteral("postalCode")].toString(),
addressData[QStringLiteral("addressLocality")].toString(),
addressData[QStringLiteral("addressCountry")].toString());
const auto &addressData = data["reservationFor"_L1]["address"_L1];
return u"%1 - %2 %3 %4"_s.arg(addressData["streetAddress"_L1].toString(),
addressData["postalCode"_L1].toString(),
addressData["addressLocality"_L1].toString(),
addressData["addressCountry"_L1].toString());
}
if (role == StartTimeRole) {
QDateTime dateTime;
if (data[QStringLiteral("@type")] == QStringLiteral("LodgingReservation")) {
dateTime = data[QStringLiteral("checkinTime")][QStringLiteral("@value")].toVariant().toDateTime();
if (data["@type"_L1] == u"LodgingReservation"_s) {
dateTime = data["checkinTime"_L1]["@value"_L1].toVariant().toDateTime();
}
if (data[QStringLiteral("@type")] == QStringLiteral("FoodEstablishmentReservation")) {
dateTime = data[QStringLiteral("startTime")][QStringLiteral("@value")].toVariant().toDateTime();
if (data["@type"_L1] == u"FoodEstablishmentReservation"_s) {
dateTime = data["startTime"_L1]["@value"_L1].toVariant().toDateTime();
}
if (data[QStringLiteral("@type")] == QStringLiteral("FlightReservation")) {
dateTime = data[QStringLiteral("reservationFor")][QStringLiteral("boardingTime")][QStringLiteral("@value")].toVariant().toDateTime();
if (data["@type"_L1] == u"FlightReservation"_s) {
dateTime = data["reservationFor"_L1]["boardingTime"_L1]["@value"_L1].toVariant().toDateTime();
}
return dateTime.toString(QLocale::system().dateTimeFormat(QLocale::ShortFormat));
}
if (role == EndTimeRole) {
auto dateTime = data[QStringLiteral("checkoutTime")][QStringLiteral("@value")].toVariant().toDateTime();
auto dateTime = data["checkoutTime"_L1]["@value"_L1].toVariant().toDateTime();
return dateTime.toString(QLocale::system().dateTimeFormat(QLocale::ShortFormat));
}
if (role == DeparturePlatformRole) {
return data[QStringLiteral("reservationFor")][QStringLiteral("departurePlatform")];
return data["reservationFor"_L1]["departurePlatform"_L1];
}
if (role == ArrivalPlatformRole) {
return data[QStringLiteral("reservationFor")][QStringLiteral("arrivalPlatform")];
return data["reservationFor"_L1]["arrivalPlatform"_L1];
}
if (role == CoachRole) {
return data[QStringLiteral("reservedTicket")][QStringLiteral("ticketedSeat")][QStringLiteral("seatSection")];
return data["reservedTicket"_L1]["ticketedSeat"_L1]["seatSection"_L1];
}
if (role == SeatRole) {
return data[QStringLiteral("reservedTicket")][QStringLiteral("ticketedSeat")][QStringLiteral("seatNumber")];
return data["reservedTicket"_L1]["ticketedSeat"_L1]["seatNumber"_L1];
}
return {};
}
@@ -186,7 +180,7 @@ void ItineraryModel::setPath(const QString &path)
void ItineraryModel::loadData()
{
auto process = new QProcess(this);
process->start(QLatin1String(CMAKE_INSTALL_FULL_LIBEXECDIR_KF6) + QLatin1String("/kitinerary-extractor"), {m_path.mid(7)});
process->start(QStringLiteral(CMAKE_INSTALL_FULL_LIBEXECDIR_KF6) + u"/kitinerary-extractor"_s, {m_path.mid(7)});
connect(process, &QProcess::finished, this, [this, process]() {
auto data = process->readAllStandardOutput();
beginResetModel();
@@ -203,7 +197,7 @@ void ItineraryModel::loadData()
void ItineraryModel::sendToItinerary()
{
#ifndef Q_OS_ANDROID
auto job = new KIO::ApplicationLauncherJob(KService::serviceByDesktopName(QStringLiteral("org.kde.itinerary")));
auto job = new KIO::ApplicationLauncherJob(KService::serviceByDesktopName(u"org.kde.itinerary"_s));
job->setUrls({QUrl::fromLocalFile(m_path.mid(7))});
job->start();
#endif

View File

@@ -62,7 +62,7 @@ QVariant LiveLocationsModel::data(const QModelIndex &index, int roleName) const
const auto &data = m_locations.at(index.row());
switch (roleName) {
case LatitudeRole: {
const auto geoUri = data.beacon["org.matrix.msc3488.location"_ls].toObject()["uri"_ls].toString();
const auto geoUri = data.beacon["org.matrix.msc3488.location"_L1].toObject()["uri"_L1].toString();
if (geoUri.isEmpty()) {
return {};
}
@@ -70,7 +70,7 @@ QVariant LiveLocationsModel::data(const QModelIndex &index, int roleName) const
return latitude.toFloat();
}
case LongitudeRole: {
const auto geoUri = data.beacon["org.matrix.msc3488.location"_ls].toObject()["uri"_ls].toString();
const auto geoUri = data.beacon["org.matrix.msc3488.location"_L1].toObject()["uri"_L1].toString();
if (geoUri.isEmpty()) {
return {};
}
@@ -78,21 +78,21 @@ QVariant LiveLocationsModel::data(const QModelIndex &index, int roleName) const
return longitude.toFloat();
}
case AssetRole:
return data.beaconInfo["org.matrix.msc3488.asset"_ls].toObject()["type"_ls].toString();
return data.beaconInfo["org.matrix.msc3488.asset"_L1].toObject()["type"_L1].toString();
case AuthorRole:
return QVariant::fromValue(m_room->member(data.senderId));
case IsLiveRole: {
if (!data.beaconInfo["live"_ls].toBool()) {
if (!data.beaconInfo["live"_L1].toBool()) {
return false;
}
// TODO Qt6: port to toInteger(), timestamps are in ms since epoch, ie. 64 bit values
const auto lastTs = std::max(data.beaconInfo.value("org.matrix.msc3488.ts"_ls).toDouble(), data.beacon.value("org.matrix.msc3488.ts"_ls).toDouble());
const auto timeout = data.beaconInfo.value("timeout"_ls).toDouble(600000);
const auto lastTs = std::max(data.beaconInfo.value("org.matrix.msc3488.ts"_L1).toDouble(), data.beacon.value("org.matrix.msc3488.ts"_L1).toDouble());
const auto timeout = data.beaconInfo.value("timeout"_L1).toDouble(600000);
return lastTs + timeout >= QDateTime::currentDateTime().toMSecsSinceEpoch();
}
case HeadingRole: {
bool success = false;
const auto heading = data.beacon["org.matrix.msc3488.location"_ls].toObject()["org.kde.itinerary.heading"_ls].toString().toDouble(&success);
const auto heading = data.beacon["org.matrix.msc3488.location"_L1].toObject()["org.kde.itinerary.heading"_L1].toString().toDouble(&success);
return success ? heading : NAN;
}
}
@@ -129,20 +129,20 @@ QRectF LiveLocationsModel::boundingBox() const
void LiveLocationsModel::addEvent(const Quotient::RoomEvent *event)
{
if (event->isStateEvent() && event->matrixType() == "org.matrix.msc3672.beacon_info"_ls) {
if (event->isStateEvent() && event->matrixType() == "org.matrix.msc3672.beacon_info"_L1) {
LiveLocationData data;
data.senderId = event->senderId();
data.beaconInfo = event->contentJson();
if (event->contentJson()["live"_ls].toBool()) {
if (event->contentJson()["live"_L1].toBool()) {
data.eventId = event->id();
} else {
data.eventId = event->fullJson()["replaces_state"_ls].toString();
data.eventId = event->fullJson()["replaces_state"_L1].toString();
}
updateLocationData(std::move(data));
}
if (event->matrixType() == "org.matrix.msc3672.beacon"_ls) {
if (event->matrixType() == "org.matrix.msc3672.beacon"_L1) {
LiveLocationData data;
data.eventId = event->contentJson()["m.relates_to"_ls].toObject()["event_id"_ls].toString();
data.eventId = event->contentJson()["m.relates_to"_L1].toObject()["event_id"_L1].toString();
data.senderId = event->senderId();
data.beacon = event->contentJson();
updateLocationData(std::move(data));
@@ -167,11 +167,11 @@ void LiveLocationsModel::updateLocationData(LiveLocationData &&data)
const auto idx = index(std::distance(m_locations.begin(), it), 0);
// TODO Qt6: port to toInteger(), timestamps are in ms since epoch, ie. 64 bit values
if (it->beacon.isEmpty() || it->beacon.value("org.matrix.msc3488.ts"_ls).toDouble() < data.beacon.value("org.matrix.msc3488.ts"_ls).toDouble()) {
if (it->beacon.isEmpty() || it->beacon.value("org.matrix.msc3488.ts"_L1).toDouble() < data.beacon.value("org.matrix.msc3488.ts"_L1).toDouble()) {
it->beacon = std::move(data.beacon);
}
if (it->beaconInfo.isEmpty()
|| it->beaconInfo.value("org.matrix.msc3488.ts"_ls).toDouble() < data.beaconInfo.value("org.matrix.msc3488.ts"_ls).toDouble()) {
|| it->beaconInfo.value("org.matrix.msc3488.ts"_L1).toDouble() < data.beaconInfo.value("org.matrix.msc3488.ts"_L1).toDouble()) {
it->beaconInfo = std::move(data.beaconInfo);
}

View File

@@ -15,7 +15,7 @@ LocationsModel::LocationsModel(QObject *parent)
if (!is<RoomMessageEvent>(*event)) {
continue;
}
if (event->contentJson()["msgtype"_ls] == "m.location"_ls) {
if (event->contentJson()["msgtype"_L1] == "m.location"_L1) {
const auto &e = *event;
addLocation(eventCast<const RoomMessageEvent>(&e));
}
@@ -25,7 +25,7 @@ LocationsModel::LocationsModel(QObject *parent)
if (!is<RoomMessageEvent>(*event)) {
continue;
}
if (event->contentJson()["msgtype"_ls] == "m.location"_ls) {
if (event->contentJson()["msgtype"_L1] == "m.location"_L1) {
const auto &e = *event;
addLocation(eventCast<const RoomMessageEvent>(&e));
}
@@ -36,7 +36,7 @@ LocationsModel::LocationsModel(QObject *parent)
if (!is<RoomMessageEvent>(*event)) {
continue;
}
if (event->contentJson()["msgtype"_ls] == "m.location"_ls) {
if (event->contentJson()["msgtype"_L1] == "m.location"_L1) {
const auto &e = *event;
addLocation(eventCast<const RoomMessageEvent>(&e));
}
@@ -49,7 +49,7 @@ LocationsModel::LocationsModel(QObject *parent)
void LocationsModel::addLocation(const RoomMessageEvent *event)
{
const auto uri = event->contentJson()["org.matrix.msc3488.location"_ls]["uri"_ls].toString();
const auto uri = event->contentJson()["org.matrix.msc3488.location"_L1]["uri"_L1].toString();
const auto parts = uri.mid(4).split(QLatin1Char(','));
if (parts.size() < 2) {
qWarning() << "invalid geo: URI" << uri;
@@ -101,9 +101,9 @@ QVariant LocationsModel::data(const QModelIndex &index, int roleName) const
} else if (roleName == LatitudeRole) {
return m_locations[row].latitude;
} else if (roleName == TextRole) {
return m_locations[row].content["body"_ls].toString();
return m_locations[row].content["body"_L1].toString();
} else if (roleName == AssetRole) {
return m_locations[row].content["org.matrix.msc3488.asset"_ls].toObject()["type"_ls].toString();
return m_locations[row].content["org.matrix.msc3488.asset"_L1].toObject()["type"_L1].toString();
} else if (roleName == AuthorRole) {
return QVariant::fromValue(m_locations[row].member);
}

View File

@@ -10,6 +10,8 @@
#include "messageeventmodel.h"
#include "messagefiltermodel.h"
using namespace Qt::StringLiterals;
MediaMessageFilterModel::MediaMessageFilterModel(QObject *parent, MessageFilterModel *sourceMediaModel)
: QSortFilterProxyModel(parent)
{
@@ -21,8 +23,8 @@ bool MediaMessageFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex
{
const QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
if (index.data(MessageEventModel::MediaInfoRole).toMap()[QLatin1String("mimeType")].toString().contains(QLatin1String("image"))
|| index.data(MessageEventModel::MediaInfoRole).toMap()[QLatin1String("mimeType")].toString().contains(QLatin1String("video"))) {
if (index.data(MessageEventModel::MediaInfoRole).toMap()["mimeType"_L1].toString().contains("image"_L1)
|| index.data(MessageEventModel::MediaInfoRole).toMap()["mimeType"_L1].toString().contains("video"_L1)) {
return true;
}
return false;
@@ -49,19 +51,19 @@ QVariant MediaMessageFilterModel::data(const QModelIndex &index, int role) const
QVariantMap mediaInfo = mapToSource(index).data(MessageEventModel::MediaInfoRole).toMap();
if (role == TempSourceRole) {
return mediaInfo[QStringLiteral("tempInfo")].toMap()[QStringLiteral("source")].toUrl();
return mediaInfo[u"tempInfo"_s].toMap()[u"source"_s].toUrl();
}
if (role == CaptionRole) {
return mapToSource(index).data(Qt::DisplayRole);
}
if (role == SourceWidthRole) {
return mediaInfo[QStringLiteral("width")].toFloat();
return mediaInfo[u"width"_s].toFloat();
}
if (role == SourceHeightRole) {
return mediaInfo[QStringLiteral("height")].toFloat();
return mediaInfo[u"height"_s].toFloat();
}
bool isVideo = mediaInfo[QStringLiteral("mimeType")].toString().contains(QStringLiteral("video"));
bool isVideo = mediaInfo[u"mimeType"_s].toString().contains("video"_L1);
if (role == TypeRole) {
return (isVideo) ? MediaType::Video : MediaType::Image;
@@ -73,7 +75,7 @@ QVariant MediaMessageFilterModel::data(const QModelIndex &index, int role) const
return mapToSource(index).data(MessageEventModel::ProgressInfoRole).value<Quotient::FileTransferInfo>().localPath;
}
} else {
return mediaInfo[QStringLiteral("source")].toUrl();
return mediaInfo[u"source"_s].toUrl();
}
}

View File

@@ -283,11 +283,11 @@ QVariant MessageContentModel::data(const QModelIndex &index, int role) const
if (theme != nullptr) {
disabledTextColor = theme->disabledTextColor().name();
} else {
disabledTextColor = QStringLiteral("#000000");
disabledTextColor = u"#000000"_s;
}
return QString(QStringLiteral("<span style=\"color:%1\">").arg(disabledTextColor)
return QString(u"<span style=\"color:%1\">"_s.arg(disabledTextColor)
+ i18nc("@info", "This message was either not found, you do not have permission to view it, or it was sent by an ignored user")
+ QStringLiteral("</span>"));
+ u"</span>"_s);
}
if (component.type == MessageComponentType::Loading) {
if (m_isReply) {
@@ -324,7 +324,7 @@ QVariant MessageContentModel::data(const QModelIndex &index, int role) const
});
auto lastUpdated = pendingIt == m_room->pendingEvents().cend() ? QDateTime() : pendingIt->lastUpdated();
return EventHandler::timeString(event.first, QStringLiteral("hh:mm"), m_currentState == Pending, lastUpdated);
return EventHandler::timeString(event.first, u"hh:mm"_s, m_currentState == Pending, lastUpdated);
}
if (role == AuthorRole) {
return QVariant::fromValue<NeochatRoomMember *>(m_eventSenderObject.get());
@@ -364,7 +364,7 @@ QVariant MessageContentModel::data(const QModelIndex &index, int role) const
if (role == LinkPreviewerRole) {
if (component.type == MessageComponentType::LinkPreview) {
return QVariant::fromValue<LinkPreviewer *>(
dynamic_cast<NeoChatConnection *>(m_room->connection())->previewerForLink(component.attributes["link"_ls].toUrl()));
dynamic_cast<NeoChatConnection *>(m_room->connection())->previewerForLink(component.attributes["link"_L1].toUrl()));
} else {
return QVariant::fromValue<LinkPreviewer *>(emptyLinkPreview);
}
@@ -462,7 +462,7 @@ QList<MessageComponent> MessageContentModel::messageContentComponents(bool isEdi
QList<MessageComponent> newComponents;
const auto roomMessageEvent = eventCast<const Quotient::RoomMessageEvent>(event.first);
if (roomMessageEvent && roomMessageEvent->rawMsgtype() == QStringLiteral("m.key.verification.request")) {
if (roomMessageEvent && roomMessageEvent->rawMsgtype() == u"m.key.verification.request"_s) {
newComponents += MessageComponent{MessageComponentType::Verification, QString(), {}};
return newComponents;
}
@@ -556,7 +556,7 @@ QList<MessageComponent> MessageContentModel::componentsForType(MessageComponentT
#ifndef Q_OS_ANDROID
Q_ASSERT(roomMessageEvent->content() != nullptr && roomMessageEvent->has<EventContent::FileContent>());
const QMimeType mimeType = roomMessageEvent->get<EventContent::FileContent>()->mimeType;
if (mimeType.name() == QStringLiteral("text/plain") || mimeType.parentMimeTypes().contains(QStringLiteral("text/plain"))) {
if (mimeType.name() == u"text/plain"_s || mimeType.parentMimeTypes().contains(u"text/plain"_s)) {
QString originalName = roomMessageEvent->get<EventContent::FileContent>()->originalName;
if (originalName.isEmpty()) {
originalName = roomMessageEvent->plainBody();
@@ -571,13 +571,13 @@ QList<MessageComponent> MessageContentModel::componentsForType(MessageComponentT
file.open(QIODevice::ReadOnly);
components += MessageComponent{MessageComponentType::Code,
QString::fromStdString(file.readAll().toStdString()),
{{QStringLiteral("class"), definitionForFile.name()}}};
{{u"class"_s, definitionForFile.name()}}};
}
#endif
if (FileType::instance().fileHasImage(fileTransferInfo.localPath)) {
QImageReader reader(fileTransferInfo.localPath.path());
components += MessageComponent{MessageComponentType::Pdf, QString(), {{QStringLiteral("size"), reader.size()}}};
components += MessageComponent{MessageComponentType::Pdf, QString(), {{u"size"_s, reader.size()}}};
}
}
} else if (m_itineraryModel != nullptr) {
@@ -632,13 +632,13 @@ MessageComponent MessageContentModel::linkPreviewComponent(const QUrl &link)
return {};
}
if (linkPreviewer->loaded()) {
return MessageComponent{MessageComponentType::LinkPreview, QString(), {{"link"_ls, link}}};
return MessageComponent{MessageComponentType::LinkPreview, QString(), {{"link"_L1, link}}};
} else {
connect(linkPreviewer, &LinkPreviewer::loadedChanged, this, [this, link]() {
const auto linkPreviewer = dynamic_cast<NeoChatConnection *>(m_room->connection())->previewerForLink(link);
if (linkPreviewer != nullptr && linkPreviewer->loaded()) {
for (auto &component : m_components) {
if (component.attributes["link"_ls].toUrl() == link) {
if (component.attributes["link"_L1].toUrl() == link) {
// HACK: Because DelegateChooser can't switch the delegate on dataChanged it has to think there is a new delegate.
beginResetModel();
component.type = MessageComponentType::LinkPreview;
@@ -647,7 +647,7 @@ MessageComponent MessageContentModel::linkPreviewComponent(const QUrl &link)
}
}
});
return MessageComponent{MessageComponentType::LinkPreviewLoad, QString(), {{"link"_ls, link}}};
return MessageComponent{MessageComponentType::LinkPreviewLoad, QString(), {{"link"_L1, link}}};
}
}
@@ -682,7 +682,7 @@ void MessageContentModel::closeLinkPreview(int row)
if (m_components[row].type == MessageComponentType::LinkPreview || m_components[row].type == MessageComponentType::LinkPreviewLoad) {
beginResetModel();
m_removedLinkPreviews += m_components[row].attributes["link"_ls].toUrl();
m_removedLinkPreviews += m_components[row].attributes["link"_L1].toUrl();
m_components.remove(row);
m_components.squeeze();
endResetModel();

View File

@@ -469,7 +469,7 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
if (isPending) {
// A pending event with an m.new_content key will be merged into the
// original event so don't show.
if (evt.contentJson().contains("m.new_content"_ls)) {
if (evt.contentJson().contains("m.new_content"_L1)) {
return EventStatus::Hidden;
}
return pendingIt->deliveryStatus();
@@ -644,7 +644,7 @@ void MessageEventModel::createEventObjects(const Quotient::RoomEvent *event, boo
}
if (!m_contentModels.contains(eventId) && !m_contentModels.contains(event->transactionId())) {
if (!event->isStateEvent() || event->matrixType() == QStringLiteral("org.matrix.msc3672.beacon_info")) {
if (!event->isStateEvent() || event->matrixType() == u"org.matrix.msc3672.beacon_info"_s) {
m_contentModels[eventId] = std::unique_ptr<MessageContentModel>(new MessageContentModel(m_currentRoom, eventId, false, isPending));
}
}

View File

@@ -136,7 +136,7 @@ QString MessageFilterModel::aggregateEventToString(int sourceRow) const
QString aggregateString;
for (int i = sourceRow; i >= 0; i--) {
aggregateString += sourceModel()->data(sourceModel()->index(i, 0), MessageEventModel::GenericDisplayRole).toString();
aggregateString += ", "_ls;
aggregateString += ", "_L1;
QVariant nextAuthor = sourceModel()->data(sourceModel()->index(i, 0), MessageEventModel::AuthorRole);
if (i > 0
&& (sourceModel()->data(sourceModel()->index(i - 1, 0), MessageEventModel::DelegateTypeRole) != DelegateType::State // If it's not a state event
@@ -158,9 +158,9 @@ QVariantList MessageFilterModel::stateEventsList(int sourceRow) const
QVariantList stateEvents;
for (int i = sourceRow; i >= 0; i--) {
auto nextState = QVariantMap{
{QStringLiteral("author"), sourceModel()->data(sourceModel()->index(i, 0), MessageEventModel::AuthorRole)},
{QStringLiteral("authorDisplayName"), sourceModel()->data(sourceModel()->index(i, 0), MessageEventModel::AuthorDisplayNameRole).toString()},
{QStringLiteral("text"), sourceModel()->data(sourceModel()->index(i, 0), Qt::DisplayRole).toString()},
{u"author"_s, sourceModel()->data(sourceModel()->index(i, 0), MessageEventModel::AuthorRole)},
{u"authorDisplayName"_s, sourceModel()->data(sourceModel()->index(i, 0), MessageEventModel::AuthorDisplayNameRole).toString()},
{u"text"_s, sourceModel()->data(sourceModel()->index(i, 0), Qt::DisplayRole).toString()},
};
stateEvents.append(nextState);
if (i > 0
@@ -221,7 +221,7 @@ QString MessageFilterModel::excessAuthors(int row) const
if (excessAuthors == 0) {
return QString();
} else {
return QStringLiteral("+ %1").arg(excessAuthors);
return u"+ %1"_s.arg(excessAuthors);
}
}

View File

@@ -105,26 +105,26 @@ void NotificationsModel::loadData()
if (std::any_of(notification.actions.constBegin(), notification.actions.constEnd(), [](const QVariant &it) {
if (it.canConvert<QVariantMap>()) {
auto map = it.toMap();
if (map["set_tweak"_ls] == "highlight"_ls) {
if (map["set_tweak"_L1] == "highlight"_L1) {
return true;
}
}
return false;
})) {
const auto &authorId = notification.event->fullJson()["sender"_ls].toString();
const auto &authorId = notification.event->fullJson()["sender"_L1].toString();
const auto &room = m_connection->room(notification.roomId);
if (!room) {
continue;
}
auto u = room->member(authorId).avatarUrl();
auto avatar = u.isEmpty() ? QUrl() : connection()->makeMediaUrl(u);
const auto &authorAvatar = avatar.isValid() && avatar.scheme() == QStringLiteral("mxc") ? avatar : QUrl();
const auto &authorAvatar = avatar.isValid() && avatar.scheme() == u"mxc"_s ? avatar : QUrl();
const auto &roomEvent = eventCast<const RoomEvent>(notification.event.get());
beginInsertRows({}, m_notifications.length(), m_notifications.length());
m_notifications += Notification{
.roomId = notification.roomId,
.text = room->member(authorId).htmlSafeDisplayName() + (roomEvent->is<StateEvent>() ? QStringLiteral(" ") : QStringLiteral(": "))
.text = room->member(authorId).htmlSafeDisplayName() + (roomEvent->is<StateEvent>() ? u" "_s : u": "_s)
+ EventHandler::plainBody(dynamic_cast<NeoChatRoom *>(room), roomEvent, true),
.authorName = room->member(authorId).htmlSafeDisplayName(),
.authorAvatar = authorAvatar,

View File

@@ -36,20 +36,20 @@ static const QStringList basicPermissions = {
};
static const QStringList knownPermissions = {
QStringLiteral("m.reaction"),
QStringLiteral("m.room.redaction"),
QStringLiteral("m.room.power_levels"),
QStringLiteral("m.room.name"),
QStringLiteral("m.room.avatar"),
QStringLiteral("m.room.canonical_alias"),
QStringLiteral("m.room.topic"),
QStringLiteral("m.room.encryption"),
QStringLiteral("m.room.history_visibility"),
QStringLiteral("m.room.pinned_events"),
QStringLiteral("m.room.tombstone"),
QStringLiteral("m.room.server_acl"),
QStringLiteral("m.space.child"),
QStringLiteral("m.space.parent"),
u"m.reaction"_s,
u"m.room.redaction"_s,
u"m.room.power_levels"_s,
u"m.room.name"_s,
u"m.room.avatar"_s,
u"m.room.canonical_alias"_s,
u"m.room.topic"_s,
u"m.room.encryption"_s,
u"m.room.history_visibility"_s,
u"m.room.pinned_events"_s,
u"m.room.tombstone"_s,
u"m.room.server_acl"_s,
u"m.space.child"_s,
u"m.space.parent"_s,
};
// Alternate name text for default permissions.
@@ -61,20 +61,20 @@ static const QHash<QString, KLazyLocalizedString> permissionNames = {
{KickKey, kli18nc("Room permission type", "Kick users")},
{BanKey, kli18nc("Room permission type", "Ban users")},
{RedactKey, kli18nc("Room permission type", "Remove messages sent by other users")},
{QStringLiteral("m.reaction"), kli18nc("Room permission type", "Send reactions")},
{QStringLiteral("m.room.redaction"), kli18nc("Room permission type", "Remove their own messages")},
{QStringLiteral("m.room.power_levels"), kli18nc("Room permission type", "Change user permissions")},
{QStringLiteral("m.room.name"), kli18nc("Room permission type", "Change the room name")},
{QStringLiteral("m.room.avatar"), kli18nc("Room permission type", "Change the room avatar")},
{QStringLiteral("m.room.canonical_alias"), kli18nc("Room permission type", "Change the room canonical alias")},
{QStringLiteral("m.room.topic"), kli18nc("Room permission type", "Change the room topic")},
{QStringLiteral("m.room.encryption"), kli18nc("Room permission type", "Enable encryption for the room")},
{QStringLiteral("m.room.history_visibility"), kli18nc("Room permission type", "Change the room history visibility")},
{QStringLiteral("m.room.pinned_events"), kli18nc("Room permission type", "Set pinned events")},
{QStringLiteral("m.room.tombstone"), kli18nc("Room permission type", "Upgrade the room")},
{QStringLiteral("m.room.server_acl"), kli18nc("Room permission type", "Set the room server access control list (ACL)")},
{QStringLiteral("m.space.child"), kli18nc("Room permission type", "Set the children of this space")},
{QStringLiteral("m.space.parent"), kli18nc("Room permission type", "Set the parent space of this room")},
{u"m.reaction"_s, kli18nc("Room permission type", "Send reactions")},
{u"m.room.redaction"_s, kli18nc("Room permission type", "Remove their own messages")},
{u"m.room.power_levels"_s, kli18nc("Room permission type", "Change user permissions")},
{u"m.room.name"_s, kli18nc("Room permission type", "Change the room name")},
{u"m.room.avatar"_s, kli18nc("Room permission type", "Change the room avatar")},
{u"m.room.canonical_alias"_s, kli18nc("Room permission type", "Change the room canonical alias")},
{u"m.room.topic"_s, kli18nc("Room permission type", "Change the room topic")},
{u"m.room.encryption"_s, kli18nc("Room permission type", "Enable encryption for the room")},
{u"m.room.history_visibility"_s, kli18nc("Room permission type", "Change the room history visibility")},
{u"m.room.pinned_events"_s, kli18nc("Room permission type", "Set pinned events")},
{u"m.room.tombstone"_s, kli18nc("Room permission type", "Upgrade the room")},
{u"m.room.server_acl"_s, kli18nc("Room permission type", "Set the room server access control list (ACL)")},
{u"m.space.child"_s, kli18nc("Room permission type", "Set the children of this space")},
{u"m.space.parent"_s, kli18nc("Room permission type", "Set the parent space of this room")},
};
// Subtitles for the default values.
@@ -86,9 +86,9 @@ static const QHash<QString, KLazyLocalizedString> permissionSubtitles = {
// Permissions that should use the event default.
static const QStringList eventPermissions = {
QStringLiteral("m.room.message"),
QStringLiteral("m.reaction"),
QStringLiteral("m.room.redaction"),
u"m.room.message"_s,
u"m.reaction"_s,
u"m.room.redaction"_s,
};
};
@@ -267,9 +267,9 @@ void PermissionsModel::setPowerLevel(const QString &permission, const int &newPo
} else if (defaultPermissions.contains(permission) || basicPermissions.contains(permission)) {
powerLevelContent[permission] = clampPowerLevel;
} else {
auto eventPowerLevels = powerLevelContent[QLatin1String("events")].toObject();
auto eventPowerLevels = powerLevelContent["events"_L1].toObject();
eventPowerLevels[permission] = clampPowerLevel;
powerLevelContent[QLatin1String("events")] = eventPowerLevels;
powerLevelContent["events"_L1] = eventPowerLevels;
}
m_room->setState<Quotient::RoomPowerLevelsEvent>(Quotient::fromJson<Quotient::PowerLevelsEventContent>(powerLevelContent));

View File

@@ -180,7 +180,7 @@ void PublicRoomListModel::next(int limit)
QStringList roomTypes;
if (m_showOnlySpaces) {
roomTypes += QLatin1String("m.space");
roomTypes += u"m.space"_s;
}
job = m_connection->callApi<NeoChatQueryPublicRoomsJob>(m_server, limit, nextBatch, QueryPublicRoomsJob::Filter{m_searchText, roomTypes});
Q_EMIT searchingChanged();
@@ -274,7 +274,7 @@ QVariant PublicRoomListModel::data(const QModelIndex &index, int role) const
return m_connection->room(room.roomId, JoinState::Join) != nullptr;
}
if (role == IsSpaceRole) {
return room.roomType == QLatin1String("m.space");
return room.roomType == u"m.space"_s;
}
return {};

View File

@@ -16,50 +16,50 @@
// Alternate name text for default rules.
static const QHash<QString, KLazyLocalizedString> defaultRuleNames = {
{QStringLiteral(".m.rule.master"), kli18nc("Notification type", "Enable notifications for this account")},
{QStringLiteral(".m.rule.room_one_to_one"), kli18nc("Notification type", "Messages in one-to-one chats")},
{QStringLiteral(".m.rule.encrypted_room_one_to_one"), kli18nc("Notification type", "Encrypted messages in one-to-one chats")},
{QStringLiteral(".m.rule.message"), kli18nc("Notification type", "Messages in group chats")},
{QStringLiteral(".m.rule.encrypted"), kli18nc("Notification type", "Messages in encrypted group chats")},
{QStringLiteral(".m.rule.tombstone"), kli18nc("Notification type", "Room upgrade messages")},
{QStringLiteral(".m.rule.contains_display_name"), kli18nc("Notification type", "Messages containing my display name")},
{QStringLiteral(".m.rule.is_user_mention"), kli18nc("Notification type", "Messages which mention my Matrix user ID")},
{QStringLiteral(".m.rule.is_room_mention"), kli18nc("Notification type", "Messages which mention a room")},
{QStringLiteral(".m.rule.contains_user_name"), kli18nc("Notification type", "Messages containing the local part of my Matrix ID")},
{QStringLiteral(".m.rule.roomnotif"), kli18nc("Notification type", "Whole room (@room) notifications")},
{QStringLiteral(".m.rule.invite_for_me"), kli18nc("Notification type", "Invites to a room")},
{QStringLiteral(".m.rule.call"), kli18nc("Notification type", "Call invitation")},
{u".m.rule.master"_s, kli18nc("Notification type", "Enable notifications for this account")},
{u".m.rule.room_one_to_one"_s, kli18nc("Notification type", "Messages in one-to-one chats")},
{u".m.rule.encrypted_room_one_to_one"_s, kli18nc("Notification type", "Encrypted messages in one-to-one chats")},
{u".m.rule.message"_s, kli18nc("Notification type", "Messages in group chats")},
{u".m.rule.encrypted"_s, kli18nc("Notification type", "Messages in encrypted group chats")},
{u".m.rule.tombstone"_s, kli18nc("Notification type", "Room upgrade messages")},
{u".m.rule.contains_display_name"_s, kli18nc("Notification type", "Messages containing my display name")},
{u".m.rule.is_user_mention"_s, kli18nc("Notification type", "Messages which mention my Matrix user ID")},
{u".m.rule.is_room_mention"_s, kli18nc("Notification type", "Messages which mention a room")},
{u".m.rule.contains_user_name"_s, kli18nc("Notification type", "Messages containing the local part of my Matrix ID")},
{u".m.rule.roomnotif"_s, kli18nc("Notification type", "Whole room (@room) notifications")},
{u".m.rule.invite_for_me"_s, kli18nc("Notification type", "Invites to a room")},
{u".m.rule.call"_s, kli18nc("Notification type", "Call invitation")},
};
// Sections for default rules.
static const QHash<QString, PushRuleSection::Section> defaultSections = {
{QStringLiteral(".m.rule.master"), PushRuleSection::Master},
{QStringLiteral(".m.rule.room_one_to_one"), PushRuleSection::Room},
{QStringLiteral(".m.rule.encrypted_room_one_to_one"), PushRuleSection::Room},
{QStringLiteral(".m.rule.message"), PushRuleSection::Room},
{QStringLiteral(".m.rule.encrypted"), PushRuleSection::Room},
{QStringLiteral(".m.rule.tombstone"), PushRuleSection::Room},
{QStringLiteral(".m.rule.contains_display_name"), PushRuleSection::Mentions},
{QStringLiteral(".m.rule.is_user_mention"), PushRuleSection::Mentions},
{QStringLiteral(".m.rule.is_room_mention"), PushRuleSection::Mentions},
{QStringLiteral(".m.rule.contains_user_name"), PushRuleSection::Mentions},
{QStringLiteral(".m.rule.roomnotif"), PushRuleSection::Mentions},
{QStringLiteral(".m.rule.invite_for_me"), PushRuleSection::Invites},
{QStringLiteral(".m.rule.call"), PushRuleSection::Undefined}, // TODO: make invites when VOIP added.
{QStringLiteral(".m.rule.suppress_notices"), PushRuleSection::Undefined},
{QStringLiteral(".m.rule.member_event"), PushRuleSection::Undefined},
{QStringLiteral(".m.rule.reaction"), PushRuleSection::Undefined},
{QStringLiteral(".m.rule.room.server_acl"), PushRuleSection::Undefined},
{QStringLiteral(".im.vector.jitsi"), PushRuleSection::Undefined},
{u".m.rule.master"_s, PushRuleSection::Master},
{u".m.rule.room_one_to_one"_s, PushRuleSection::Room},
{u".m.rule.encrypted_room_one_to_one"_s, PushRuleSection::Room},
{u".m.rule.message"_s, PushRuleSection::Room},
{u".m.rule.encrypted"_s, PushRuleSection::Room},
{u".m.rule.tombstone"_s, PushRuleSection::Room},
{u".m.rule.contains_display_name"_s, PushRuleSection::Mentions},
{u".m.rule.is_user_mention"_s, PushRuleSection::Mentions},
{u".m.rule.is_room_mention"_s, PushRuleSection::Mentions},
{u".m.rule.contains_user_name"_s, PushRuleSection::Mentions},
{u".m.rule.roomnotif"_s, PushRuleSection::Mentions},
{u".m.rule.invite_for_me"_s, PushRuleSection::Invites},
{u".m.rule.call"_s, PushRuleSection::Undefined}, // TODO: make invites when VOIP added.
{u".m.rule.suppress_notices"_s, PushRuleSection::Undefined},
{u".m.rule.member_event"_s, PushRuleSection::Undefined},
{u".m.rule.reaction"_s, PushRuleSection::Undefined},
{u".m.rule.room.server_acl"_s, PushRuleSection::Undefined},
{u".im.vector.jitsi"_s, PushRuleSection::Undefined},
};
// Default rules that don't have a highlight option as it would lead to all messages
// in a room being highlighted.
static const QStringList noHighlight = {
QStringLiteral(".m.rule.room_one_to_one"),
QStringLiteral(".m.rule.encrypted_room_one_to_one"),
QStringLiteral(".m.rule.message"),
QStringLiteral(".m.rule.encrypted"),
u".m.rule.room_one_to_one"_s,
u".m.rule.encrypted_room_one_to_one"_s,
u".m.rule.message"_s,
u".m.rule.encrypted"_s,
};
PushRuleModel::PushRuleModel(QObject *parent)
@@ -70,12 +70,12 @@ PushRuleModel::PushRuleModel(QObject *parent)
void PushRuleModel::updateNotificationRules(const QString &type)
{
if (type != QStringLiteral("m.push_rules")) {
if (type != u"m.push_rules"_s) {
return;
}
const QJsonObject ruleDataJson = m_connection->accountDataJson(QStringLiteral("m.push_rules"));
const Quotient::PushRuleset ruleData = Quotient::fromJson<Quotient::PushRuleset>(ruleDataJson[QStringLiteral("global")].toObject());
const QJsonObject ruleDataJson = m_connection->accountDataJson(u"m.push_rules"_s);
const Quotient::PushRuleset ruleData = Quotient::fromJson<Quotient::PushRuleset>(ruleDataJson["global"_L1].toObject());
beginResetModel();
m_rules.clear();
@@ -99,7 +99,7 @@ void PushRuleModel::setRules(QList<Quotient::PushRule> rules, PushRuleKind::Kind
QString roomId;
if (rule.conditions.size() > 0) {
for (const auto &condition : std::as_const(rule.conditions)) {
if (condition.key == QStringLiteral("room_id")) {
if (condition.key == u"room_id"_s) {
roomId = condition.pattern;
}
}
@@ -163,7 +163,7 @@ PushRuleSection::Section PushRuleModel::getSection(Quotient::PushRule rule)
// If the rule has push conditions and one is a room ID it is a room only keyword.
if (!rule.conditions.isEmpty()) {
for (const auto &condition : std::as_const(rule.conditions)) {
if (condition.key == QStringLiteral("room_id")) {
if (condition.key == u"room_id"_s) {
return PushRuleSection::RoomKeywords;
}
}
@@ -189,7 +189,7 @@ void PushRuleModel::setDefaultState(PushRuleAction::Action defaultState)
bool PushRuleModel::globalNotificationsEnabled() const
{
auto masterIndex = getRuleIndex(QStringLiteral(".m.rule.master"));
auto masterIndex = getRuleIndex(u".m.rule.master"_s);
if (masterIndex > -1) {
return !m_rules[masterIndex].enabled;
}
@@ -198,12 +198,12 @@ bool PushRuleModel::globalNotificationsEnabled() const
void PushRuleModel::setGlobalNotificationsEnabled(bool enabled)
{
setNotificationRuleEnabled(QStringLiteral("override"), QStringLiteral(".m.rule.master"), !enabled);
setNotificationRuleEnabled(u"override"_s, u".m.rule.master"_s, !enabled);
}
bool PushRuleModel::globalNotificationsSet() const
{
return getRuleIndex(QStringLiteral(".m.rule.master")) > -1;
return getRuleIndex(u".m.rule.master"_s) > -1;
}
QVariant PushRuleModel::data(const QModelIndex &index, int role) const
@@ -238,7 +238,7 @@ QVariant PushRuleModel::data(const QModelIndex &index, int role) const
return !noHighlight.contains(m_rules.at(index.row()).id);
}
if (role == DeletableRole) {
return !m_rules.at(index.row()).id.startsWith(QStringLiteral("."));
return !m_rules.at(index.row()).id.startsWith(u"."_s);
}
if (role == SectionRole) {
return m_rules.at(index.row()).section;
@@ -299,14 +299,14 @@ void PushRuleModel::addKeyword(const QString &keyword, const QString &roomId)
kind = PushRuleKind::Override;
Quotient::PushCondition roomCondition;
roomCondition.kind = QStringLiteral("event_match");
roomCondition.key = QStringLiteral("room_id");
roomCondition.kind = u"event_match"_s;
roomCondition.key = u"room_id"_s;
roomCondition.pattern = roomId;
pushConditions.append(roomCondition);
Quotient::PushCondition keywordCondition;
keywordCondition.kind = QStringLiteral("event_match");
keywordCondition.key = QStringLiteral("content.body");
keywordCondition.kind = u"event_match"_s;
keywordCondition.key = u"content.body"_s;
keywordCondition.pattern = keyword;
pushConditions.append(keywordCondition);
}
@@ -319,7 +319,7 @@ void PushRuleModel::addKeyword(const QString &keyword, const QString &roomId)
pushConditions,
roomId.isEmpty() ? keyword : QString());
connect(job, &Quotient::BaseJob::failure, this, [job, keyword]() {
qWarning() << QLatin1String("Unable to set push rule for keyword %1: ").arg(keyword) << job->errorString();
qWarning() << "Unable to set push rule for keyword %1: "_L1.arg(keyword) << job->errorString();
});
}
@@ -338,7 +338,7 @@ void PushRuleModel::removeKeyword(const QString &keyword)
auto kind = PushRuleKind::kindString(m_rules[index].kind);
auto job = m_connection->callApi<Quotient::DeletePushRuleJob>(kind, m_rules[index].id);
connect(job, &Quotient::BaseJob::failure, this, [this, job, index]() {
qWarning() << QLatin1String("Unable to remove push rule for keyword %1: ").arg(m_rules[index].id) << job->errorString();
qWarning() << "Unable to remove push rule for keyword %1: "_L1.arg(m_rules[index].id) << job->errorString();
});
}
@@ -355,8 +355,8 @@ void PushRuleModel::setNotificationRuleEnabled(const QString &kind, const QStrin
void PushRuleModel::setNotificationRuleActions(const QString &kind, const QString &ruleId, PushRuleAction::Action action)
{
QList<QVariant> actions;
if (ruleId == QStringLiteral(".m.rule.call")) {
actions = actionToVariant(action, QStringLiteral("ring"));
if (ruleId == u".m.rule.call"_s) {
actions = actionToVariant(action, u"ring"_s);
} else {
actions = actionToVariant(action);
}
@@ -372,17 +372,17 @@ PushRuleAction::Action PushRuleModel::variantToAction(const QList<QVariant> &act
for (const auto &i : actions) {
auto actionString = i.toString();
if (!actionString.isEmpty()) {
if (actionString == QLatin1String("notify")) {
if (actionString == u"notify"_s) {
notify = true;
}
continue;
}
QJsonObject action = i.toJsonObject();
if (action[QStringLiteral("set_tweak")].toString() == QStringLiteral("sound")) {
if (action["set_tweak"_L1].toString() == u"sound"_s) {
isNoisy = true;
} else if (action[QStringLiteral("set_tweak")].toString() == QStringLiteral("highlight")) {
if (action[QStringLiteral("value")].toString() != QStringLiteral("false")) {
} else if (action["set_tweak"_L1].toString() == u"highlight"_s) {
if (action["value"_L1].toString() != u"false"_s) {
highlightEnabled = true;
}
}
@@ -419,19 +419,19 @@ QList<QVariant> PushRuleModel::actionToVariant(PushRuleAction::Action action, co
QList<QVariant> actions;
if (action != PushRuleAction::Off) {
actions.append(QStringLiteral("notify"));
actions.append(u"notify"_s);
} else {
actions.append(QStringLiteral("dont_notify"));
actions.append(u"dont_notify"_s);
}
if (action == PushRuleAction::Noisy || action == PushRuleAction::NoisyHighlight) {
QJsonObject soundTweak;
soundTweak.insert(QStringLiteral("set_tweak"), QStringLiteral("sound"));
soundTweak.insert(QStringLiteral("value"), sound);
soundTweak.insert("set_tweak"_L1, u"sound"_s);
soundTweak.insert("value"_L1, sound);
actions.append(soundTweak);
}
if (action == PushRuleAction::Highlight || action == PushRuleAction::NoisyHighlight) {
QJsonObject highlightTweak;
highlightTweak.insert(QStringLiteral("set_tweak"), QStringLiteral("highlight"));
highlightTweak.insert("set_tweak"_L1, u"highlight"_s);
actions.append(highlightTweak);
}
@@ -453,7 +453,7 @@ void PushRuleModel::setConnection(NeoChatConnection *connection)
if (m_connection) {
connect(m_connection, &NeoChatConnection::accountDataChanged, this, &PushRuleModel::updateNotificationRules);
updateNotificationRules(QStringLiteral("m.push_rules"));
updateNotificationRules(u"m.push_rules"_s);
}
}

View File

@@ -11,6 +11,8 @@
#include "enums/pushrule.h"
#include "neochatconnection.h"
using namespace Qt::StringLiterals;
/**
* @class PushRuleModel
*
@@ -136,6 +138,6 @@ private:
void setNotificationRuleEnabled(const QString &kind, const QString &ruleId, bool enabled);
void setNotificationRuleActions(const QString &kind, const QString &ruleId, PushRuleAction::Action action);
PushRuleAction::Action variantToAction(const QList<QVariant> &actions, bool enabled);
QList<QVariant> actionToVariant(PushRuleAction::Action action, const QString &sound = QStringLiteral("default"));
QList<QVariant> actionToVariant(PushRuleAction::Action action, const QString &sound = u"default"_s);
};
Q_DECLARE_METATYPE(PushRuleModel *)

View File

@@ -9,6 +9,8 @@
#include <KLocalizedString>
using namespace Qt::StringLiterals;
ReactionModel::ReactionModel(const Quotient::RoomMessageEvent *event, NeoChatRoom *room)
: QAbstractListModel(nullptr)
, m_room(room)
@@ -40,7 +42,7 @@ QVariant ReactionModel::data(const QModelIndex &index, int role) const
if (role == TextContentRole) {
if (reaction.authors.count() > 1) {
return QStringLiteral("%1 %2").arg(reactionText(reaction.reaction), QString::number(reaction.authors.count()));
return u"%1 %2"_s.arg(reactionText(reaction.reaction), QString::number(reaction.authors.count()));
} else {
return reactionText(reaction.reaction);
}
@@ -56,7 +58,7 @@ QVariant ReactionModel::data(const QModelIndex &index, int role) const
for (int i = 0; i < reaction.authors.count() && i < 3; i++) {
if (i != 0) {
if (i < reaction.authors.count() - 1) {
text += QStringLiteral(", ");
text += u", "_s;
} else {
text += i18nc("Separate the usernames of users", " and ");
}
@@ -115,8 +117,8 @@ void ReactionModel::updateReactions()
}
if (const auto &e = eventCast<const Quotient::ReactionEvent>(a)) {
reactions[e->key()].append(e->senderId());
if (e->contentJson()[QStringLiteral("shortcode")].toString().length()) {
m_shortcodes[e->key()] = e->contentJson()[QStringLiteral("shortcode")].toString().toHtmlEscaped();
if (e->contentJson()["shortcode"_L1].toString().length()) {
m_shortcodes[e->key()] = e->contentJson()["shortcode"_L1].toString().toHtmlEscaped();
}
}
}
@@ -152,17 +154,16 @@ QHash<int, QByteArray> ReactionModel::roleNames() const
QString ReactionModel::reactionText(QString text) const
{
text = text.toHtmlEscaped();
if (text.startsWith(QStringLiteral("mxc://"))) {
if (text.startsWith(u"mxc://"_s)) {
static QFont font;
static int size = font.pixelSize();
if (size == -1) {
size = font.pointSizeF() * 1.333;
}
return QStringLiteral("<img src=\"%1\" width=\"%2\" height=\"%2\">")
.arg(m_room->connection()->makeMediaUrl(QUrl(text)).toString(), QString::number(size));
return u"<img src=\"%1\" width=\"%2\" height=\"%2\">"_s.arg(m_room->connection()->makeMediaUrl(QUrl(text)).toString(), QString::number(size));
}
return Utils::isEmoji(text) ? QStringLiteral("<span style=\"font-family: 'emoji';\">") + text + QStringLiteral("</span>") : text;
return Utils::isEmoji(text) ? u"<span style=\"font-family: 'emoji';\">"_s + text + u"</span>"_s : text;
}
#include "moc_reactionmodel.cpp"

View File

@@ -9,6 +9,8 @@
#define MAXMARKERS 5
using namespace Qt::StringLiterals;
ReadMarkerModel::ReadMarkerModel(const QString &eventId, NeoChatRoom *room)
: QAbstractListModel(nullptr)
, m_room(room)
@@ -127,7 +129,7 @@ QString ReadMarkerModel::excessReadMarkersString()
}
if (m_markerIds.size() > MAXMARKERS) {
return QStringLiteral("+ ") + QString::number(m_markerIds.size() - MAXMARKERS);
return u"+ "_s + QString::number(m_markerIds.size() - MAXMARKERS);
} else {
return QString();
}

View File

@@ -231,7 +231,7 @@ QVariant RoomListModel::data(const QModelIndex &index, int role) const
}
if (role == JoinStateRole) {
if (!room->successorId().isEmpty()) {
return QStringLiteral("upgraded");
return u"upgraded"_s;
}
return QVariant::fromValue(room->joinState());
}

View File

@@ -301,9 +301,9 @@ QVariant RoomTreeModel::data(const QModelIndex &index, int role) const
}
if (role == DelegateTypeRole) {
if (index.row() == NeoChatRoomType::AddDirect) {
return QStringLiteral("addDirect");
return u"addDirect"_s;
}
return QStringLiteral("section");
return u"section"_s;
}
if (role == IconRole) {
return NeoChatRoomType::typeIconName(index.row());
@@ -340,7 +340,7 @@ QVariant RoomTreeModel::data(const QModelIndex &index, int role) const
}
if (role == JoinStateRole) {
if (!room->successorId().isEmpty()) {
return QStringLiteral("upgraded");
return u"upgraded"_s;
}
return QVariant::fromValue(room->joinState());
}
@@ -372,7 +372,7 @@ QVariant RoomTreeModel::data(const QModelIndex &index, int role) const
return room->isDirectChat();
}
if (role == DelegateTypeRole) {
return QStringLiteral("normal");
return u"normal"_s;
}
if (role == RoomTypeRole) {
if (room->creation()) {

View File

@@ -55,7 +55,7 @@ void SearchModel::search()
.searchTerm = m_searchText,
.keys = {},
.filter = filter,
.orderBy = "recent"_ls,
.orderBy = "recent"_L1,
.eventContext = SearchJob::IncludeEventContext{3, 3, true},
.includeState = false,
.groupings = std::nullopt,
@@ -124,7 +124,7 @@ QVariant SearchModel::data(const QModelIndex &index, int role) const
return QVariant::fromValue<MessageContentModel *>(new MessageContentModel(m_room, event.id()));
}
if (event.isStateEvent()) {
if (event.matrixType() == QStringLiteral("org.matrix.msc3672.beacon_info")) {
if (event.matrixType() == u"org.matrix.msc3672.beacon_info"_s) {
return QVariant::fromValue<MessageContentModel *>(new MessageContentModel(m_room, event.id()));
}
}

View File

@@ -11,6 +11,8 @@
#include "neochatconnection.h"
using namespace Qt::StringLiterals;
ServerListModel::ServerListModel(QObject *parent)
: QAbstractListModel(parent)
{
@@ -56,7 +58,7 @@ int ServerListModel::rowCount(const QModelIndex &parent) const
void ServerListModel::checkServer(const QString &url)
{
const auto stateConfig = KSharedConfig::openStateConfig();
const KConfigGroup serverGroup = stateConfig->group(QStringLiteral("Servers"));
const KConfigGroup serverGroup = stateConfig->group(u"Servers"_s);
if (!serverGroup.hasKey(url)) {
if (Quotient::isJobPending(m_checkServerJob)) {
@@ -73,7 +75,7 @@ void ServerListModel::checkServer(const QString &url)
void ServerListModel::addServer(const QString &url)
{
const auto stateConfig = KSharedConfig::openStateConfig();
KConfigGroup serverGroup = stateConfig->group(QStringLiteral("Servers"));
KConfigGroup serverGroup = stateConfig->group(u"Servers"_s);
if (!serverGroup.hasKey(url)) {
Server newServer = Server{
@@ -95,7 +97,7 @@ void ServerListModel::addServer(const QString &url)
void ServerListModel::removeServerAtIndex(int row)
{
const auto stateConfig = KSharedConfig::openStateConfig();
KConfigGroup serverGroup = stateConfig->group(QStringLiteral("Servers"));
KConfigGroup serverGroup = stateConfig->group(u"Servers"_s);
serverGroup.deleteEntry(data(index(row), UrlRole).toString());
@@ -140,7 +142,7 @@ void ServerListModel::initialize()
beginResetModel();
const auto stateConfig = KSharedConfig::openStateConfig();
const KConfigGroup serverGroup = stateConfig->group(QStringLiteral("Servers"));
const KConfigGroup serverGroup = stateConfig->group(u"Servers"_s);
QString domain = m_connection->domain();
@@ -153,7 +155,7 @@ void ServerListModel::initialize()
});
// Add matrix.org
m_servers.append(Server{
QStringLiteral("matrix.org"),
u"matrix.org"_s,
false,
false,
false,

View File

@@ -7,6 +7,8 @@
#include "neochatconnection.h"
using namespace Qt::StringLiterals;
SortFilterRoomListModel::SortFilterRoomListModel(RoomListModel *sourceModel, QObject *parent)
: QSortFilterProxyModel(parent)
{
@@ -39,7 +41,7 @@ bool SortFilterRoomListModel::filterAcceptsRow(int source_row, const QModelIndex
{
QModelIndex index = sourceModel()->index(source_row, 0, source_parent);
if (sourceModel()->data(index, RoomListModel::JoinStateRole).toString() == QStringLiteral("upgraded")
if (sourceModel()->data(index, RoomListModel::JoinStateRole).toString() == u"upgraded"_s
&& dynamic_cast<RoomListModel *>(sourceModel())->connection()->room(sourceModel()->data(index, RoomListModel::ReplacementIdRole).toString())) {
return false;
}

View File

@@ -131,7 +131,7 @@ bool SortFilterRoomTreeModel::filterAcceptsRow(int source_row, const QModelIndex
return false;
}
if (sourceModel()->data(index, RoomTreeModel::JoinStateRole).toString() == QStringLiteral("upgraded")
if (sourceModel()->data(index, RoomTreeModel::JoinStateRole).toString() == u"upgraded"_s
&& dynamic_cast<RoomTreeModel *>(sourceModel())->connection()->room(sourceModel()->data(index, RoomTreeModel::ReplacementIdRole).toString())) {
return false;
}

View File

@@ -5,6 +5,8 @@
#include "roomlistmodel.h"
using namespace Qt::StringLiterals;
SortFilterSpaceListModel::SortFilterSpaceListModel(RoomListModel *sourceModel, QObject *parent)
: QSortFilterProxyModel{parent}
{
@@ -26,7 +28,7 @@ bool SortFilterSpaceListModel::filterAcceptsRow(int source_row, const QModelInde
{
Q_UNUSED(source_parent);
return sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::IsSpaceRole).toBool()
&& sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::JoinStateRole).toString() != QStringLiteral("upgraded")
&& sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::JoinStateRole).toString() != u"upgraded"_s
&& !sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::IsChildSpaceRole).toBool();
}

View File

@@ -147,7 +147,7 @@ void SpaceChildrenModel::insertChildren(std::vector<Quotient::GetSpaceHierarchyJ
children[i].avatarUrl,
children[i].guestCanJoin,
children[i].worldReadable,
children[i].roomType == QLatin1String("m.space"),
children[i].roomType == u"m.space"_s,
std::move(children[i].childrenState)));
}
}
@@ -217,7 +217,7 @@ QVariant SpaceChildrenModel::data(const QModelIndex &index, int role) const
}
if (role == CanAddChildrenRole) {
if (const auto room = static_cast<NeoChatRoom *>(m_space->connection()->room(child->id()))) {
return room->canSendState(QLatin1String("m.space.child"));
return room->canSendState(u"m.space.child"_s);
}
return false;
}
@@ -237,20 +237,20 @@ QVariant SpaceChildrenModel::data(const QModelIndex &index, int role) const
}
if (role == CanSetParentRole) {
if (const auto room = static_cast<NeoChatRoom *>(m_space->connection()->room(child->id()))) {
return room->canSendState(QLatin1String("m.space.parent"));
return room->canSendState(u"m.space.parent"_s);
}
return false;
}
if (role == IsDeclaredParentRole) {
if (const auto room = static_cast<NeoChatRoom *>(m_space->connection()->room(child->id()))) {
return room->currentState().contains(QLatin1String("m.space.parent"), child->parentItem()->id());
return room->currentState().contains(u"m.space.parent"_s, child->parentItem()->id());
}
return false;
}
if (role == CanRemove) {
const auto parent = child->parentItem();
if (const auto room = static_cast<NeoChatRoom *>(m_space->connection()->room(parent->id()))) {
return room->canSendState(QLatin1String("m.space.child"));
return room->canSendState(u"m.space.child"_s);
}
return false;
}
@@ -265,14 +265,14 @@ QVariant SpaceChildrenModel::data(const QModelIndex &index, int role) const
return QString();
}
const auto childState = child->parentItem()->childStateContent(child);
return childState[QLatin1String("order")].toString();
return childState["order"_L1].toString();
}
if (role == ChildTimestampRole) {
if (child->parentItem() == nullptr) {
return QString();
}
const auto childState = child->parentItem()->childState(child);
return childState[QLatin1String("origin_server_ts")].toString();
return childState["origin_server_ts"_L1].toString();
}
return {};

View File

@@ -5,6 +5,8 @@
#include "neochatconnection.h"
using namespace Qt::StringLiterals;
SpaceTreeItem::SpaceTreeItem(NeoChatConnection *connection,
SpaceTreeItem *parent,
const QString &id,
@@ -122,11 +124,11 @@ int SpaceTreeItem::memberCount() const
QUrl SpaceTreeItem::avatarUrl() const
{
if (m_avatarUrl.isEmpty() || m_avatarUrl.scheme() != QLatin1String("mxc")) {
if (m_avatarUrl.isEmpty() || m_avatarUrl.scheme() != u"mxc"_s) {
return {};
}
auto url = m_connection->makeMediaUrl(m_avatarUrl);
if (url.scheme() == QLatin1String("mxc")) {
if (url.scheme() == u"mxc"_s) {
return url;
}
return {};
@@ -199,5 +201,5 @@ bool SpaceTreeItem::isSuggested() const
return false;
}
const auto childStateContent = m_parentItem->childStateContent(this);
return childStateContent.value(QLatin1String("suggested")).toBool();
return childStateContent.value("suggested"_L1).toBool();
}

View File

@@ -33,13 +33,13 @@ QVariant StickerModel::data(const QModelIndex &index, int role) const
}
if (role == IsStickerRole) {
if (image.usage) {
return image.usage->isEmpty() || image.usage->contains("sticker"_ls);
return image.usage->isEmpty() || image.usage->contains("sticker"_L1);
}
return true;
}
if (role == IsEmojiRole) {
if (image.usage) {
return image.usage->isEmpty() || image.usage->contains("emoticon"_ls);
return image.usage->isEmpty() || image.usage->contains("emoticon"_L1);
}
return true;
}
@@ -118,18 +118,18 @@ void StickerModel::postSticker(int index)
const auto &body = image.body ? *image.body : image.shortcode;
QJsonObject infoJson;
if (image.info) {
infoJson["w"_ls] = image.info->imageSize.width();
infoJson["h"_ls] = image.info->imageSize.height();
infoJson["mimetype"_ls] = image.info->mimeType.name();
infoJson["size"_ls] = image.info->payloadSize;
infoJson["w"_L1] = image.info->imageSize.width();
infoJson["h"_L1] = image.info->imageSize.height();
infoJson["mimetype"_L1] = image.info->mimeType.name();
infoJson["size"_L1] = image.info->payloadSize;
// TODO thumbnail
}
QJsonObject content{
{"body"_ls, body},
{"url"_ls, image.url.toString()},
{"info"_ls, infoJson},
{"body"_L1, body},
{"url"_L1, image.url.toString()},
{"info"_L1, infoJson},
};
m_room->postJson("m.sticker"_ls, content);
m_room->postJson("m.sticker"_L1, content);
}
#include "moc_stickermodel.cpp"

View File

@@ -77,8 +77,7 @@ void ThreadModel::fetchMore(const QModelIndex &parent)
if (!m_currentJob && m_nextBatch.has_value()) {
const auto room = dynamic_cast<NeoChatRoom *>(QObject::parent());
const auto connection = room->connection();
m_currentJob =
connection->callApi<Quotient::GetRelatingEventsWithRelTypeJob>(room->id(), m_threadRootId, QLatin1String("m.thread"), *m_nextBatch, QString(), 5);
m_currentJob = connection->callApi<Quotient::GetRelatingEventsWithRelTypeJob>(room->id(), m_threadRootId, u"m.thread"_s, *m_nextBatch, QString(), 5);
connect(m_currentJob, &Quotient::BaseJob::success, this, [this]() {
const auto room = dynamic_cast<NeoChatRoom *>(QObject::parent());
auto newEvents = m_currentJob->chunk();

View File

@@ -11,6 +11,8 @@
#include "neochatconnection.h"
using namespace Qt::StringLiterals;
ThreePIdModel::ThreePIdModel(NeoChatConnection *connection)
: QAbstractListModel(connection)
{
@@ -82,8 +84,8 @@ void ThreePIdModel::refreshBindStatus()
const auto openIdJob = connection->callApi<Quotient::RequestOpenIdTokenJob>(connection->userId());
connect(openIdJob, &Quotient::BaseJob::success, this, [this, connection, openIdJob]() {
const auto requestUrl = QUrl(connection->identityServer().toString() + QStringLiteral("/_matrix/identity/v2/account/register"));
if (!(requestUrl.scheme() == QStringLiteral("https") || requestUrl.scheme() == QStringLiteral("http"))) {
const auto requestUrl = QUrl(connection->identityServer().toString() + u"/_matrix/identity/v2/account/register"_s);
if (!(requestUrl.scheme() == u"https"_s || requestUrl.scheme() == u"http"_s)) {
return;
}
@@ -91,10 +93,10 @@ void ThreePIdModel::refreshBindStatus()
auto newRequest = Quotient::NetworkAccessManager::instance()->post(request, QJsonDocument(openIdJob->jsonData()).toJson());
connect(newRequest, &QNetworkReply::finished, this, [this, connection, newRequest]() {
QJsonObject replyJson = QJsonDocument::fromJson(newRequest->readAll()).object();
const auto identityServerToken = replyJson[QLatin1String("token")].toString();
const auto identityServerToken = replyJson["token"_L1].toString();
const auto requestUrl = QUrl(connection->identityServer().toString() + QStringLiteral("/_matrix/identity/v2/hash_details"));
if (!(requestUrl.scheme() == QStringLiteral("https") || requestUrl.scheme() == QStringLiteral("http"))) {
const auto requestUrl = QUrl(connection->identityServer().toString() + u"/_matrix/identity/v2/hash_details"_s);
if (!(requestUrl.scheme() == u"https"_s || requestUrl.scheme() == u"http"_s)) {
return;
}
@@ -104,10 +106,10 @@ void ThreePIdModel::refreshBindStatus()
auto hashReply = Quotient::NetworkAccessManager::instance()->get(hashRequest);
connect(hashReply, &QNetworkReply::finished, this, [this, connection, identityServerToken, hashReply]() {
QJsonObject replyJson = QJsonDocument::fromJson(hashReply->readAll()).object();
const auto lookupPepper = replyJson[QLatin1String("lookup_pepper")].toString();
const auto lookupPepper = replyJson["lookup_pepper"_L1].toString();
const auto requestUrl = QUrl(connection->identityServer().toString() + QStringLiteral("/_matrix/identity/v2/lookup"));
if (!(requestUrl.scheme() == QStringLiteral("https") || requestUrl.scheme() == QStringLiteral("http"))) {
const auto requestUrl = QUrl(connection->identityServer().toString() + u"/_matrix/identity/v2/lookup"_s);
if (!(requestUrl.scheme() == u"https"_s || requestUrl.scheme() == u"http"_s)) {
return;
}
@@ -115,21 +117,21 @@ void ThreePIdModel::refreshBindStatus()
lookupRequest.setRawHeader("Authorization", "Bearer " + identityServerToken.toLatin1());
QJsonObject requestData = {
{QLatin1String("algorithm"), QLatin1String("none")},
{QLatin1String("pepper"), lookupPepper},
{"algorithm"_L1, "none"_L1},
{"pepper"_L1, lookupPepper},
};
QJsonArray idLookups;
for (const auto &id : m_threePIds) {
idLookups += QStringLiteral("%1 %2").arg(id.address, id.medium);
idLookups += u"%1 %2"_s.arg(id.address, id.medium);
}
requestData[QLatin1String("addresses")] = idLookups;
requestData["addresses"_L1] = idLookups;
auto lookupReply = Quotient::NetworkAccessManager::instance()->post(lookupRequest, QJsonDocument(requestData).toJson(QJsonDocument::Compact));
connect(lookupReply, &QNetworkReply::finished, this, [this, connection, lookupReply]() {
beginResetModel();
m_bindings.clear();
QJsonObject mappings = QJsonDocument::fromJson(lookupReply->readAll()).object()[QLatin1String("mappings")].toObject();
QJsonObject mappings = QJsonDocument::fromJson(lookupReply->readAll()).object()["mappings"_L1].toObject();
for (const auto &id : mappings.keys()) {
if (mappings[id] == connection->userId()) {
m_bindings += id.section(u' ', 0, 0);

View File

@@ -132,7 +132,7 @@ QVariant UserDirectoryListModel::data(const QModelIndex &index, int role) const
return displayName;
}
return QStringLiteral("Unknown User");
return u"Unknown User"_s;
}
if (role == AvatarRole) {
auto avatarUrl = user.avatarUrl;

View File

@@ -104,7 +104,7 @@ QVariant UserListModel::data(const QModelIndex &index, int role) const
// User might not in the room yet, in this case pl can be nullptr.
// e.g. When invited but user not accepted or denied the invitation.
if (!pl) {
return QStringLiteral("Not Available");
return u"Not Available"_s;
}
auto userPl = pl->powerLevelForUser(memberId);

View File

@@ -10,6 +10,8 @@
#endif
#include <KStringHandler>
using namespace Qt::StringLiterals;
struct WebShortcutModelPrivate {
QString selectedText;
#ifdef HAVE_KIO
@@ -125,7 +127,7 @@ void WebShortcutModel::trigger(const QString &data)
void WebShortcutModel::configureWebShortcuts()
{
#ifdef HAVE_KIO
auto job = new KIO::CommandLauncherJob(QStringLiteral("kcmshell6"), QStringList() << QStringLiteral("webshortcuts"), this);
auto job = new KIO::CommandLauncherJob(u"kcmshell6"_s, QStringList() << u"webshortcuts"_s, this);
job->exec();
#endif
}

View File

@@ -56,10 +56,10 @@ NeoChatConnection::NeoChatConnection(const QUrl &server, QObject *parent)
void NeoChatConnection::connectSignals()
{
connect(this, &NeoChatConnection::accountDataChanged, this, [this](const QString &type) {
if (type == QLatin1String("org.kde.neochat.account_label")) {
if (type == u"org.kde.neochat.account_label"_s) {
Q_EMIT labelChanged();
}
if (type == QLatin1String("m.identity_server")) {
if (type == u"m.identity_server"_s) {
Q_EMIT identityServerChanged();
}
});
@@ -75,7 +75,7 @@ void NeoChatConnection::connectSignals()
}
});
connect(this, &NeoChatConnection::requestFailed, this, [this](BaseJob *job) {
if (dynamic_cast<DownloadFileJob *>(job) && job->jsonData()["errcode"_ls].toString() == "M_TOO_LARGE"_ls) {
if (dynamic_cast<DownloadFileJob *>(job) && job->jsonData()["errcode"_L1].toString() == "M_TOO_LARGE"_L1) {
Q_EMIT showMessage(MessageType::Warning, i18n("File too large to download.<br />Contact your matrix server administrator for support."));
}
});
@@ -140,7 +140,7 @@ void NeoChatConnection::connectSignals()
[this] {
auto job = callApi<GetVersionsJob>(BackgroundRequest);
connect(job, &GetVersionsJob::success, this, [this, job] {
m_canCheckMutualRooms = job->unstableFeatures().contains("uk.half-shot.msc2666.query_mutual_rooms"_ls);
m_canCheckMutualRooms = job->unstableFeatures().contains("uk.half-shot.msc2666.query_mutual_rooms"_L1);
Q_EMIT canCheckMutualRoomsChanged();
});
},
@@ -169,7 +169,7 @@ void NeoChatConnection::refreshBadgeNotificationCount()
void NeoChatConnection::logout(bool serverSideLogout)
{
SettingsGroup(QStringLiteral("Accounts")).remove(userId());
SettingsGroup(u"Accounts"_s).remove(userId());
QKeychain::DeletePasswordJob job(qAppName());
job.setAutoDelete(true);
@@ -205,9 +205,9 @@ QVariantList NeoChatConnection::getSupportedRoomVersions() const
QVariantList supportedRoomVersions;
for (const auto &v : roomVersions) {
QVariantMap roomVersionMap;
roomVersionMap.insert("id"_ls, v.id);
roomVersionMap.insert("status"_ls, v.status);
roomVersionMap.insert("isStable"_ls, v.isStable());
roomVersionMap.insert("id"_L1, v.id);
roomVersionMap.insert("status"_L1, v.status);
roomVersionMap.insert("isStable"_L1, v.isStable());
supportedRoomVersions.append(roomVersionMap);
}
return supportedRoomVersions;
@@ -225,18 +225,18 @@ void NeoChatConnection::changePassword(const QString &currentPassword, const QSt
if (job->error() == 103) {
QJsonObject replyData = job->jsonData();
QJsonObject authData;
authData["session"_ls] = replyData["session"_ls];
authData["password"_ls] = currentPassword;
authData["type"_ls] = "m.login.password"_ls;
authData["user"_ls] = user()->id();
QJsonObject identifier = {{"type"_ls, "m.id.user"_ls}, {"user"_ls, user()->id()}};
authData["identifier"_ls] = identifier;
authData["session"_L1] = replyData["session"_L1];
authData["password"_L1] = currentPassword;
authData["type"_L1] = "m.login.password"_L1;
authData["user"_L1] = user()->id();
QJsonObject identifier = {{"type"_L1, "m.id.user"_L1}, {"user"_L1, user()->id()}};
authData["identifier"_L1] = identifier;
NeochatChangePasswordJob *innerJob = callApi<NeochatChangePasswordJob>(newPassword, false, authData);
connect(innerJob, &BaseJob::success, this, [this]() {
Q_EMIT passwordStatus(PasswordStatus::Success);
});
connect(innerJob, &BaseJob::failure, this, [innerJob, this]() {
Q_EMIT passwordStatus(innerJob->jsonData()["errcode"_ls] == "M_FORBIDDEN"_ls ? PasswordStatus::Wrong : PasswordStatus::Other);
Q_EMIT passwordStatus(innerJob->jsonData()["errcode"_L1] == "M_FORBIDDEN"_L1 ? PasswordStatus::Wrong : PasswordStatus::Other);
});
}
});
@@ -245,15 +245,15 @@ void NeoChatConnection::changePassword(const QString &currentPassword, const QSt
void NeoChatConnection::setLabel(const QString &label)
{
QJsonObject json{
{"account_label"_ls, label},
{"account_label"_L1, label},
};
setAccountData("org.kde.neochat.account_label"_ls, json);
setAccountData("org.kde.neochat.account_label"_L1, json);
Q_EMIT labelChanged();
}
QString NeoChatConnection::label() const
{
return accountDataJson("org.kde.neochat.account_label"_ls)["account_label"_ls].toString();
return accountDataJson("org.kde.neochat.account_label"_L1)["account_label"_L1].toString();
}
void NeoChatConnection::deactivateAccount(const QString &password)
@@ -263,12 +263,12 @@ void NeoChatConnection::deactivateAccount(const QString &password)
if (job->error() == 103) {
QJsonObject replyData = job->jsonData();
QJsonObject authData;
authData["session"_ls] = replyData["session"_ls];
authData["password"_ls] = password;
authData["type"_ls] = "m.login.password"_ls;
authData["user"_ls] = user()->id();
QJsonObject identifier = {{"type"_ls, "m.id.user"_ls}, {"user"_ls, user()->id()}};
authData["identifier"_ls] = identifier;
authData["session"_L1] = replyData["session"_L1];
authData["password"_L1] = password;
authData["type"_L1] = "m.login.password"_L1;
authData["user"_L1] = user()->id();
QJsonObject identifier = {{"type"_L1, "m.id.user"_L1}, {"user"_L1, user()->id()}};
authData["identifier"_L1] = identifier;
auto innerJob = callApi<NeoChatDeactivateAccountJob>(authData);
connect(innerJob, &BaseJob::success, this, [this]() {
logout(false);
@@ -284,11 +284,11 @@ ThreePIdModel *NeoChatConnection::threePIdModel() const
bool NeoChatConnection::hasIdentityServer() const
{
if (!hasAccountData(QLatin1String("m.identity_server"))) {
if (!hasAccountData(u"m.identity_server"_s)) {
return false;
}
const auto url = accountData(QLatin1String("m.identity_server"))->contentPart<QUrl>(QLatin1String("base_url"));
const auto url = accountData(u"m.identity_server"_s)->contentPart<QUrl>("base_url"_L1);
if (!url.isEmpty()) {
return true;
}
@@ -297,11 +297,11 @@ bool NeoChatConnection::hasIdentityServer() const
QUrl NeoChatConnection::identityServer() const
{
if (!hasAccountData(QLatin1String("m.identity_server"))) {
if (!hasAccountData(u"m.identity_server"_s)) {
return {};
}
const auto url = accountData(QLatin1String("m.identity_server"))->contentPart<QUrl>(QLatin1String("base_url"));
const auto url = accountData(u"m.identity_server"_s)->contentPart<QUrl>("base_url"_L1);
if (!url.isEmpty()) {
return url;
}
@@ -322,10 +322,10 @@ void NeoChatConnection::createRoom(const QString &name, const QString &topic, co
QList<CreateRoomJob::StateEvent> initialStateEvents;
if (!parent.isEmpty()) {
initialStateEvents.append(CreateRoomJob::StateEvent{
"m.space.parent"_ls,
"m.space.parent"_L1,
QJsonObject{
{"canonical"_ls, true},
{"via"_ls, QJsonArray{domain()}},
{"canonical"_L1, true},
{"via"_L1, QJsonArray{domain()}},
},
parent,
});
@@ -336,7 +336,7 @@ void NeoChatConnection::createRoom(const QString &name, const QString &topic, co
connect(job, &Quotient::CreateRoomJob::success, this, [this, parent, setChildParent, job]() {
if (setChildParent) {
if (auto parentRoom = room(parent)) {
parentRoom->setState(QLatin1String("m.space.child"), job->roomId(), QJsonObject{{QLatin1String("via"), QJsonArray{domain()}}});
parentRoom->setState(u"m.space.child"_s, job->roomId(), QJsonObject{{"via"_L1, QJsonArray{domain()}}});
}
}
});
@@ -351,21 +351,22 @@ void NeoChatConnection::createSpace(const QString &name, const QString &topic, c
QList<CreateRoomJob::StateEvent> initialStateEvents;
if (!parent.isEmpty()) {
initialStateEvents.append(CreateRoomJob::StateEvent{
"m.space.parent"_ls,
"m.space.parent"_L1,
QJsonObject{
{"canonical"_ls, true},
{"via"_ls, QJsonArray{domain()}},
{"canonical"_L1, true},
{"via"_L1, QJsonArray{domain()}},
},
parent,
});
}
const auto job = Connection::createRoom(Connection::UnpublishRoom, {}, name, topic, {}, {}, {}, false, initialStateEvents, {}, QJsonObject{{"type"_ls, "m.space"_ls}});
const auto job =
Connection::createRoom(Connection::UnpublishRoom, {}, name, topic, {}, {}, {}, false, initialStateEvents, {}, QJsonObject{{"type"_L1, "m.space"_L1}});
if (!parent.isEmpty()) {
connect(job, &Quotient::CreateRoomJob::success, this, [this, parent, setChildParent, job]() {
if (setChildParent) {
if (auto parentRoom = room(parent)) {
parentRoom->setState(QLatin1String("m.space.child"), job->roomId(), QJsonObject{{QLatin1String("via"), QJsonArray{domain()}}});
parentRoom->setState(u"m.space.child"_s, job->roomId(), QJsonObject{{"via"_L1, QJsonArray{domain()}}});
}
}
});
@@ -451,7 +452,7 @@ QCoro::Task<void> NeoChatConnection::setupPushNotifications(QString endpoint)
{
#ifdef HAVE_KUNIFIEDPUSH
QUrl gatewayEndpoint(endpoint);
gatewayEndpoint.setPath(QStringLiteral("/_matrix/push/v1/notify"));
gatewayEndpoint.setPath(u"/_matrix/push/v1/notify"_s);
QNetworkRequest checkGateway(gatewayEndpoint);
auto reply = co_await NetworkAccessManager::instance()->get(checkGateway);
@@ -460,15 +461,15 @@ QCoro::Task<void> NeoChatConnection::setupPushNotifications(QString endpoint)
// This is because Matrix does not natively support UnifiedPush
const auto &replyJson = QJsonDocument::fromJson(reply->readAll()).object();
if (replyJson["unifiedpush"_L1]["gateway"_L1].toString() == QStringLiteral("matrix")) {
if (replyJson["unifiedpush"_L1]["gateway"_L1].toString() == u"matrix"_s) {
callApi<PostPusherJob>(endpoint,
QStringLiteral("http"),
QStringLiteral("org.kde.neochat"),
QStringLiteral("NeoChat"),
u"http"_s,
u"org.kde.neochat"_s,
u"NeoChat"_s,
deviceId(),
QString(), // profileTag is intentionally left empty for now, it's optional
QStringLiteral("en-US"),
PostPusherJob::PusherData{QUrl::fromUserInput(gatewayEndpoint.toString()), QStringLiteral(" ")},
u"en-US"_s,
PostPusherJob::PusherData{QUrl::fromUserInput(gatewayEndpoint.toString()), u" "_s},
false);
qInfo() << "Registered for push notifications";
@@ -488,9 +489,9 @@ QString NeoChatConnection::deviceKey() const
QString NeoChatConnection::encryptionKey() const
{
auto query = database()->prepareQuery(QStringLiteral("SELECT curveKey FROM tracked_devices WHERE matrixId=:matrixId AND deviceid=:deviceId LIMIT 1;"));
query.bindValue(QStringLiteral(":matrixId"), userId());
query.bindValue(QStringLiteral(":deviceId"), deviceId());
auto query = database()->prepareQuery(u"SELECT curveKey FROM tracked_devices WHERE matrixId=:matrixId AND deviceid=:deviceId LIMIT 1;"_s);
query.bindValue(u":matrixId"_s, userId());
query.bindValue(u":deviceId"_s, deviceId());
database()->execute(query);
if (!query.next()) {
return {};

View File

@@ -86,7 +86,7 @@ NeoChatRoom::NeoChatRoom(Connection *connection, QString roomId, JoinState joinS
return;
}
auto localPath = this->fileTransferInfo(eventId).localPath.toLocalFile();
auto config = KSharedConfig::openStateConfig(QStringLiteral("neochatdownloads"))->group(QStringLiteral("downloads"));
auto config = KSharedConfig::openStateConfig(u"neochatdownloads"_s)->group(u"downloads"_s);
config.writePathEntry(mxcUrl.mid(6), localPath);
}
});
@@ -123,7 +123,7 @@ NeoChatRoom::NeoChatRoom(Connection *connection, QString roomId, JoinState joinS
&Room::baseStateLoaded,
this,
[this]() {
updatePushNotificationState(QStringLiteral("m.push_rules"));
updatePushNotificationState(u"m.push_rules"_s);
Q_EMIT canEncryptRoomChanged();
if (this->joinState() == JoinState::Invite) {
@@ -143,7 +143,7 @@ NeoChatRoom::NeoChatRoom(Connection *connection, QString roomId, JoinState joinS
Q_EMIT defaultUrlPreviewStateChanged();
});
connect(this, &Room::accountDataChanged, this, [this](QString type) {
if (type == "org.matrix.room.preview_urls"_ls) {
if (type == "org.matrix.room.preview_urls"_L1) {
Q_EMIT urlPreviewEnabledChanged();
}
});
@@ -216,15 +216,15 @@ QCoro::Task<void> NeoChatRoom::doUploadFile(QUrl url, QString body)
}
auto mime = QMimeDatabase().mimeTypeForUrl(url);
url.setScheme("file"_ls);
url.setScheme("file"_L1);
QFileInfo fileInfo(url.isLocalFile() ? url.toLocalFile() : url.toString());
EventContent::FileContentBase *content;
if (mime.name().startsWith("image/"_ls)) {
if (mime.name().startsWith("image/"_L1)) {
QImage image(url.toLocalFile());
content = new EventContent::ImageContent(url, fileInfo.size(), mime, image.size(), fileInfo.fileName());
} else if (mime.name().startsWith("audio/"_ls)) {
} else if (mime.name().startsWith("audio/"_L1)) {
content = new EventContent::AudioContent(url, fileInfo.size(), mime, fileInfo.fileName());
} else if (mime.name().startsWith("video/"_ls)) {
} else if (mime.name().startsWith("video/"_L1)) {
QMediaPlayer player;
player.setSource(url);
co_await qCoro(&player, &QMediaPlayer::mediaStatusChanged);
@@ -365,9 +365,9 @@ bool NeoChatRoom::lastEventIsSpoiler() const
{
if (auto event = lastEvent()) {
if (auto e = eventCast<const RoomMessageEvent>(event)) {
if (e->has<EventContent::TextContent>() && e->content() && e->mimeType().name() == "text/html"_ls) {
if (e->has<EventContent::TextContent>() && e->content() && e->mimeType().name() == "text/html"_L1) {
auto htmlBody = e->get<EventContent::TextContent>()->body;
return htmlBody.contains("data-mx-spoiler"_ls);
return htmlBody.contains("data-mx-spoiler"_L1);
}
}
}
@@ -455,7 +455,7 @@ void NeoChatRoom::changeAvatar(const QUrl &localFile)
const auto job = connection()->uploadFile(localFile.toLocalFile());
if (isJobPending(job)) {
connect(job, &BaseJob::success, this, [this, job] {
connection()->callApi<SetRoomStateWithKeyJob>(id(), "m.room.avatar"_ls, QString(), QJsonObject{{"url"_ls, job->contentUri().toString()}});
connection()->callApi<SetRoomStateWithKeyJob>(id(), "m.room.avatar"_L1, QString(), QJsonObject{{"url"_L1, job->contentUri().toString()}});
});
}
}
@@ -464,23 +464,23 @@ QString msgTypeToString(MessageEventType msgType)
{
switch (msgType) {
case MessageEventType::Text:
return "m.text"_ls;
return "m.text"_L1;
case MessageEventType::File:
return "m.file"_ls;
return "m.file"_L1;
case MessageEventType::Audio:
return "m.audio"_ls;
return "m.audio"_L1;
case MessageEventType::Emote:
return "m.emote"_ls;
return "m.emote"_L1;
case MessageEventType::Image:
return "m.image"_ls;
return "m.image"_L1;
case MessageEventType::Video:
return "m.video"_ls;
return "m.video"_L1;
case MessageEventType::Notice:
return "m.notice"_ls;
return "m.notice"_L1;
case MessageEventType::Location:
return "m.location"_ls;
return "m.location"_L1;
default:
return "m.text"_ls;
return "m.text"_L1;
}
}
@@ -566,7 +566,7 @@ bool NeoChatRoom::isInvite() const
bool NeoChatRoom::readOnly() const
{
return !canSendEvent("m.room.message"_ls);
return !canSendEvent("m.room.message"_L1);
}
bool NeoChatRoom::isUserBanned(const QString &user) const
@@ -594,29 +594,29 @@ QString NeoChatRoom::joinRule() const
void NeoChatRoom::setJoinRule(const QString &joinRule, const QList<QString> &allowedSpaces)
{
if (!canSendState("m.room.join_rules"_ls)) {
if (!canSendState("m.room.join_rules"_L1)) {
qWarning() << "Power level too low to set join rules";
return;
}
auto actualRule = joinRule;
if (joinRule == "restricted"_ls && allowedSpaces.isEmpty()) {
actualRule = "private"_ls;
if (joinRule == "restricted"_L1 && allowedSpaces.isEmpty()) {
actualRule = "private"_L1;
}
QJsonArray allowConditions;
if (actualRule == "restricted"_ls) {
if (actualRule == "restricted"_L1) {
for (auto allowedSpace : allowedSpaces) {
allowConditions += QJsonObject{{"type"_ls, "m.room_membership"_ls}, {"room_id"_ls, allowedSpace}};
allowConditions += QJsonObject{{"type"_L1, "m.room_membership"_L1}, {"room_id"_L1, allowedSpace}};
}
}
QJsonObject content;
content.insert("join_rule"_ls, joinRule);
content.insert("join_rule"_L1, joinRule);
if (!allowConditions.isEmpty()) {
content.insert("allow"_ls, allowConditions);
content.insert("allow"_L1, allowConditions);
}
qWarning() << content;
setState("m.room.join_rules"_ls, {}, content);
setState("m.room.join_rules"_L1, {}, content);
// Not emitting joinRuleChanged() here, since that would override the change in the UI with the *current* value, which is not the *new* value.
}
@@ -626,40 +626,40 @@ QList<QString> NeoChatRoom::restrictedIds() const
if (!joinRulesEvent) {
return {};
}
if (joinRulesEvent->joinRule() != "restricted"_ls) {
if (joinRulesEvent->joinRule() != "restricted"_L1) {
return {};
}
QList<QString> roomIds;
for (auto allow : joinRulesEvent->allow()) {
roomIds += allow.toObject().value("room_id"_ls).toString();
roomIds += allow.toObject().value("room_id"_L1).toString();
}
return roomIds;
}
QString NeoChatRoom::historyVisibility() const
{
return currentState().get("m.room.history_visibility"_ls)->contentJson()["history_visibility"_ls].toString();
return currentState().get("m.room.history_visibility"_L1)->contentJson()["history_visibility"_L1].toString();
}
void NeoChatRoom::setHistoryVisibility(const QString &historyVisibilityRule)
{
if (!canSendState("m.room.history_visibility"_ls)) {
if (!canSendState("m.room.history_visibility"_L1)) {
qWarning() << "Power level too low to set history visibility";
return;
}
setState("m.room.history_visibility"_ls, {}, QJsonObject{{"history_visibility"_ls, historyVisibilityRule}});
setState("m.room.history_visibility"_L1, {}, QJsonObject{{"history_visibility"_L1, historyVisibilityRule}});
// Not emitting historyVisibilityChanged() here, since that would override the change in the UI with the *current* value, which is not the *new* value.
}
bool NeoChatRoom::defaultUrlPreviewState() const
{
auto urlPreviewsDisabled = currentState().get("org.matrix.room.preview_urls"_ls);
auto urlPreviewsDisabled = currentState().get("org.matrix.room.preview_urls"_L1);
// Some rooms will not have this state event set so check for a nullptr return.
if (urlPreviewsDisabled != nullptr) {
return !urlPreviewsDisabled->contentJson()["disable"_ls].toBool();
return !urlPreviewsDisabled->contentJson()["disable"_L1].toBool();
} else {
return false;
}
@@ -667,7 +667,7 @@ bool NeoChatRoom::defaultUrlPreviewState() const
void NeoChatRoom::setDefaultUrlPreviewState(const bool &defaultUrlPreviewState)
{
if (!canSendState("org.matrix.room.preview_urls"_ls)) {
if (!canSendState("org.matrix.room.preview_urls"_L1)) {
qWarning() << "Power level too low to set the default URL preview state for the room";
return;
}
@@ -701,13 +701,13 @@ void NeoChatRoom::setDefaultUrlPreviewState(const bool &defaultUrlPreviewState)
*
* You just have to set disable to true to disable URL previews by default.
*/
setState("org.matrix.room.preview_urls"_ls, {}, QJsonObject{{"disable"_ls, !defaultUrlPreviewState}});
setState("org.matrix.room.preview_urls"_L1, {}, QJsonObject{{"disable"_L1, !defaultUrlPreviewState}});
}
bool NeoChatRoom::urlPreviewEnabled() const
{
if (hasAccountData("org.matrix.room.preview_urls"_ls)) {
return !accountData("org.matrix.room.preview_urls"_ls)->contentJson()["disable"_ls].toBool();
if (hasAccountData("org.matrix.room.preview_urls"_L1)) {
return !accountData("org.matrix.room.preview_urls"_L1)->contentJson()["disable"_L1].toBool();
} else {
return defaultUrlPreviewState();
}
@@ -728,8 +728,8 @@ void NeoChatRoom::setUrlPreviewEnabled(const bool &urlPreviewEnabled)
*/
connection()->callApi<SetAccountDataPerRoomJob>(localMember().id(),
id(),
"org.matrix.room.preview_urls"_ls,
QJsonObject{{"disable"_ls, !urlPreviewEnabled}});
"org.matrix.room.preview_urls"_L1,
QJsonObject{{"disable"_L1, !urlPreviewEnabled}});
}
void NeoChatRoom::setUserPowerLevel(const QString &userID, const int &powerLevel)
@@ -738,7 +738,7 @@ void NeoChatRoom::setUserPowerLevel(const QString &userID, const int &powerLevel
qWarning() << "Cannot modify the power level of the only user";
return;
}
if (!canSendState("m.room.power_levels"_ls)) {
if (!canSendState("m.room.power_levels"_L1)) {
qWarning() << "Power level too low to set user power levels";
return;
}
@@ -748,14 +748,14 @@ void NeoChatRoom::setUserPowerLevel(const QString &userID, const int &powerLevel
}
int clampPowerLevel = std::clamp(powerLevel, -1, 100);
auto powerLevelContent = currentState().get("m.room.power_levels"_ls)->contentJson();
auto powerLevelUserOverrides = powerLevelContent["users"_ls].toObject();
auto powerLevelContent = currentState().get("m.room.power_levels"_L1)->contentJson();
auto powerLevelUserOverrides = powerLevelContent["users"_L1].toObject();
if (powerLevelUserOverrides[userID] != clampPowerLevel) {
powerLevelUserOverrides[userID] = clampPowerLevel;
powerLevelContent["users"_ls] = powerLevelUserOverrides;
powerLevelContent["users"_L1] = powerLevelUserOverrides;
setState("m.room.power_levels"_ls, {}, powerLevelContent);
setState("m.room.power_levels"_L1, {}, powerLevelContent);
}
}
@@ -795,15 +795,15 @@ QCoro::Task<void> NeoChatRoom::doDeleteMessagesByUser(const QString &user, QStri
bool NeoChatRoom::hasParent() const
{
return currentState().eventsOfType("m.space.parent"_ls).size() > 0;
return currentState().eventsOfType("m.space.parent"_L1).size() > 0;
}
QList<QString> NeoChatRoom::parentIds() const
{
auto parentEvents = currentState().eventsOfType("m.space.parent"_ls);
auto parentEvents = currentState().eventsOfType("m.space.parent"_L1);
QList<QString> parentIds;
for (const auto &parentEvent : parentEvents) {
if (parentEvent->contentJson().contains("via"_ls) && !parentEvent->contentPart<QJsonArray>("via"_ls).isEmpty()) {
if (parentEvent->contentJson().contains("via"_L1) && !parentEvent->contentPart<QJsonArray>("via"_L1).isEmpty()) {
parentIds += parentEvent->stateKey();
}
}
@@ -827,10 +827,10 @@ QList<NeoChatRoom *> NeoChatRoom::parentObjects(bool multiLevel) const
QString NeoChatRoom::canonicalParent() const
{
auto parentEvents = currentState().eventsOfType("m.space.parent"_ls);
auto parentEvents = currentState().eventsOfType("m.space.parent"_L1);
for (const auto &parentEvent : parentEvents) {
if (parentEvent->contentJson().contains("via"_ls) && !parentEvent->contentPart<QJsonArray>("via"_ls).isEmpty()) {
if (parentEvent->contentPart<bool>("canonical"_ls)) {
if (parentEvent->contentJson().contains("via"_L1) && !parentEvent->contentPart<QJsonArray>("via"_L1).isEmpty()) {
if (parentEvent->contentPart<bool>("canonical"_L1)) {
return parentEvent->stateKey();
}
}
@@ -843,28 +843,28 @@ void NeoChatRoom::setCanonicalParent(const QString &parentId)
if (!canModifyParent(parentId)) {
return;
}
if (const auto &parent = currentState().get("m.space.parent"_ls, parentId)) {
if (const auto &parent = currentState().get("m.space.parent"_L1, parentId)) {
auto content = parent->contentJson();
content.insert("canonical"_ls, true);
setState("m.space.parent"_ls, parentId, content);
content.insert("canonical"_L1, true);
setState("m.space.parent"_L1, parentId, content);
} else {
return;
}
// Only one canonical parent can exist so make sure others are set false.
auto parentEvents = currentState().eventsOfType("m.space.parent"_ls);
auto parentEvents = currentState().eventsOfType("m.space.parent"_L1);
for (const auto &parentEvent : parentEvents) {
if (parentEvent->contentPart<bool>("canonical"_ls) && parentEvent->stateKey() != parentId) {
if (parentEvent->contentPart<bool>("canonical"_L1) && parentEvent->stateKey() != parentId) {
auto content = parentEvent->contentJson();
content.insert("canonical"_ls, false);
setState("m.space.parent"_ls, parentEvent->stateKey(), content);
content.insert("canonical"_L1, false);
setState("m.space.parent"_L1, parentEvent->stateKey(), content);
}
}
}
bool NeoChatRoom::canModifyParent(const QString &parentId) const
{
if (!canSendState("m.space.parent"_ls)) {
if (!canSendState("m.space.parent"_L1)) {
return false;
}
// If we can't peek the parent we assume that we neither have permission nor is
@@ -876,12 +876,12 @@ bool NeoChatRoom::canModifyParent(const QString &parentId) const
// If the user is allowed to set space child events in the parent they are
// allowed to set the space as a parent (even if a space child event doesn't
// exist).
if (parent->canSendState("m.space.child"_ls)) {
if (parent->canSendState("m.space.child"_L1)) {
return true;
}
// If the parent has a space child event the user can set as a parent (even
// if they don't have permission to set space child events in that parent).
if (parent->currentState().contains("m.space.child"_ls, id())) {
if (parent->currentState().contains("m.space.child"_L1, id())) {
return true;
}
}
@@ -895,21 +895,21 @@ void NeoChatRoom::addParent(const QString &parentId, bool canonical, bool setPar
}
if (canonical) {
// Only one canonical parent can exist so make sure others are set false.
auto parentEvents = currentState().eventsOfType("m.space.parent"_ls);
auto parentEvents = currentState().eventsOfType("m.space.parent"_L1);
for (const auto &parentEvent : parentEvents) {
if (parentEvent->contentPart<bool>("canonical"_ls)) {
if (parentEvent->contentPart<bool>("canonical"_L1)) {
auto content = parentEvent->contentJson();
content.insert("canonical"_ls, false);
setState("m.space.parent"_ls, parentEvent->stateKey(), content);
content.insert("canonical"_L1, false);
setState("m.space.parent"_L1, parentEvent->stateKey(), content);
}
}
}
setState("m.space.parent"_ls, parentId, QJsonObject{{"canonical"_ls, canonical}, {"via"_ls, QJsonArray{connection()->domain()}}});
setState("m.space.parent"_L1, parentId, QJsonObject{{"canonical"_L1, canonical}, {"via"_L1, QJsonArray{connection()->domain()}}});
if (setParentChild) {
if (auto parent = static_cast<NeoChatRoom *>(connection()->room(parentId))) {
parent->setState("m.space.child"_ls, id(), QJsonObject{{QLatin1String("via"), QJsonArray{connection()->domain()}}});
parent->setState("m.space.child"_L1, id(), QJsonObject{{"via"_L1, QJsonArray{connection()->domain()}}});
}
}
}
@@ -919,10 +919,10 @@ void NeoChatRoom::removeParent(const QString &parentId)
if (!canModifyParent(parentId)) {
return;
}
if (!currentState().contains("m.space.parent"_ls, parentId)) {
if (!currentState().contains("m.space.parent"_L1, parentId)) {
return;
}
setState("m.space.parent"_ls, parentId, {});
setState("m.space.parent"_L1, parentId, {});
}
bool NeoChatRoom::isSpace() const
@@ -956,26 +956,24 @@ void NeoChatRoom::addChild(const QString &childId, bool setChildParent, bool can
if (!isSpace()) {
return;
}
if (!canSendEvent("m.space.child"_ls)) {
if (!canSendEvent("m.space.child"_L1)) {
return;
}
setState("m.space.child"_ls,
childId,
QJsonObject{{QLatin1String("via"), QJsonArray{connection()->domain()}}, {"suggested"_ls, suggested}, {"order"_ls, order}});
setState("m.space.child"_L1, childId, QJsonObject{{"via"_L1, QJsonArray{connection()->domain()}}, {"suggested"_L1, suggested}, {"order"_L1, order}});
if (setChildParent) {
if (auto child = static_cast<NeoChatRoom *>(connection()->room(childId))) {
if (child->canSendState("m.space.parent"_ls)) {
child->setState("m.space.parent"_ls, id(), QJsonObject{{"canonical"_ls, canonical}, {"via"_ls, QJsonArray{connection()->domain()}}});
if (child->canSendState("m.space.parent"_L1)) {
child->setState("m.space.parent"_L1, id(), QJsonObject{{"canonical"_L1, canonical}, {"via"_L1, QJsonArray{connection()->domain()}}});
if (canonical) {
// Only one canonical parent can exist so make sure others are set to false.
auto parentEvents = child->currentState().eventsOfType("m.space.parent"_ls);
auto parentEvents = child->currentState().eventsOfType("m.space.parent"_L1);
for (const auto &parentEvent : parentEvents) {
if (parentEvent->contentPart<bool>("canonical"_ls)) {
if (parentEvent->contentPart<bool>("canonical"_L1)) {
auto content = parentEvent->contentJson();
content.insert("canonical"_ls, false);
setState("m.space.parent"_ls, parentEvent->stateKey(), content);
content.insert("canonical"_L1, false);
setState("m.space.parent"_L1, parentEvent->stateKey(), content);
}
}
}
@@ -989,15 +987,15 @@ void NeoChatRoom::removeChild(const QString &childId, bool unsetChildParent)
if (!isSpace()) {
return;
}
if (!canSendEvent("m.space.child"_ls)) {
if (!canSendEvent("m.space.child"_L1)) {
return;
}
setState("m.space.child"_ls, childId, {});
setState("m.space.child"_L1, childId, {});
if (unsetChildParent) {
if (auto child = static_cast<NeoChatRoom *>(connection()->room(childId))) {
if (child->canSendState("m.space.parent"_ls) && child->currentState().contains("m.space.parent"_ls, id())) {
child->setState("m.space.parent"_ls, id(), {});
if (child->canSendState("m.space.parent"_L1) && child->currentState().contains("m.space.parent"_L1, id())) {
child->setState("m.space.parent"_L1, id(), {});
}
}
}
@@ -1005,11 +1003,11 @@ void NeoChatRoom::removeChild(const QString &childId, bool unsetChildParent)
bool NeoChatRoom::isSuggested(const QString &childId)
{
if (!currentState().contains("m.space.child"_ls, childId)) {
if (!currentState().contains("m.space.child"_L1, childId)) {
return false;
}
const auto childEvent = currentState().get("m.space.child"_ls, childId);
return childEvent->contentPart<bool>("suggested"_ls);
const auto childEvent = currentState().get("m.space.child"_L1, childId);
return childEvent->contentPart<bool>("suggested"_L1);
}
void NeoChatRoom::toggleChildSuggested(const QString &childId)
@@ -1017,13 +1015,13 @@ void NeoChatRoom::toggleChildSuggested(const QString &childId)
if (!isSpace()) {
return;
}
if (!canSendEvent("m.space.child"_ls)) {
if (!canSendEvent("m.space.child"_L1)) {
return;
}
if (const auto childEvent = currentState().get("m.space.child"_ls, childId)) {
if (const auto childEvent = currentState().get("m.space.child"_L1, childId)) {
auto content = childEvent->contentJson();
content.insert("suggested"_ls, !childEvent->contentPart<bool>("suggested"_ls));
setState("m.space.child"_ls, childId, content);
content.insert("suggested"_L1, !childEvent->contentPart<bool>("suggested"_L1));
setState("m.space.child"_L1, childId, content);
}
}
@@ -1032,20 +1030,20 @@ void NeoChatRoom::setChildOrder(const QString &childId, const QString &order)
if (!isSpace()) {
return;
}
if (!canSendEvent("m.space.child"_ls)) {
if (!canSendEvent("m.space.child"_L1)) {
return;
}
if (const auto childEvent = currentState().get("m.space.child"_ls, childId)) {
if (const auto childEvent = currentState().get("m.space.child"_L1, childId)) {
auto content = childEvent->contentJson();
if (!content.contains("via"_ls)) {
if (!content.contains("via"_L1)) {
return;
}
if (content.value("order"_ls).toString() == order) {
if (content.value("order"_L1).toString() == order) {
return;
}
content.insert("order"_ls, order);
setState("m.space.child"_ls, childId, content);
content.insert("order"_L1, order);
setState("m.space.child"_L1, childId, content);
}
}
@@ -1076,26 +1074,26 @@ void NeoChatRoom::setPushNotificationState(PushNotificationState::State state)
* Note to prevent race conditions any rule that is going ot be overridden later is not removed.
* If the default push notification state is chosen any existing rule needs to be removed.
*/
QJsonObject accountData = connection()->accountDataJson("m.push_rules"_ls);
QJsonObject accountData = connection()->accountDataJson("m.push_rules"_L1);
// For default and mute check for a room rule and remove if found.
if (state == PushNotificationState::Default || state == PushNotificationState::Mute) {
QJsonArray roomRuleArray = accountData["global"_ls].toObject()["room"_ls].toArray();
QJsonArray roomRuleArray = accountData["global"_L1].toObject()["room"_L1].toArray();
for (const auto &i : roomRuleArray) {
QJsonObject roomRule = i.toObject();
if (roomRule["rule_id"_ls] == id()) {
connection()->callApi<DeletePushRuleJob>("room"_ls, id());
if (roomRule["rule_id"_L1] == id()) {
connection()->callApi<DeletePushRuleJob>("room"_L1, id());
}
}
}
// For default, all and @mentions and keywords check for an override rule and remove if found.
if (state == PushNotificationState::Default || state == PushNotificationState::All || state == PushNotificationState::MentionKeyword) {
QJsonArray overrideRuleArray = accountData["global"_ls].toObject()["override"_ls].toArray();
QJsonArray overrideRuleArray = accountData["global"_L1].toObject()["override"_L1].toArray();
for (const auto &i : overrideRuleArray) {
QJsonObject overrideRule = i.toObject();
if (overrideRule["rule_id"_ls] == id()) {
connection()->callApi<DeletePushRuleJob>("override"_ls, id());
if (overrideRule["rule_id"_L1] == id()) {
connection()->callApi<DeletePushRuleJob>("override"_L1, id());
}
}
}
@@ -1111,7 +1109,7 @@ void NeoChatRoom::setPushNotificationState(PushNotificationState::State state)
* "don't_notify"
* ]
*/
const QList<QVariant> actions = {"dont_notify"_ls};
const QList<QVariant> actions = {"dont_notify"_L1};
/**
* Setup the push condition to get all events for the current room
* see https://spec.matrix.org/v1.3/client-server-api/#conditions-1
@@ -1125,15 +1123,15 @@ void NeoChatRoom::setPushNotificationState(PushNotificationState::State state)
* ]
*/
PushCondition pushCondition;
pushCondition.kind = "event_match"_ls;
pushCondition.key = "room_id"_ls;
pushCondition.kind = "event_match"_L1;
pushCondition.key = "room_id"_L1;
pushCondition.pattern = id();
const QList<PushCondition> conditions = {pushCondition};
// Add new override rule and make sure it's enabled
auto job = connection()->callApi<SetPushRuleJob>("override"_ls, id(), actions, QString(), QString(), conditions, QString());
auto job = connection()->callApi<SetPushRuleJob>("override"_L1, id(), actions, QString(), QString(), conditions, QString());
connect(job, &BaseJob::success, this, [this]() {
auto enableJob = connection()->callApi<SetPushRuleEnabledJob>("override"_ls, id(), true);
auto enableJob = connection()->callApi<SetPushRuleEnabledJob>("override"_L1, id(), true);
connect(enableJob, &BaseJob::success, this, [this]() {
m_pushNotificationStateUpdating = false;
});
@@ -1153,13 +1151,13 @@ void NeoChatRoom::setPushNotificationState(PushNotificationState::State state)
* "don't_notify"
* ]
*/
const QList<QVariant> actions = {"dont_notify"_ls};
const QList<QVariant> actions = {"dont_notify"_L1};
// No conditions for a room rule
const QList<PushCondition> conditions;
auto setJob = connection()->callApi<SetPushRuleJob>("room"_ls, id(), actions, QString(), QString(), conditions, QString());
auto setJob = connection()->callApi<SetPushRuleJob>("room"_L1, id(), actions, QString(), QString(), conditions, QString());
connect(setJob, &BaseJob::success, this, [this]() {
auto enableJob = connection()->callApi<SetPushRuleEnabledJob>("room"_ls, id(), true);
auto enableJob = connection()->callApi<SetPushRuleEnabledJob>("room"_L1, id(), true);
connect(enableJob, &BaseJob::success, this, [this]() {
m_pushNotificationStateUpdating = false;
});
@@ -1181,16 +1179,16 @@ void NeoChatRoom::setPushNotificationState(PushNotificationState::State state)
* ]
*/
QJsonObject tweaks;
tweaks.insert("set_tweak"_ls, "sound"_ls);
tweaks.insert("value"_ls, "default"_ls);
const QList<QVariant> actions = {"notify"_ls, tweaks};
tweaks.insert("set_tweak"_L1, "sound"_L1);
tweaks.insert("value"_L1, "default"_L1);
const QList<QVariant> actions = {"notify"_L1, tweaks};
// No conditions for a room rule
const QList<PushCondition> conditions;
// Add new room rule and make sure enabled
auto setJob = connection()->callApi<SetPushRuleJob>("room"_ls, id(), actions, QString(), QString(), conditions, QString());
auto setJob = connection()->callApi<SetPushRuleJob>("room"_L1, id(), actions, QString(), QString(), conditions, QString());
connect(setJob, &BaseJob::success, this, [this]() {
auto enableJob = connection()->callApi<SetPushRuleEnabledJob>("room"_ls, id(), true);
auto enableJob = connection()->callApi<SetPushRuleEnabledJob>("room"_L1, id(), true);
connect(enableJob, &BaseJob::success, this, [this]() {
m_pushNotificationStateUpdating = false;
});
@@ -1203,28 +1201,28 @@ void NeoChatRoom::setPushNotificationState(PushNotificationState::State state)
void NeoChatRoom::updatePushNotificationState(QString type)
{
if (type != "m.push_rules"_ls || m_pushNotificationStateUpdating) {
if (type != "m.push_rules"_L1 || m_pushNotificationStateUpdating) {
return;
}
QJsonObject accountData = connection()->accountDataJson("m.push_rules"_ls);
QJsonObject accountData = connection()->accountDataJson("m.push_rules"_L1);
// First look for a room rule with the room id
QJsonArray roomRuleArray = accountData["global"_ls].toObject()["room"_ls].toArray();
QJsonArray roomRuleArray = accountData["global"_L1].toObject()["room"_L1].toArray();
for (const auto &i : roomRuleArray) {
QJsonObject roomRule = i.toObject();
if (roomRule["rule_id"_ls] == id()) {
if (roomRule["actions"_ls].toArray().size() == 0) {
if (roomRule["rule_id"_L1] == id()) {
if (roomRule["actions"_L1].toArray().size() == 0) {
m_currentPushNotificationState = PushNotificationState::MentionKeyword;
Q_EMIT pushNotificationStateChanged(m_currentPushNotificationState);
return;
}
QString notifyAction = roomRule["actions"_ls].toArray()[0].toString();
if (notifyAction == "notify"_ls) {
QString notifyAction = roomRule["actions"_L1].toArray()[0].toString();
if (notifyAction == "notify"_L1) {
m_currentPushNotificationState = PushNotificationState::All;
Q_EMIT pushNotificationStateChanged(m_currentPushNotificationState);
return;
} else if (notifyAction == "dont_notify"_ls) {
} else if (notifyAction == "dont_notify"_L1) {
m_currentPushNotificationState = PushNotificationState::MentionKeyword;
Q_EMIT pushNotificationStateChanged(m_currentPushNotificationState);
return;
@@ -1233,17 +1231,17 @@ void NeoChatRoom::updatePushNotificationState(QString type)
}
// Check for an override rule with the room id
QJsonArray overrideRuleArray = accountData["global"_ls].toObject()["override"_ls].toArray();
QJsonArray overrideRuleArray = accountData["global"_L1].toObject()["override"_L1].toArray();
for (const auto &i : overrideRuleArray) {
QJsonObject overrideRule = i.toObject();
if (overrideRule["rule_id"_ls] == id()) {
if (overrideRule["actions"_ls].toArray().isEmpty()) {
if (overrideRule["rule_id"_L1] == id()) {
if (overrideRule["actions"_L1].toArray().isEmpty()) {
m_currentPushNotificationState = PushNotificationState::Mute;
Q_EMIT pushNotificationStateChanged(m_currentPushNotificationState);
return;
}
QString notifyAction = overrideRule["actions"_ls].toArray()[0].toString();
if (notifyAction == "dont_notify"_ls) {
QString notifyAction = overrideRule["actions"_L1].toArray()[0].toString();
if (notifyAction == "dont_notify"_L1) {
m_currentPushNotificationState = PushNotificationState::Mute;
Q_EMIT pushNotificationStateChanged(m_currentPushNotificationState);
return;
@@ -1363,7 +1361,7 @@ FileTransferInfo NeoChatRoom::cachedFileTransferInfo(const Quotient::RoomEvent *
return transferInfo;
}
auto config = KSharedConfig::openStateConfig(QStringLiteral("neochatdownloads"))->group(QStringLiteral("downloads"));
auto config = KSharedConfig::openStateConfig(u"neochatdownloads"_s)->group(u"downloads"_s);
if (!config.hasKey(mxcUrl.mid(6))) {
return transferInfo;
}
@@ -1419,9 +1417,9 @@ void NeoChatRoom::replyLastMessage()
if (e->msgtype() != MessageEventType::Unknown) {
QString eventId;
if (content.contains("m.new_content"_ls)) {
if (content.contains("m.new_content"_L1)) {
// The message has been edited so we have to return the id of the original message instead of the replacement
eventId = content["m.relates_to"_ls].toObject()["event_id"_ls].toString();
eventId = content["m.relates_to"_L1].toObject()["event_id"_L1].toString();
} else {
// For any message that isn't an edit return the id of the current message
eventId = (*it)->id();
@@ -1453,9 +1451,9 @@ void NeoChatRoom::editLastMessage()
if (e->msgtype() != MessageEventType::Unknown) {
QString eventId;
if (content.contains("m.new_content"_ls)) {
if (content.contains("m.new_content"_L1)) {
// The message has been edited so we have to return the id of the original message instead of the replacement
eventId = content["m.relates_to"_ls].toObject()["event_id"_ls].toString();
eventId = content["m.relates_to"_L1].toObject()["event_id"_L1].toString();
} else {
// For any message that isn't an edit return the id of the current message
eventId = (*it)->id();
@@ -1469,7 +1467,7 @@ void NeoChatRoom::editLastMessage()
bool NeoChatRoom::canEncryptRoom() const
{
return !usesEncryption() && canSendState("m.room.encryption"_ls);
return !usesEncryption() && canSendState("m.room.encryption"_L1);
}
static PollHandler *emptyPollHandler = new PollHandler;
@@ -1585,25 +1583,25 @@ NeochatRoomMember *NeoChatRoom::directChatRemoteMember()
void NeoChatRoom::sendLocation(float lat, float lon, const QString &description)
{
QJsonObject locationContent{
{"uri"_ls, "geo:%1,%2"_ls.arg(QString::number(lat), QString::number(lon))},
{"uri"_L1, "geo:%1,%2"_L1.arg(QString::number(lat), QString::number(lon))},
};
if (!description.isEmpty()) {
locationContent["description"_ls] = description;
locationContent["description"_L1] = description;
}
QJsonObject content{
{"body"_ls, i18nc("'Lat' and 'Lon' as in Latitude and Longitude", "Lat: %1, Lon: %2", lat, lon)},
{"msgtype"_ls, "m.location"_ls},
{"geo_uri"_ls, "geo:%1,%2"_ls.arg(QString::number(lat), QString::number(lon))},
{"org.matrix.msc3488.location"_ls, locationContent},
{"org.matrix.msc3488.asset"_ls,
{"body"_L1, i18nc("'Lat' and 'Lon' as in Latitude and Longitude", "Lat: %1, Lon: %2", lat, lon)},
{"msgtype"_L1, "m.location"_L1},
{"geo_uri"_L1, "geo:%1,%2"_L1.arg(QString::number(lat), QString::number(lon))},
{"org.matrix.msc3488.location"_L1, locationContent},
{"org.matrix.msc3488.asset"_L1,
QJsonObject{
{"type"_ls, "m.pin"_ls},
{"type"_L1, "m.pin"_L1},
}},
{"org.matrix.msc1767.text"_ls, i18nc("'Lat' and 'Lon' as in Latitude and Longitude", "Lat: %1, Lon: %2", lat, lon)},
{"org.matrix.msc1767.text"_L1, i18nc("'Lat' and 'Lon' as in Latitude and Longitude", "Lat: %1, Lon: %2", lat, lon)},
};
postJson("m.room.message"_ls, content);
postJson("m.room.message"_L1, content);
}
QByteArray NeoChatRoom::roomAcountDataJson(const QString &eventType)
@@ -1667,7 +1665,7 @@ std::pair<const Quotient::RoomEvent *, bool> NeoChatRoom::getEvent(const QString
const RoomEvent *NeoChatRoom::getReplyForEvent(const RoomEvent &event) const
{
const QString &replyEventId = event.contentJson()["m.relates_to"_ls].toObject()["m.in_reply_to"_ls].toObject()["event_id"_ls].toString();
const QString &replyEventId = event.contentJson()["m.relates_to"_L1].toObject()["m.in_reply_to"_L1].toObject()["event_id"_L1].toString();
if (replyEventId.isEmpty()) {
return {};
};

View File

@@ -77,20 +77,20 @@ void NotificationsManager::processNotificationJob(QPointer<NeoChatConnection> co
const auto connectionId = connection->user()->id();
const auto notifications = job->jsonData()["notifications"_ls].toArray();
const auto notifications = job->jsonData()["notifications"_L1].toArray();
if (initialization) {
for (const auto &notification : notifications) {
if (!m_initialTimestamp.contains(connectionId)) {
m_initialTimestamp[connectionId] = notification["ts"_ls].toVariant().toLongLong();
m_initialTimestamp[connectionId] = notification["ts"_L1].toVariant().toLongLong();
} else {
qint64 timestamp = notification["ts"_ls].toVariant().toLongLong();
qint64 timestamp = notification["ts"_L1].toVariant().toLongLong();
if (timestamp > m_initialTimestamp[connectionId]) {
m_initialTimestamp[connectionId] = timestamp;
}
}
auto connectionNotifications = m_oldNotifications.value(connectionId);
connectionNotifications += notification["event"_ls]["event_id"_ls].toString();
connectionNotifications += notification["event"_L1]["event_id"_L1].toString();
m_oldNotifications[connectionId] = connectionNotifications;
}
return;
@@ -99,23 +99,23 @@ void NotificationsManager::processNotificationJob(QPointer<NeoChatConnection> co
QMap<QString, std::pair<qint64, QJsonObject>> notificationsToPost;
for (const auto &n : notifications) {
const auto notification = n.toObject();
if (notification["read"_ls].toBool()) {
if (notification["read"_L1].toBool()) {
continue;
}
auto connectionNotifications = m_oldNotifications.value(connectionId);
if (connectionNotifications.contains(notification["event"_ls]["event_id"_ls].toString())) {
if (connectionNotifications.contains(notification["event"_L1]["event_id"_L1].toString())) {
continue;
}
connectionNotifications += notification["event"_ls]["event_id"_ls].toString();
connectionNotifications += notification["event"_L1]["event_id"_L1].toString();
m_oldNotifications[connectionId] = connectionNotifications;
if (!shouldPostNotification(connection, n)) {
continue;
}
const auto &roomId = notification["room_id"_ls].toString();
if (!notificationsToPost.contains(roomId) || notificationsToPost[roomId].first < notification["ts"_ls].toVariant().toLongLong()) {
notificationsToPost[roomId] = {notification["ts"_ls].toVariant().toLongLong(), notification};
const auto &roomId = notification["room_id"_L1].toString();
if (!notificationsToPost.contains(roomId) || notificationsToPost[roomId].first < notification["ts"_L1].toVariant().toLongLong()) {
notificationsToPost[roomId] = {notification["ts"_L1].toVariant().toLongLong(), notification};
}
}
@@ -125,7 +125,7 @@ void NotificationsManager::processNotificationJob(QPointer<NeoChatConnection> co
if (!room) {
continue;
}
auto sender = room->member(notification["event"_ls]["sender"_ls].toString());
auto sender = room->member(notification["event"_L1]["sender"_L1].toString());
// Don't display notifications for events in invited rooms
// This should prevent empty notifications from appearing when they shouldn't
@@ -134,16 +134,16 @@ void NotificationsManager::processNotificationJob(QPointer<NeoChatConnection> co
}
QString body;
if (notification["event"_ls]["type"_ls].toString() == "org.matrix.msc3381.poll.start"_ls) {
body = notification["event"_ls]["content"_ls]["org.matrix.msc3381.poll.start"_ls]["question"_ls]["body"_ls].toString();
} else if (notification["event"_ls]["type"_ls] == "m.room.encrypted"_ls) {
if (notification["event"_L1]["type"_L1].toString() == "org.matrix.msc3381.poll.start"_L1) {
body = notification["event"_L1]["content"_L1]["org.matrix.msc3381.poll.start"_L1]["question"_L1]["body"_L1].toString();
} else if (notification["event"_L1]["type"_L1] == "m.room.encrypted"_L1) {
const auto decrypted = connection->decryptNotification(notification);
body = decrypted["content"_ls]["body"_ls].toString();
body = decrypted["content"_L1]["body"_L1].toString();
if (body.isEmpty()) {
body = i18n("Encrypted Message");
}
} else {
body = notification["event"_ls]["content"_ls]["body"_ls].toString();
body = notification["event"_L1]["content"_L1]["body"_L1].toString();
}
QImage avatar_image;
@@ -156,7 +156,7 @@ void NotificationsManager::processNotificationJob(QPointer<NeoChatConnection> co
sender.displayName(),
body,
avatar_image,
notification["event"_ls].toObject()["event_id"_ls].toString(),
notification["event"_L1].toObject()["event_id"_L1].toString(),
true,
pair.first);
}
@@ -168,7 +168,7 @@ bool NotificationsManager::shouldPostNotification(QPointer<NeoChatConnection> co
return false;
}
auto room = connection->room(notification["room_id"_ls].toString());
auto room = connection->room(notification["room_id"_L1].toString());
if (room == nullptr) {
return false;
}
@@ -184,7 +184,7 @@ bool NotificationsManager::shouldPostNotification(QPointer<NeoChatConnection> co
// If the notification timestamp is earlier than the initial timestamp assume
// the notification is old and shouldn't be posted.
qint64 timestamp = notification["ts"_ls].toDouble();
qint64 timestamp = notification["ts"_L1].toDouble();
if (timestamp < m_initialTimestamp[connection->user()->id()]) {
return false;
}
@@ -210,7 +210,7 @@ void NotificationsManager::postNotification(NeoChatRoom *room,
notification->close();
}
auto notification = new KNotification(QStringLiteral("message"));
auto notification = new KNotification(u"message"_s);
m_notifications.insert(roomId, {timestamp, notification});
connect(notification, &KNotification::closed, this, [this, roomId, notification] {
if (m_notifications[roomId].second == notification) {
@@ -255,7 +255,7 @@ void NotificationsManager::postNotification(NeoChatRoom *room,
notification->setReplyAction(std::move(replyAction));
}
notification->setHint(QStringLiteral("x-kde-origin-name"), room->localMember().id());
notification->setHint(u"x-kde-origin-name"_s, room->localMember().id());
notification->sendEvent();
}
@@ -272,8 +272,8 @@ void NotificationsManager::postInviteNotification(NeoChatRoom *rawRoom)
auto job = room->connection()->callApi<NeochatGetCommonRoomsJob>(roomMemberEvent->senderId());
connect(job, &BaseJob::result, this, [this, job, room] {
QJsonObject replyData = job->jsonData();
if (replyData.contains(QStringLiteral("joined"))) {
const bool inAnyOfOurRooms = !replyData[QStringLiteral("joined")].toArray().isEmpty();
if (replyData.contains(u"joined"_s)) {
const bool inAnyOfOurRooms = !replyData["joined"_L1].toArray().isEmpty();
if (inAnyOfOurRooms) {
doPostInviteNotification(room);
} else {
@@ -302,7 +302,7 @@ void NotificationsManager::doPostInviteNotification(QPointer<NeoChatRoom> room)
avatar_image = room->avatar(128);
}
KNotification *notification = new KNotification(QStringLiteral("invite"));
KNotification *notification = new KNotification(u"invite"_s);
notification->setText(i18n("%1 invited you to a room", sender.htmlSafeDisplayName()));
notification->setTitle(room->displayName());
notification->setPixmap(createNotificationImage(avatar_image, nullptr));
@@ -348,7 +348,7 @@ void NotificationsManager::doPostInviteNotification(QPointer<NeoChatRoom> room)
m_invitations.remove(room->id());
});
notification->setHint(QStringLiteral("x-kde-origin-name"), room->localMember().id());
notification->setHint(u"x-kde-origin-name"_s, room->localMember().id());
notification->sendEvent();
}
@@ -364,15 +364,15 @@ void NotificationsManager::postPushNotification(const QByteArray &message)
{
const auto json = QJsonDocument::fromJson(message).object();
const auto type = json["notification"_ls]["type"_ls].toString();
const auto type = json["notification"_L1]["type"_L1].toString();
// the only two types of push notifications we support right now
if (type == QStringLiteral("m.room.message") || type == QStringLiteral("m.room.encrypted")) {
auto notification = new KNotification("message"_ls);
if (type == u"m.room.message"_s || type == u"m.room.encrypted"_s) {
auto notification = new KNotification("message"_L1);
const auto sender = json["notification"_ls]["sender_display_name"_ls].toString();
const auto roomName = json["notification"_ls]["room_name"_ls].toString();
const auto roomId = json["notification"_ls]["room_id"_ls].toString();
const auto sender = json["notification"_L1]["sender_display_name"_L1].toString();
const auto roomName = json["notification"_L1]["room_name"_L1].toString();
const auto roomId = json["notification"_L1]["room_id"_L1].toString();
if (roomName.isEmpty() || sender == roomName) {
notification->setTitle(sender);
@@ -380,10 +380,10 @@ void NotificationsManager::postPushNotification(const QByteArray &message)
notification->setTitle(i18n("%1 (%2)", sender, roomName));
}
if (type == QStringLiteral("m.room.message")) {
const auto text = json["notification"_ls]["content"_ls]["body"_ls].toString();
if (type == u"m.room.message"_s) {
const auto text = json["notification"_L1]["content"_L1]["body"_L1].toString();
notification->setText(text.toHtmlEscaped());
} else if (type == QStringLiteral("m.room.encrypted")) {
} else if (type == u"m.room.encrypted"_s) {
notification->setText(i18n("Encrypted Message"));
}
@@ -391,11 +391,11 @@ void NotificationsManager::postPushNotification(const QByteArray &message)
auto openAction = notification->addAction(i18n("Open NeoChat"));
connect(openAction, &KNotificationAction::activated, this, [=]() {
QString properId = roomId;
properId = properId.replace(QStringLiteral("#"), QString());
properId = properId.replace(QStringLiteral("!"), QString());
properId = properId.replace(u"#"_s, QString());
properId = properId.replace(u"!"_s, QString());
auto *job = new KIO::ApplicationLauncherJob(KService::serviceByDesktopName(QStringLiteral("org.kde.neochat")));
job->setUrls({QUrl::fromUserInput(QStringLiteral("matrix:r/%1").arg(properId))});
auto *job = new KIO::ApplicationLauncherJob(KService::serviceByDesktopName(u"org.kde.neochat"_s));
job->setUrls({QUrl::fromUserInput(u"matrix:r/%1"_s.arg(properId))});
job->start();
});
#endif
@@ -404,7 +404,7 @@ void NotificationsManager::postPushNotification(const QByteArray &message)
notification->sendEvent();
m_notifications.insert(roomId, {json["ts"_ls].toVariant().toLongLong(), notification});
m_notifications.insert(roomId, {json["ts"_L1].toVariant().toLongLong(), notification});
} else {
qWarning() << "Skipping unsupported push notification" << type;
}

View File

@@ -43,9 +43,9 @@ void PollHandler::updatePoll(Quotient::RoomEventsRange events)
if (event->is<PollResponseEvent>()) {
handleAnswer(event->contentJson(), event->senderId(), event->originTimestamp());
}
if (event->contentPart<QJsonObject>("m.relates_to"_ls).contains("rel_type"_ls)
&& event->contentPart<QJsonObject>("m.relates_to"_ls)["rel_type"_ls].toString() == "m.replace"_ls
&& event->contentPart<QJsonObject>("m.relates_to"_ls)["event_id"_ls].toString() == m_pollStartEvent->id()) {
if (event->contentPart<QJsonObject>("m.relates_to"_L1).contains("rel_type"_L1)
&& event->contentPart<QJsonObject>("m.relates_to"_L1)["rel_type"_L1].toString() == "m.replace"_L1
&& event->contentPart<QJsonObject>("m.relates_to"_L1)["event_id"_L1].toString() == m_pollStartEvent->id()) {
Q_EMIT questionChanged();
Q_EMIT optionsChanged();
}
@@ -86,7 +86,7 @@ void PollHandler::handleAnswer(const QJsonObject &content, const QString &sender
m_answerTimestamps[sender] = timestamp;
m_answers[sender] = {};
int i = 0;
for (const auto &answer : content["org.matrix.msc3381.poll.response"_ls]["answers"_ls].toArray()) {
for (const auto &answer : content["org.matrix.msc3381.poll.response"_L1]["answers"_L1].toArray()) {
auto array = m_answers[sender].toArray();
array.insert(0, answer);
m_answers[sender] = array;
@@ -109,7 +109,7 @@ QString PollHandler::question() const
if (m_pollStartEvent == nullptr) {
return {};
}
return m_pollStartEvent->contentPart<QJsonObject>("org.matrix.msc3381.poll.start"_ls)["question"_ls].toObject()["body"_ls].toString();
return m_pollStartEvent->contentPart<QJsonObject>("org.matrix.msc3381.poll.start"_L1)["question"_L1].toObject()["body"_L1].toString();
}
QJsonArray PollHandler::options() const
@@ -117,7 +117,7 @@ QJsonArray PollHandler::options() const
if (m_pollStartEvent == nullptr) {
return {};
}
return m_pollStartEvent->contentPart<QJsonObject>("org.matrix.msc3381.poll.start"_ls)["answers"_ls].toArray();
return m_pollStartEvent->contentPart<QJsonObject>("org.matrix.msc3381.poll.start"_L1)["answers"_L1].toArray();
}
QJsonObject PollHandler::answers() const
@@ -141,7 +141,7 @@ QString PollHandler::kind() const
if (m_pollStartEvent == nullptr) {
return {};
}
return m_pollStartEvent->contentPart<QJsonObject>("org.matrix.msc3381.poll.start"_ls)["kind"_ls].toString();
return m_pollStartEvent->contentPart<QJsonObject>("org.matrix.msc3381.poll.start"_L1)["kind"_L1].toString();
}
void PollHandler::sendPollAnswer(const QString &eventId, const QString &answerId)

View File

@@ -5,6 +5,8 @@
#include <KPluginFactory>
#include <Purpose/PluginBase>
using namespace Qt::StringLiterals;
class NeoChatJob : public Purpose::Job
{
Q_OBJECT
@@ -25,11 +27,11 @@ public:
void start() override
{
const QJsonArray urlsJson = data().value(QStringLiteral("urls")).toArray();
const QString title = data().value(QStringLiteral("title")).toString();
const QString message = QStringLiteral("%1 - %2").arg(title, arrayToList(urlsJson).join(QLatin1Char(' ')));
const QJsonArray urlsJson = data().value("urls"_L1).toArray();
const QString title = data().value("title"_L1).toString();
const QString message = u"%1 - %2"_s.arg(title, arrayToList(urlsJson).join(QLatin1Char(' ')));
auto *job = new KIO::CommandLauncherJob(QStringLiteral("neochat"), {QStringLiteral("--share"), message});
auto *job = new KIO::CommandLauncherJob(u"neochat"_s, {u"--share"_s, message});
connect(job, &KJob::finished, this, &NeoChatJob::emitResult);
job->start();
}

View File

@@ -20,12 +20,12 @@ using namespace Quotient;
Registration::Registration()
{
auto server = new QTcpServer(this);
server->listen(QHostAddress("127.0.0.1"_ls), 20847);
server->listen(QHostAddress("127.0.0.1"_L1), 20847);
connect(server, &QTcpServer::newConnection, this, [this, server]() {
auto conn = server->nextPendingConnection();
connect(conn, &QIODevice::readyRead, this, [this, conn]() {
auto code =
"HTTP/1.0 200\nContent-type: text/html\n\n<html><head><script src=\"https://www.google.com/recaptcha/api.js\" async defer></script></head><body style=\"background: #00000000\"><center><div class=\"g-recaptcha\" data-sitekey=\"%1\"></div></center></body></html>"_ls
"HTTP/1.0 200\nContent-type: text/html\n\n<html><head><script src=\"https://www.google.com/recaptcha/api.js\" async defer></script></head><body style=\"background: #00000000\"><center><div class=\"g-recaptcha\" data-sitekey=\"%1\"></div></center></body></html>"_L1
.arg(m_recaptchaSiteKey);
conn->write(code.toLatin1().data(), code.length());
conn->close();
@@ -63,37 +63,37 @@ void Registration::registerAccount()
{
setStatus(Working);
std::optional<QJsonObject> authData;
if (nextStep() == "m.login.recaptcha"_ls) {
if (nextStep() == "m.login.recaptcha"_L1) {
authData = QJsonObject{
{"type"_ls, "m.login.recaptcha"_ls},
{"response"_ls, m_recaptchaResponse},
{"session"_ls, m_session},
{"type"_L1, "m.login.recaptcha"_L1},
{"response"_L1, m_recaptchaResponse},
{"session"_L1, m_session},
};
} else if (nextStep() == "m.login.terms"_ls) {
} else if (nextStep() == "m.login.terms"_L1) {
authData = QJsonObject{
{"type"_ls, "m.login.terms"_ls},
{"session"_ls, m_session},
{"type"_L1, "m.login.terms"_L1},
{"session"_L1, m_session},
};
} else if (nextStep() == "m.login.email.identity"_ls) {
} else if (nextStep() == "m.login.email.identity"_L1) {
authData = QJsonObject{
{"type"_ls, "m.login.email.identity"_ls},
{"threepid_creds"_ls,
{"type"_L1, "m.login.email.identity"_L1},
{"threepid_creds"_L1,
QJsonObject{
{"sid"_ls, m_sid},
{"client_secret"_ls, m_emailSecret},
{"sid"_L1, m_sid},
{"client_secret"_L1, m_emailSecret},
}},
{"session"_ls, m_session},
{"session"_L1, m_session},
};
}
auto job = m_connection->callApi<NeoChatRegisterJob>("user"_ls, authData, m_username, m_password, QString(), QString(), true);
auto job = m_connection->callApi<NeoChatRegisterJob>("user"_L1, authData, m_username, m_password, QString(), QString(), true);
connect(job, &BaseJob::result, this, [this, job]() {
if (job->status() == BaseJob::Success) {
setNextStep("loading"_ls);
setNextStep("loading"_L1);
auto connection = new NeoChatConnection(this);
auto matrixId = "@%1:%2"_ls.arg(m_username, m_homeserver);
auto matrixId = "@%1:%2"_L1.arg(m_username, m_homeserver);
connection->resolveServer(matrixId);
auto displayName = "NeoChat"_ls;
auto displayName = "NeoChat"_L1;
connection->loginWithPassword(matrixId, m_password, displayName);
connect(connection, &Connection::connected, this, [this, displayName, connection] {
@@ -120,27 +120,27 @@ void Registration::registerAccount()
return;
}
const auto &data = job->jsonData();
m_session = data["session"_ls].toString();
const auto &params = data["params"_ls].toObject();
m_session = data["session"_L1].toString();
const auto &params = data["params"_L1].toObject();
// I'm not motivated enough to figure out how we should handle the flow stuff, so:
// If there is a flow that requires e-mail, we use that, to make sure that the user can recover the account from a forgotten password.
// Otherwise, we're using the first flow.
auto selectedFlow = data["flows"_ls].toArray()[0].toObject()["stages"_ls].toArray();
for (const auto &flow : data["flows"_ls].toArray()) {
if (flow.toObject()["stages"_ls].toArray().contains("m.login.email.identity"_ls)) {
selectedFlow = flow.toObject()["stages"_ls].toArray();
auto selectedFlow = data["flows"_L1].toArray()[0].toObject()["stages"_L1].toArray();
for (const auto &flow : data["flows"_L1].toArray()) {
if (flow.toObject()["stages"_L1].toArray().contains("m.login.email.identity"_L1)) {
selectedFlow = flow.toObject()["stages"_L1].toArray();
}
}
setNextStep(selectedFlow[data["completed"_ls].toArray().size()].toString());
m_recaptchaSiteKey = params["m.login.recaptcha"_ls]["public_key"_ls].toString();
setNextStep(selectedFlow[data["completed"_L1].toArray().size()].toString());
m_recaptchaSiteKey = params["m.login.recaptcha"_L1]["public_key"_L1].toString();
Q_EMIT recaptchaSiteKeyChanged();
m_terms.clear();
for (const auto &term : params["m.login.terms"_ls]["policies"_ls].toObject().keys()) {
for (const auto &term : params["m.login.terms"_L1]["policies"_L1].toObject().keys()) {
QVariantMap termData;
termData["title"_ls] = params["m.login.terms"_ls]["policies"_ls][term]["en"_ls]["name"_ls].toString();
termData["url"_ls] = params["m.login.terms"_ls]["policies"_ls][term]["en"_ls]["url"_ls].toString();
termData["title"_L1] = params["m.login.terms"_L1]["policies"_L1][term]["en"_L1]["name"_L1].toString();
termData["url"_L1] = params["m.login.terms"_L1]["policies"_L1][term]["en"_L1]["url"_L1].toString();
m_terms += termData;
Q_EMIT termsChanged();
}
@@ -170,7 +170,7 @@ void Registration::testHomeserver()
}
m_connection = new NeoChatConnection(this);
m_connection->resolveServer("@user:%1"_ls.arg(m_homeserver));
m_connection->resolveServer("@user:%1"_L1.arg(m_homeserver));
connect(
m_connection.data(),
&Connection::loginFlowsChanged,
@@ -179,7 +179,7 @@ void Registration::testHomeserver()
if (m_testServerJob) {
delete m_testServerJob;
}
m_testServerJob = m_connection->callApi<NeoChatRegisterJob>("user"_ls, std::nullopt, "user"_ls, QString(), QString(), QString(), false);
m_testServerJob = m_connection->callApi<NeoChatRegisterJob>("user"_L1, std::nullopt, "user"_L1, QString(), QString(), QString(), false);
connect(m_testServerJob.data(), &BaseJob::finished, this, [this]() {
if (m_testServerJob->error() == BaseJob::StatusCode::ContentAccessError) {
@@ -255,19 +255,19 @@ NeoChatRegisterJob::NeoChatRegisterJob(const QString &kind,
const QString &deviceId,
const QString &initialDeviceDisplayName,
std::optional<bool> inhibitLogin)
: BaseJob(HttpVerb::Post, "RegisterJob"_ls, QByteArrayLiteral("/_matrix/client/r0/register"), false)
: BaseJob(HttpVerb::Post, "RegisterJob"_L1, QByteArrayLiteral("/_matrix/client/r0/register"), false)
{
QJsonObject _data;
if (auth) {
addParam<>(_data, "auth"_ls, auth);
addParam<>(_data, "auth"_L1, auth);
}
addParam<>(_data, "username"_ls, username);
addParam<IfNotEmpty>(_data, "password"_ls, password);
addParam<IfNotEmpty>(_data, "device_id"_ls, deviceId);
addParam<IfNotEmpty>(_data, "initial_device_display_name"_ls, initialDeviceDisplayName);
addParam<IfNotEmpty>(_data, "inhibit_login"_ls, inhibitLogin);
addParam<IfNotEmpty>(_data, "kind"_ls, kind);
addParam<IfNotEmpty>(_data, "refresh_token"_ls, false);
addParam<>(_data, "username"_L1, username);
addParam<IfNotEmpty>(_data, "password"_L1, password);
addParam<IfNotEmpty>(_data, "device_id"_L1, deviceId);
addParam<IfNotEmpty>(_data, "initial_device_display_name"_L1, initialDeviceDisplayName);
addParam<IfNotEmpty>(_data, "inhibit_login"_L1, inhibitLogin);
addParam<IfNotEmpty>(_data, "kind"_L1, kind);
addParam<IfNotEmpty>(_data, "refresh_token"_L1, false);
setRequestData(_data);
}
@@ -339,7 +339,7 @@ void Registration::registerEmail()
auto job = m_connection->callApi<RequestTokenToRegisterEmailJob>(data);
connect(job, &BaseJob::finished, this, [this, job]() {
m_sid = job->jsonData()["sid"_ls].toString();
m_sid = job->jsonData()["sid"_L1].toString();
});
}

View File

@@ -16,6 +16,8 @@
#include <Quotient/jobs/basejob.h>
#include <Quotient/util.h>
using namespace Qt::StringLiterals;
namespace Quotient
{
class CheckUsernameAvailabilityJob;
@@ -26,7 +28,7 @@ class NeoChatConnection;
class NeoChatRegisterJob : public Quotient::BaseJob
{
public:
explicit NeoChatRegisterJob(const QString &kind = QStringLiteral("user"),
explicit NeoChatRegisterJob(const QString &kind = u"user"_s,
const std::optional<QJsonObject> &auth = {},
const QString &username = {},
const QString &password = {},
@@ -36,22 +38,22 @@ public:
QString userId() const
{
return loadFromJson<QString>(QStringLiteral("user_id"));
return loadFromJson<QString>(u"user_id"_s);
}
QString accessToken() const
{
return loadFromJson<QString>(QStringLiteral("access_token"));
return loadFromJson<QString>(u"access_token"_s);
}
QString homeServer() const
{
return loadFromJson<QString>(QStringLiteral("home_server"));
return loadFromJson<QString>(u"home_server"_s);
}
QString deviceId() const
{
return loadFromJson<QString>(QStringLiteral("device_id"));
return loadFromJson<QString>(u"device_id"_s);
}
};

View File

@@ -50,9 +50,9 @@ RoomManager::RoomManager(QObject *parent)
}
#endif
m_lastRoomConfig = m_config->group(QStringLiteral("LastOpenRoom"));
m_lastSpaceConfig = m_config->group(QStringLiteral("LastOpenSpace"));
m_directChatsConfig = m_config->group(QStringLiteral("DirectChatsActive"));
m_lastRoomConfig = m_config->group(u"LastOpenRoom"_s);
m_lastSpaceConfig = m_config->group(u"LastOpenSpace"_s);
m_directChatsConfig = m_config->group(u"DirectChatsActive"_s);
connect(this, &RoomManager::currentRoomChanged, this, [this]() {
m_timelineModel->setRoom(m_currentRoom);
@@ -146,7 +146,7 @@ void RoomManager::resolveResource(Uri uri, const QString &action)
return;
}
if (uri.type() == Uri::NonMatrix && action == "qr"_ls) {
if (uri.type() == Uri::NonMatrix && action == "qr"_L1) {
Q_EMIT externalUrl(uri.toUrl());
return;
}
@@ -155,7 +155,7 @@ void RoomManager::resolveResource(Uri uri, const QString &action)
if (!m_connection) {
return;
}
if (!action.isEmpty() && (uri.type() != Uri::UserId || action != "join"_ls)) {
if (!action.isEmpty() && (uri.type() != Uri::UserId || action != "join"_L1)) {
uri.setAction(action);
}
// TODO we should allow the user to select a connection.
@@ -163,7 +163,7 @@ void RoomManager::resolveResource(Uri uri, const QString &action)
const auto result = visitResource(m_connection, uri);
if (result == Quotient::CouldNotResolve) {
if ((uri.type() == Uri::RoomAlias || uri.type() == Uri::RoomId) && action != "no_join"_ls) {
if ((uri.type() == Uri::RoomAlias || uri.type() == Uri::RoomId) && action != "no_join"_L1) {
Q_EMIT askJoinRoom(uri.primaryId());
}
}
@@ -199,12 +199,12 @@ void RoomManager::viewEventMenu(const QString &eventId, NeoChatRoom *room, Neoch
{
const auto &event = **room->findInTimeline(eventId);
if (EventHandler::mediaInfo(room, &event).contains("mimeType"_ls)) {
if (EventHandler::mediaInfo(room, &event).contains("mimeType"_L1)) {
Q_EMIT showFileMenu(eventId,
sender,
MessageComponentType::typeForEvent(event),
EventHandler::plainBody(room, &event),
EventHandler::mediaInfo(room, &event)["mimeType"_ls].toString(),
EventHandler::mediaInfo(room, &event)["mimeType"_L1].toString(),
room->fileTransferInfo(eventId));
return;
}
@@ -271,12 +271,12 @@ void RoomManager::openRoomForActiveConnection()
UriResolveResult RoomManager::visitUser(User *user, const QString &action)
{
if (action == "mention"_ls || action == "qr"_ls || action.isEmpty()) {
if (action == "mention"_L1 || action == "qr"_L1 || action.isEmpty()) {
user->load();
Q_EMIT showUserDetail(user, action == "qr"_ls ? nullptr : currentRoom());
} else if (action == "_interactive"_ls) {
Q_EMIT showUserDetail(user, action == "qr"_L1 ? nullptr : currentRoom());
} else if (action == "_interactive"_L1) {
user->requestDirectChat();
} else if (action == "chat"_ls) {
} else if (action == "chat"_L1) {
user->load();
Q_EMIT askDirectChatConfirmation(user);
} else {
@@ -445,7 +445,7 @@ void RoomManager::setCurrentSpace(const QString &spaceId, bool setRoom)
// This need to happen before the signal so TreeView.expandRecursively() can work nicely.
m_sortFilterRoomTreeModel->setActiveSpaceId(m_currentSpaceId);
m_sortFilterRoomTreeModel->setMode(m_currentSpaceId == QLatin1String("DM") ? SortFilterRoomTreeModel::DirectChats : SortFilterRoomTreeModel::Rooms);
m_sortFilterRoomTreeModel->setMode(m_currentSpaceId == u"DM"_s ? SortFilterRoomTreeModel::DirectChats : SortFilterRoomTreeModel::Rooms);
Q_EMIT currentSpaceChanged();
if (m_connection) {
@@ -458,7 +458,7 @@ void RoomManager::setCurrentSpace(const QString &spaceId, bool setRoom)
if (!m_isMobile) {
if (spaceId.length() > 3) {
resolveResource(spaceId, "no_join"_ls);
resolveResource(spaceId, "no_join"_L1);
} else {
visitRoom({}, {});
}
@@ -492,8 +492,8 @@ void RoomManager::setCurrentRoom(const QString &roomId)
return;
}
if (m_currentRoom->isDirectChat()) {
if (m_currentSpaceId != "DM"_ls) {
setCurrentSpace("DM"_ls, false);
if (m_currentSpaceId != "DM"_L1) {
setCurrentSpace("DM"_L1, false);
}
return;
}

View File

@@ -58,13 +58,13 @@ RemoteMatches Runner::Match(const QString &searchTerm)
const QString name = m_model->data(m_model->index(i, 0), RoomListModel::DisplayNameRole).toString();
match.iconName = QStringLiteral("org.kde.neochat");
match.iconName = u"org.kde.neochat"_s;
match.id = m_model->data(m_model->index(i, 0), RoomListModel::RoomIdRole).toString();
match.text = name;
match.relevance = 1;
const RemoteImage remoteImage = serializeImage(m_model->data(m_model->index(i, 0), RoomListModel::AvatarImageRole).value<QImage>());
match.properties.insert(QStringLiteral("icon-data"), QVariant::fromValue(remoteImage));
match.properties.insert(QStringLiteral("subtext"), m_model->data(m_model->index(i, 0), RoomListModel::TopicRole).toString());
match.properties.insert(u"icon-data"_s, QVariant::fromValue(remoteImage));
match.properties.insert(u"subtext"_s, m_model->data(m_model->index(i, 0), RoomListModel::TopicRole).toString());
if (name.compare(searchTerm, Qt::CaseInsensitive) == 0) {
match.type = ExactMatch;

View File

@@ -62,7 +62,7 @@ void SpaceHierarchyCache::populateSpaceHierarchy(const QString &spaceId)
m_nextBatchTokens[spaceId] = QString();
auto job = m_connection->callApi<GetSpaceHierarchyJob>(spaceId, std::nullopt, std::nullopt, std::nullopt, *m_nextBatchTokens[spaceId]);
auto group = KConfigGroup(KSharedConfig::openStateConfig("SpaceHierarchy"_ls), "Cache"_ls);
auto group = KConfigGroup(KSharedConfig::openStateConfig("SpaceHierarchy"_L1), "Cache"_L1);
m_spaceHierarchy.insert(spaceId, group.readEntry(spaceId, QStringList()));
connect(job, &BaseJob::success, this, [this, job, spaceId]() {
@@ -83,7 +83,7 @@ void SpaceHierarchyCache::addBatch(const QString &spaceId, Quotient::GetSpaceHie
}
m_spaceHierarchy.insert(spaceId, roomList);
Q_EMIT spaceHierarchyChanged();
auto group = KConfigGroup(KSharedConfig::openStateConfig("SpaceHierarchy"_ls), "Cache"_ls);
auto group = KConfigGroup(KSharedConfig::openStateConfig("SpaceHierarchy"_L1), "Cache"_L1);
group.writeEntry(spaceId, roomList);
group.sync();
@@ -208,34 +208,34 @@ void SpaceHierarchyCache::setConnection(NeoChatConnection *connection)
QString SpaceHierarchyCache::recommendedSpaceId() const
{
return KConfigGroup(KSharedConfig::openConfig(), QStringLiteral("RecommendedSpace")).readEntry(QStringLiteral("Id"), {});
return KConfigGroup(KSharedConfig::openConfig(), u"RecommendedSpace"_s).readEntry(u"Id"_s, {});
}
QString SpaceHierarchyCache::recommendedSpaceAvatar() const
{
return KConfigGroup(KSharedConfig::openConfig(), QStringLiteral("RecommendedSpace")).readEntry(QStringLiteral("Avatar"), {});
return KConfigGroup(KSharedConfig::openConfig(), u"RecommendedSpace"_s).readEntry(u"Avatar"_s, {});
}
QString SpaceHierarchyCache::recommendedSpaceDisplayName() const
{
return KConfigGroup(KSharedConfig::openConfig(), QStringLiteral("RecommendedSpace")).readEntry(QStringLiteral("DisplayName"), {});
return KConfigGroup(KSharedConfig::openConfig(), u"RecommendedSpace"_s).readEntry(u"DisplayName"_s, {});
}
QString SpaceHierarchyCache::recommendedSpaceDescription() const
{
return KConfigGroup(KSharedConfig::openConfig(), QStringLiteral("RecommendedSpace")).readEntry(QStringLiteral("Description"), {});
return KConfigGroup(KSharedConfig::openConfig(), u"RecommendedSpace"_s).readEntry(u"Description"_s, {});
}
bool SpaceHierarchyCache::recommendedSpaceHidden() const
{
KConfigGroup group(KSharedConfig::openStateConfig(), QStringLiteral("RecommendedSpace"));
return group.readEntry<bool>(QStringLiteral("hidden"), false);
KConfigGroup group(KSharedConfig::openStateConfig(), u"RecommendedSpace"_s);
return group.readEntry<bool>(u"hidden"_s, false);
}
void SpaceHierarchyCache::setRecommendedSpaceHidden(bool hidden)
{
KConfigGroup group(KSharedConfig::openStateConfig(), QStringLiteral("RecommendedSpace"));
group.writeEntry(QStringLiteral("hidden"), hidden);
KConfigGroup group(KSharedConfig::openStateConfig(), u"RecommendedSpace"_s);
group.writeEntry(u"hidden"_s, hidden);
group.sync();
Q_EMIT recommendedSpaceHiddenChanged();
}

View File

@@ -24,35 +24,19 @@
using namespace Qt::StringLiterals;
static const QStringList allowedTags = {
QStringLiteral("font"), QStringLiteral("del"), QStringLiteral("h1"), QStringLiteral("h2"), QStringLiteral("h3"), QStringLiteral("h4"),
QStringLiteral("h5"), QStringLiteral("h6"), QStringLiteral("blockquote"), QStringLiteral("p"), QStringLiteral("a"), QStringLiteral("ul"),
QStringLiteral("ol"), QStringLiteral("sup"), QStringLiteral("sub"), QStringLiteral("li"), QStringLiteral("b"), QStringLiteral("i"),
QStringLiteral("u"), QStringLiteral("strong"), QStringLiteral("em"), QStringLiteral("strike"), QStringLiteral("code"), QStringLiteral("hr"),
QStringLiteral("br"), QStringLiteral("div"), QStringLiteral("table"), QStringLiteral("thead"), QStringLiteral("tbody"), QStringLiteral("tr"),
QStringLiteral("th"), QStringLiteral("td"), QStringLiteral("caption"), QStringLiteral("pre"), QStringLiteral("span"), QStringLiteral("img"),
QStringLiteral("details"), QStringLiteral("summary")};
static const QHash<QString, QStringList> allowedAttributes = {
{QStringLiteral("font"), {QStringLiteral("data-mx-bg-color"), QStringLiteral("data-mx-color"), QStringLiteral("color")}},
{QStringLiteral("span"), {QStringLiteral("data-mx-bg-color"), QStringLiteral("data-mx-color"), QStringLiteral("data-mx-spoiler")}},
{QStringLiteral("a"), {QStringLiteral("name"), QStringLiteral("target"), QStringLiteral("href")}},
{QStringLiteral("img"),
{QStringLiteral("style"), QStringLiteral("width"), QStringLiteral("height"), QStringLiteral("alt"), QStringLiteral("title"), QStringLiteral("src")}},
{QStringLiteral("ol"), {QStringLiteral("start")}},
{QStringLiteral("code"), {QStringLiteral("class")}}};
static const QStringList allowedLinkSchemes = {QStringLiteral("https"),
QStringLiteral("http"),
QStringLiteral("ftp"),
QStringLiteral("mailto"),
QStringLiteral("magnet")};
static const QStringList blockTags = {QStringLiteral("blockquote"),
QStringLiteral("p"),
QStringLiteral("ul"),
QStringLiteral("ol"),
QStringLiteral("div"),
QStringLiteral("table"),
QStringLiteral("pre")};
u"font"_s, u"del"_s, u"h1"_s, u"h2"_s, u"h3"_s, u"h4"_s, u"h5"_s, u"h6"_s, u"blockquote"_s, u"p"_s, u"a"_s, u"ul"_s, u"ol"_s,
u"sup"_s, u"sub"_s, u"li"_s, u"b"_s, u"i"_s, u"u"_s, u"strong"_s, u"em"_s, u"strike"_s, u"code"_s, u"hr"_s, u"br"_s, u"div"_s,
u"table"_s, u"thead"_s, u"tbody"_s, u"tr"_s, u"th"_s, u"td"_s, u"caption"_s, u"pre"_s, u"span"_s, u"img"_s, u"details"_s, u"summary"_s};
static const QHash<QString, QStringList> allowedAttributes = {{u"font"_s, {u"data-mx-bg-color"_s, u"data-mx-color"_s, u"color"_s}},
{u"span"_s, {u"data-mx-bg-color"_s, u"data-mx-color"_s, u"data-mx-spoiler"_s}},
{u"a"_s, {u"name"_s, u"target"_s, u"href"_s}},
{u"img"_s, {u"style"_s, u"width"_s, u"height"_s, u"alt"_s, u"title"_s, u"src"_s}},
{u"ol"_s, {u"start"_s}},
{u"code"_s, {u"class"_s}}};
static const QStringList allowedLinkSchemes = {u"https"_s, u"http"_s, u"ftp"_s, u"mailto"_s, u"magnet"_s};
static const QStringList blockTags = {u"blockquote"_s, u"p"_s, u"ul"_s, u"ol"_s, u"div"_s, u"table"_s, u"pre"_s};
static const QString customEmojiStyle = QStringLiteral("vertical-align:bottom");
static const QString customEmojiStyle = u"vertical-align:bottom"_s;
QString TextHandler::data() const
{
@@ -120,35 +104,34 @@ TextHandler::handleRecieveRichText(Qt::TextFormat inputFormat, const NeoChatRoom
// For plain text, convert links, escape html and convert line brakes.
if (inputFormat == Qt::PlainText) {
m_dataBuffer = escapeHtml(m_dataBuffer);
m_dataBuffer.replace(u'\n', QStringLiteral("<br>"));
m_dataBuffer.replace(u'\n', u"<br>"_s);
}
// Linkify any plain text urls
m_dataBuffer = linkifyUrls(m_dataBuffer);
// Apply user style
m_dataBuffer.replace(TextRegex::userPill, QStringLiteral(R"(<b>\1</b>)"));
m_dataBuffer.replace(TextRegex::userPill, uR"(<b>\1</b>)"_s);
// Make all media URLs resolvable.
if (room && event) {
QRegularExpressionMatchIterator i = TextRegex::mxcImage.globalMatch(m_dataBuffer);
while (i.hasNext()) {
const QRegularExpressionMatch match = i.next();
const QUrl mediaUrl = room->makeMediaUrl(event->id(), QUrl(QStringLiteral("mxc://") + match.captured(2) + u'/' + match.captured(3)));
const QUrl mediaUrl = room->makeMediaUrl(event->id(), QUrl(u"mxc://"_s + match.captured(2) + u'/' + match.captured(3)));
QStringList extraAttributes = match.captured(4).split(QChar::Space);
const bool isEmoticon = match.captured(1).contains(QStringLiteral("data-mx-emoticon"));
const bool isEmoticon = match.captured(1).contains(u"data-mx-emoticon"_s);
// If the image does not have an explicit width, but has a vertical-align it's most likely an emoticon.
// We must do some pre-processing for it to show up nicely in and around text.
if (isEmoticon) {
// Align it properly
extraAttributes.append(QStringLiteral("style=\"%1\"").arg(customEmojiStyle));
extraAttributes.append(u"style=\"%1\""_s.arg(customEmojiStyle));
}
m_dataBuffer.replace(match.captured(0),
QStringLiteral("<img ") + match.captured(1) + QStringLiteral("src=\"") + mediaUrl.toString() + u'"'
+ extraAttributes.join(QChar::Space) + u'>');
u"<img "_s + match.captured(1) + u"src=\""_s + mediaUrl.toString() + u'"' + extraAttributes.join(QChar::Space) + u'>');
}
}
@@ -164,7 +147,7 @@ TextHandler::handleRecieveRichText(Qt::TextFormat inputFormat, const NeoChatRoom
} else if (m_nextTokenType == Type::Tag) {
if (!isAllowedTag(getTagType(m_nextToken))) {
nextTokenBuffer = QString();
} else if ((getTagType(m_nextToken) == QStringLiteral("br") && stripNewlines)) {
} else if ((getTagType(m_nextToken) == u"br"_s && stripNewlines)) {
nextTokenBuffer = u' ';
}
nextTokenBuffer = cleanAttributes(getTagType(m_nextToken), nextTokenBuffer);
@@ -176,12 +159,11 @@ TextHandler::handleRecieveRichText(Qt::TextFormat inputFormat, const NeoChatRoom
}
if (isEdited) {
if (outputString.endsWith(QStringLiteral("</p>"))) {
if (outputString.endsWith(u"</p>"_s)) {
outputString.insert(outputString.length() - 4, editString());
} else if (outputString.endsWith(QStringLiteral("</pre>")) || outputString.endsWith(QStringLiteral("</blockquote>"))
|| outputString.endsWith(QStringLiteral("</table>")) || outputString.endsWith(QStringLiteral("</ol>"))
|| outputString.endsWith(QStringLiteral("</ul>"))) {
outputString.append(QStringLiteral("<p>%1</p>").arg(editString()));
} else if (outputString.endsWith(u"</pre>"_s) || outputString.endsWith(u"</blockquote>"_s) || outputString.endsWith(u"</table>"_s)
|| outputString.endsWith(u"</ol>"_s) || outputString.endsWith(u"</ul>"_s)) {
outputString.append(u"<p>%1</p>"_s.arg(editString()));
} else {
outputString.append(editString());
}
@@ -192,7 +174,7 @@ TextHandler::handleRecieveRichText(Qt::TextFormat inputFormat, const NeoChatRoom
* Note: <s> is still not a valid tag for the message from the server. We
* convert as that is what is needed for Qt::RichText.
*/
outputString.replace(TextRegex::strikethrough, QStringLiteral("<s>\\1</s>"));
outputString.replace(TextRegex::strikethrough, u"<s>\\1</s>"_s);
if (outputString.count("<p>"_L1) == 1 && outputString.count("</p>"_L1) == 1 && outputString.startsWith("<p>"_L1) && outputString.endsWith("</p>"_L1)) {
outputString.remove("<p>"_L1);
@@ -223,15 +205,15 @@ QString TextHandler::handleRecievePlainText(Qt::TextFormat inputFormat, const bo
m_dataBuffer = markdownToHTML(m_dataBuffer);
// This is how \n is converted and for plain text we need it to just be <br>
// to prevent extra newlines being inserted.
m_dataBuffer.replace(QStringLiteral("<br />\n"), QStringLiteral("<br>"));
m_dataBuffer.replace(u"<br />\n"_s, u"<br>"_s);
if (stripNewlines) {
m_dataBuffer.replace(QStringLiteral("<br>\n"), QStringLiteral(" "));
m_dataBuffer.replace(QStringLiteral("<br>"), QStringLiteral(" "));
m_dataBuffer.replace(QStringLiteral("<br />\n"), QStringLiteral(" "));
m_dataBuffer.replace(QStringLiteral("<br />"), QStringLiteral(" "));
m_dataBuffer.replace(u'\n', QStringLiteral(" "));
m_dataBuffer.replace(u'\u2028', QStringLiteral(" "));
m_dataBuffer.replace(u"<br>\n"_s, u" "_s);
m_dataBuffer.replace(u"<br>"_s, u" "_s);
m_dataBuffer.replace(u"<br />\n"_s, u" "_s);
m_dataBuffer.replace(u"<br />"_s, u" "_s);
m_dataBuffer.replace(u'\n', u" "_s);
m_dataBuffer.replace(u'\u2028', u" "_s);
}
// Strip all tags/attributes except code blocks which will be escaped.
@@ -244,7 +226,7 @@ QString TextHandler::handleRecievePlainText(Qt::TextFormat inputFormat, const bo
if (m_nextTokenType == Type::TextCode) {
nextTokenBuffer = unescapeHtml(nextTokenBuffer);
} else if (m_nextTokenType == Type::Tag) {
if (getTagType(m_nextToken) == QStringLiteral("br") && !stripNewlines) {
if (getTagType(m_nextToken) == u"br"_s && !stripNewlines) {
nextTokenBuffer = u'\n';
} else {
nextTokenBuffer = QString();
@@ -271,7 +253,7 @@ void TextHandler::next()
searchStr = u'>';
} else if (m_nextTokenType == Type::TextCode) {
// Anything between code tags is assumed to be plain text
searchStr = QStringLiteral("</code>");
searchStr = u"</code>"_s;
} else {
searchStr = u'<';
}
@@ -291,8 +273,8 @@ TextHandler::Type TextHandler::nextTokenType(const QString &string, int currentP
// This is to stop the function accessing an index outside the length of
// string during the final loop.
return Type::End;
} else if (currentTokenType == Type::Tag && getTagType(currentToken) == QStringLiteral("code") && !isCloseTag(currentToken)
&& string.indexOf(QStringLiteral("</code>"), currentPos) != currentPos) {
} else if (currentTokenType == Type::Tag && getTagType(currentToken) == u"code"_s && !isCloseTag(currentToken)
&& string.indexOf(u"</code>"_s, currentPos) != currentPos) {
return Type::TextCode;
} else if (string[currentPos] == u'<' && string[currentPos + 1] != u' ') {
return Type::Tag;
@@ -335,7 +317,7 @@ int TextHandler::nextBlockPos(const QString &string)
return string.size();
}
const auto closeTag = QStringLiteral("</%1>").arg(tagType);
const auto closeTag = u"</%1>"_s.arg(tagType);
int closeTagPos = string.indexOf(closeTag);
// If the close tag can't be found assume malformed html and process as single block.
if (closeTagPos == -1) {
@@ -362,7 +344,7 @@ MessageComponent TextHandler::nextBlock(const QString &string,
const auto messageComponentType = MessageComponentType::typeForTag(tagType);
QVariantMap attributes;
if (messageComponentType == MessageComponentType::Code) {
attributes = getAttributes(QStringLiteral("code"), string.mid(tagEndPos + 1, string.indexOf(u'>', tagEndPos + 1) - tagEndPos));
attributes = getAttributes(u"code"_s, string.mid(tagEndPos + 1, string.indexOf(u'>', tagEndPos + 1) - tagEndPos));
}
auto content = stripBlockTags(string.first(nextBlockPos), tagType);
@@ -379,30 +361,29 @@ MessageComponent TextHandler::nextBlock(const QString &string,
QString TextHandler::stripBlockTags(QString string, const QString &tagType) const
{
if (blockTags.contains(tagType) && tagType != QStringLiteral("ol") && tagType != QStringLiteral("ul") && tagType != QStringLiteral("table")
&& string.startsWith(QLatin1String("<%1").arg(tagType))) {
string.remove(0, string.indexOf(u'>') + 1).remove(string.indexOf(QLatin1String("</%1>").arg(tagType)), string.size());
if (blockTags.contains(tagType) && tagType != u"ol"_s && tagType != u"ul"_s && tagType != u"table"_s && string.startsWith(u"<%1"_s.arg(tagType))) {
string.remove(0, string.indexOf(u'>') + 1).remove(string.indexOf(u"</%1>"_s.arg(tagType)), string.size());
}
if (string.startsWith(QStringLiteral("\n"))) {
if (string.startsWith(u"\n"_s)) {
string.remove(0, 1);
}
if (string.endsWith(QStringLiteral("\n"))) {
if (string.endsWith(u"\n"_s)) {
string.remove(string.size() - 1, string.size());
}
if (tagType == QStringLiteral("pre")) {
if (string.startsWith(QStringLiteral("<code"))) {
if (tagType == u"pre"_s) {
if (string.startsWith(u"<code"_s)) {
string.remove(0, string.indexOf(u'>') + 1);
string.remove(string.indexOf(QLatin1String("</code>")), string.size());
string.remove(string.indexOf(u"</code>"_s), string.size());
}
if (string.endsWith(QStringLiteral("\n"))) {
if (string.endsWith(u"\n"_s)) {
string.remove(string.size() - 1, string.size());
}
}
if (tagType == QStringLiteral("blockquote")) {
if (string.startsWith(QStringLiteral("<p>"))) {
if (tagType == u"blockquote"_s) {
if (string.startsWith(u"<p>"_s)) {
string.remove(0, string.indexOf(u'>') + 1);
string.remove(string.indexOf(QLatin1String("</p>")), string.size());
string.remove(string.indexOf(u"</p>"_s), string.size());
}
// This is not a normal quotation mark but U+201C
if (!string.startsWith(u'')) {
@@ -447,7 +428,7 @@ QString TextHandler::getAttributeType(const QString &string)
QString TextHandler::getAttributeData(const QString &string, bool stripQuotes)
{
if (!string.contains(u'=')) {
return QStringLiteral();
return QString();
}
const int equalsPos = string.indexOf(u'=');
auto data = string.right(string.length() - equalsPos - 1);
@@ -472,7 +453,7 @@ bool TextHandler::isAllowedLink(const QString &link, bool isImg)
const QUrl linkUrl = QUrl(link);
if (isImg) {
return !linkUrl.isRelative() && linkUrl.scheme() == QStringLiteral("mxc");
return !linkUrl.isRelative() && linkUrl.scheme() == u"mxc"_s;
} else {
return !linkUrl.isRelative() && allowedLinkSchemes.contains(linkUrl.scheme());
}
@@ -497,38 +478,38 @@ QString TextHandler::cleanAttributes(const QString &tag, const QString &tagStrin
if (isAllowedAttribute(tag, getAttributeType(nextAttribute))) {
QString style;
if (tag == QStringLiteral("img") && getAttributeType(nextAttribute) == QStringLiteral("src")) {
if (tag == u"img"_s && getAttributeType(nextAttribute) == u"src"_s) {
QString attributeData = TextRegex::attributeData.match(getAttributeData(nextAttribute)).captured(1);
if (isAllowedLink(attributeData, true)) {
outputString.append(u' ' + nextAttribute);
}
} else if (tag == u'a' && getAttributeType(nextAttribute) == QStringLiteral("href")) {
} else if (tag == u'a' && getAttributeType(nextAttribute) == u"href"_s) {
QString attributeData = TextRegex::attributeData.match(getAttributeData(nextAttribute)).captured(1);
if (isAllowedLink(attributeData)) {
outputString.append(u' ' + nextAttribute);
}
} else if (tag == QStringLiteral("code") && getAttributeType(nextAttribute) == QStringLiteral("class")) {
if (getAttributeData(nextAttribute).remove(u'"').startsWith(QStringLiteral("language-"))) {
} else if (tag == u"code"_s && getAttributeType(nextAttribute) == u"class"_s) {
if (getAttributeData(nextAttribute).remove(u'"').startsWith(u"language-"_s)) {
outputString.append(u' ' + nextAttribute);
}
} else if (tag == QStringLiteral("img") && getAttributeType(nextAttribute) == QStringLiteral("style")) {
} else if (tag == u"img"_s && getAttributeType(nextAttribute) == u"style"_s) {
const QString attributeData = TextRegex::attributeData.match(getAttributeData(nextAttribute)).captured(1);
// Ignore every other style attribute except for our own, which we use to align custom emoticons
if (attributeData == customEmojiStyle) {
outputString.append(u' ' + nextAttribute);
}
} else if (getAttributeType(nextAttribute) == QStringLiteral("data-mx-color")) {
} else if (getAttributeType(nextAttribute) == u"data-mx-color"_s) {
const QString attributeData = TextRegex::attributeData.match(getAttributeData(nextAttribute)).captured(1);
style.append(u"color: " + attributeData + u';');
} else if (getAttributeType(nextAttribute) == QStringLiteral("data-mx-bg-color")) {
style.append(u"color: "_s + attributeData + u';');
} else if (getAttributeType(nextAttribute) == u"data-mx-bg-color"_s) {
const QString attributeData = TextRegex::attributeData.match(getAttributeData(nextAttribute)).captured(1);
style.append(u"background-color: " + attributeData + u';');
style.append(u"background-color: "_s + attributeData + u';');
} else {
outputString.append(u' ' + nextAttribute);
}
if (!style.isEmpty()) {
outputString.append(u" style=\"" + style + u'"');
outputString.append(u" style=\""_s + style + u'"');
}
}
nextAttributeIndex = nextSpaceIndex + 1;
@@ -559,18 +540,18 @@ QVariantMap TextHandler::getAttributes(const QString &tag, const QString &tagStr
nextAttribute = tagString.mid(nextAttributeIndex, nextSpaceIndex - nextAttributeIndex);
if (isAllowedAttribute(tag, getAttributeType(nextAttribute))) {
if (tag == QStringLiteral("img") && getAttributeType(nextAttribute) == QStringLiteral("src")) {
if (tag == u"img"_s && getAttributeType(nextAttribute) == u"src"_s) {
QString attributeData = TextRegex::attributeData.match(getAttributeData(nextAttribute)).captured(1);
if (isAllowedLink(attributeData, true)) {
attributes[getAttributeType(nextAttribute)] = getAttributeData(nextAttribute, true);
}
} else if (tag == u'a' && getAttributeType(nextAttribute) == QStringLiteral("href")) {
} else if (tag == u'a' && getAttributeType(nextAttribute) == u"href"_s) {
QString attributeData = TextRegex::attributeData.match(getAttributeData(nextAttribute)).captured(1);
if (isAllowedLink(attributeData)) {
attributes[getAttributeType(nextAttribute)] = getAttributeData(nextAttribute, true);
}
} else if (tag == QStringLiteral("code") && getAttributeType(nextAttribute) == QStringLiteral("class")) {
if (getAttributeData(nextAttribute).remove(u'"').startsWith(QStringLiteral("language-"))) {
} else if (tag == u"code"_s && getAttributeType(nextAttribute) == u"class"_s) {
if (getAttributeData(nextAttribute).remove(u'"').startsWith(u"language-"_s)) {
attributes[getAttributeType(nextAttribute)] = convertCodeLanguageString(getAttributeData(nextAttribute, true));
}
} else {
@@ -600,7 +581,7 @@ TextHandler::textComponents(QString string, Qt::TextFormat inputFormat, const Ne
components += nextBlock;
string.remove(0, nextBlockPos);
if (string.startsWith(QStringLiteral("\n"))) {
if (string.startsWith(u"\n"_s)) {
string.remove(0, 1);
}
string = string.trimmed();
@@ -634,7 +615,7 @@ QString TextHandler::markdownToHTML(const QString &markdown)
auto result = QString::fromStdString(html).trimmed();
result.replace(QStringLiteral("<!-- raw HTML omitted -->"), QString());
result.replace(u"<!-- raw HTML omitted -->"_s, QString());
return result;
}
@@ -647,21 +628,21 @@ QString TextHandler::markdownToHTML(const QString &markdown)
*/
QString TextHandler::escapeHtml(QString stringIn)
{
stringIn.replace(u'<', QStringLiteral("&lt;"));
stringIn.replace(u'>', QStringLiteral("&gt;"));
stringIn.replace(u'<', u"&lt;"_s);
stringIn.replace(u'>', u"&gt;"_s);
return stringIn;
}
QString TextHandler::unescapeHtml(QString stringIn)
{
// For those situations where brackets in code block get double escaped
stringIn.replace(QStringLiteral("&amp;lt;"), QStringLiteral("<"));
stringIn.replace(QStringLiteral("&amp;gt;"), QStringLiteral(">"));
stringIn.replace(QStringLiteral("&lt;"), QStringLiteral("<"));
stringIn.replace(QStringLiteral("&gt;"), QStringLiteral(">"));
stringIn.replace(QStringLiteral("&amp;"), QStringLiteral("&"));
stringIn.replace(QStringLiteral("&quot;"), QStringLiteral("\""));
stringIn.replace(QStringLiteral("&#x27;"), QStringLiteral("'"));
stringIn.replace(u"&amp;lt;"_s, u"<"_s);
stringIn.replace(u"&amp;gt;"_s, u">"_s);
stringIn.replace(u"&lt;"_s, u"<"_s);
stringIn.replace(u"&gt;"_s, u">"_s);
stringIn.replace(u"&amp;"_s, u"&"_s);
stringIn.replace(u"&quot;"_s, u"\""_s);
stringIn.replace(u"&#x27;"_s, u"'"_s);
return stringIn;
}
@@ -672,8 +653,8 @@ QString TextHandler::linkifyUrls(QString stringIn)
for (int index = 0; index != -1; index = stringIn.indexOf(TextRegex::mxId, start, &match)) {
int skip = 0;
if (match.captured(0).size() > 0) {
if (stringIn.left(index).count(QStringLiteral("<code>")) == stringIn.left(index).count(QStringLiteral("</code>"))) {
auto replacement = QStringLiteral("<a href=\"https://matrix.to/#/%1\">%1</a>").arg(match.captured(1));
if (stringIn.left(index).count(u"<code>"_s) == stringIn.left(index).count(u"</code>"_s)) {
auto replacement = u"<a href=\"https://matrix.to/#/%1\">%1</a>"_s.arg(match.captured(1));
stringIn = stringIn.replace(index, match.captured(0).size(), replacement);
} else {
skip = match.captured().length();
@@ -687,8 +668,8 @@ QString TextHandler::linkifyUrls(QString stringIn)
for (int index = 0; index != -1; index = stringIn.indexOf(TextRegex::plainUrl, start, &match)) {
int skip = 0;
if (match.captured(0).size() > 0) {
if (stringIn.left(index).count(QStringLiteral("<code>")) == stringIn.left(index).count(QStringLiteral("</code>"))) {
auto replacement = QStringLiteral("<a href=\"%1\">%1</a>").arg(match.captured(1));
if (stringIn.left(index).count(u"<code>"_s) == stringIn.left(index).count(u"</code>"_s)) {
auto replacement = u"<a href=\"%1\">%1</a>"_s.arg(match.captured(1));
stringIn = stringIn.replace(index, match.captured(0).size(), replacement);
skip = replacement.length();
} else {
@@ -703,8 +684,8 @@ QString TextHandler::linkifyUrls(QString stringIn)
for (int index = 0; index != -1; index = stringIn.indexOf(TextRegex::emailAddress, start, &match)) {
int skip = 0;
if (match.captured(0).size() > 0) {
if (stringIn.left(index).count(QStringLiteral("<code>")) == stringIn.left(index).count(QStringLiteral("</code>"))) {
auto replacement = QStringLiteral("<a href=\"mailto:%1\">%1</a>").arg(match.captured(2));
if (stringIn.left(index).count(u"<code>"_s) == stringIn.left(index).count(u"</code>"_s)) {
auto replacement = u"<a href=\"mailto:%1\">%1</a>"_s.arg(match.captured(2));
stringIn = stringIn.replace(index, match.captured(0).size(), replacement);
skip = replacement.length();
} else {
@@ -727,9 +708,9 @@ QString TextHandler::editString() const
if (theme != nullptr) {
editTextColor = theme->disabledTextColor().name();
} else {
editTextColor = QStringLiteral("#000000");
editTextColor = u"#000000"_s;
}
return QStringLiteral(" <span style=\"color:") + editTextColor + QStringLiteral("\">(edited)</span>");
return u" <span style=\"color:"_s + editTextColor + u"\">(edited)</span>"_s;
}
QString TextHandler::emoteString(const NeoChatRoom *room, const Quotient::RoomEvent *event) const
@@ -740,8 +721,8 @@ QString TextHandler::emoteString(const NeoChatRoom *room, const Quotient::RoomEv
auto e = eventCast<const Quotient::RoomMessageEvent>(event);
auto author = room->member(e->senderId());
return QStringLiteral("* <a href=\"https://matrix.to/#/") + e->senderId() + QStringLiteral("\" style=\"color:") + author.color().name()
+ QStringLiteral("\">") + author.htmlSafeDisplayName() + QStringLiteral("</a> ");
return u"* <a href=\"https://matrix.to/#/"_s + e->senderId() + u"\" style=\"color:"_s + author.color().name() + u"\">"_s + author.htmlSafeDisplayName()
+ u"</a> "_s;
}
QString TextHandler::convertCodeLanguageString(const QString &languageString)

View File

@@ -10,6 +10,8 @@
#include "jobs/neochatadd3pidjob.h"
#include "neochatconnection.h"
using namespace Qt::StringLiterals;
ThreePIdAddHelper::ThreePIdAddHelper(QObject *parent)
: QObject(parent)
{
@@ -86,7 +88,7 @@ void ThreePIdAddHelper::initiateNewIdAdd()
if (m_newId.isEmpty()) {
return;
}
if (m_medium == QLatin1String("email")) {
if (m_medium == u"email"_s) {
emailTokenJob();
} else {
msisdnTokenJob();
@@ -121,7 +123,7 @@ void ThreePIdAddHelper::msisdnTokenJob()
void ThreePIdAddHelper::tokenJobFinished(Quotient::BaseJob *job)
{
if (job->status() == Quotient::BaseJob::Success) {
m_newIdSid = job->jsonData()[QLatin1String("sid")].toString();
m_newIdSid = job->jsonData()["sid"_L1].toString();
m_newIdStatus = Verification;
Q_EMIT newIdStatusChanged();
return;
@@ -145,11 +147,11 @@ void ThreePIdAddHelper::finalizeNewIdAdd(const QString &password)
if (static_cast<Quotient::BaseJob::StatusCode>(job->error()) == Quotient::BaseJob::Unauthorised) {
QJsonObject replyData = job->jsonData();
QJsonObject authData;
authData[QLatin1String("session")] = replyData[QLatin1String("session")];
authData[QLatin1String("password")] = password;
authData[QLatin1String("type")] = QLatin1String("m.login.password");
QJsonObject identifier = {{QLatin1String("type"), QLatin1String("m.id.user")}, {QLatin1String("user"), m_connection->userId()}};
authData[QLatin1String("identifier")] = identifier;
authData["session"_L1] = replyData["session"_L1];
authData["password"_L1] = password;
authData["type"_L1] = "m.login.password"_L1;
QJsonObject identifier = {{"type"_L1, "m.id.user"_L1}, {"user"_L1, m_connection->userId()}};
authData["identifier"_L1] = identifier;
const auto innerJob = m_connection->callApi<NeochatAdd3PIdJob>(m_newIdSecret, m_newIdSid, authData);
connect(innerJob, &Quotient::BaseJob::success, this, [this]() {
m_connection->threePIdModel()->refreshModel();
@@ -159,10 +161,10 @@ void ThreePIdAddHelper::finalizeNewIdAdd(const QString &password)
Q_EMIT newIdStatusChanged();
});
connect(innerJob, &Quotient::BaseJob::failure, this, [innerJob, this]() {
if (innerJob->jsonData()[QLatin1String("errcode")] == QLatin1String("M_FORBIDDEN")) {
if (innerJob->jsonData()["errcode"_L1] == "M_FORBIDDEN"_L1) {
m_newIdStatus = AuthFailure;
Q_EMIT newIdStatusChanged();
} else if (innerJob->jsonData()[QLatin1String("errcode")] == QLatin1String("M_THREEPID_AUTH_FAILED")) {
} else if (innerJob->jsonData()["errcode"_L1] == "M_THREEPID_AUTH_FAILED"_L1) {
m_newIdStatus = VerificationFailure;
Q_EMIT newIdStatusChanged();
} else {

View File

@@ -15,6 +15,8 @@
#include "neochatconnection.h"
using namespace Qt::StringLiterals;
ThreePIdBindHelper::ThreePIdBindHelper(QObject *parent)
: QObject(parent)
{
@@ -96,8 +98,8 @@ void ThreePIdBindHelper::initiateNewIdBind()
const auto openIdJob = m_connection->callApi<Quotient::RequestOpenIdTokenJob>(m_connection->userId());
connect(openIdJob, &Quotient::BaseJob::success, this, [this, openIdJob]() {
const auto requestUrl = QUrl(m_connection->identityServer().toString() + QStringLiteral("/_matrix/identity/v2/account/register"));
if (!(requestUrl.scheme() == QStringLiteral("https") || requestUrl.scheme() == QStringLiteral("http"))) {
const auto requestUrl = QUrl(m_connection->identityServer().toString() + u"/_matrix/identity/v2/account/register"_s);
if (!(requestUrl.scheme() == u"https"_s || requestUrl.scheme() == u"http"_s)) {
m_bindStatus = AuthFailure;
Q_EMIT bindStatusChanged();
return;
@@ -107,10 +109,10 @@ void ThreePIdBindHelper::initiateNewIdBind()
auto newRequest = Quotient::NetworkAccessManager::instance()->post(request, QJsonDocument(openIdJob->jsonData()).toJson());
connect(newRequest, &QNetworkReply::finished, this, [this, newRequest]() {
QJsonObject replyJson = parseJson(newRequest->readAll());
m_identityServerToken = replyJson[QLatin1String("token")].toString();
m_identityServerToken = replyJson["token"_L1].toString();
const auto requestUrl = QUrl(m_connection->identityServer().toString() + QStringLiteral("/_matrix/identity/v2/validate/email/requestToken"));
if (!(requestUrl.scheme() == QStringLiteral("https") || requestUrl.scheme() == QStringLiteral("http"))) {
const auto requestUrl = QUrl(m_connection->identityServer().toString() + u"/_matrix/identity/v2/validate/email/requestToken"_s);
if (!(requestUrl.scheme() == u"https"_s || requestUrl.scheme() == u"http"_s)) {
m_bindStatus = AuthFailure;
Q_EMIT bindStatusChanged();
return;
@@ -131,15 +133,15 @@ QByteArray ThreePIdBindHelper::validationRequestData()
{
m_newIdSecret = QString::fromLatin1(QUuid::createUuid().toString().toLatin1().toBase64());
QJsonObject requestData = {
{QLatin1String("client_secret"), m_newIdSecret},
{QLatin1String("send_attempt"), 0},
{"client_secret"_L1, m_newIdSecret},
{"send_attempt"_L1, 0},
};
if (m_medium == QLatin1String("email")) {
requestData[QLatin1String("email")] = m_newId;
if (m_medium == u"email"_s) {
requestData["email"_L1] = m_newId;
} else {
requestData[QLatin1String("phone_number")] = m_newId;
requestData[QLatin1String("country")] = m_newCountryCode;
requestData["phone_number"_L1] = m_newId;
requestData["country"_L1] = m_newCountryCode;
}
return QJsonDocument(requestData).toJson();
@@ -152,7 +154,7 @@ void ThreePIdBindHelper::tokenRequestFinished(QNetworkReply *reply)
}
QJsonObject replyJson = parseJson(reply->readAll());
m_newIdSid = replyJson[QLatin1String("sid")].toString();
m_newIdSid = replyJson["sid"_L1].toString();
if (m_newIdSid.isEmpty()) {
m_bindStatus = Invalid;
@@ -173,11 +175,11 @@ QString ThreePIdBindHelper::bindStatusString() const
switch (m_bindStatus) {
case Verification:
return i18n("%1. Please follow the instructions there and then click the button above",
m_medium == QStringLiteral("email") ? i18n("We've sent you an email") : i18n("We've sent you a text message"));
m_medium == u"email"_s ? i18n("We've sent you an email") : i18n("We've sent you a text message"));
case Invalid:
return m_medium == QStringLiteral("email") ? i18n("The entered email is not valid") : i18n("The entered phone number is not valid");
return m_medium == u"email"_s ? i18n("The entered email is not valid") : i18n("The entered phone number is not valid");
case VerificationFailure:
return m_medium == QStringLiteral("email")
return m_medium == u"email"_s
? i18n("The email has not been verified. Please go to the email and follow the instructions there and then click the button above")
: i18n("The phone number has not been verified. Please go to the text message and follow the instructions there and then click the button above");
default:
@@ -194,7 +196,7 @@ void ThreePIdBindHelper::finalizeNewIdBind()
m_connection->threePIdModel()->refreshModel();
});
connect(job, &Quotient::BaseJob::failure, this, [this, job]() {
if (job->jsonData()[QLatin1String("errcode")] == QLatin1String("M_SESSION_NOT_VALIDATED")) {
if (job->jsonData()["errcode"_L1] == "M_SESSION_NOT_VALIDATED"_L1) {
m_bindStatus = VerificationFailure;
Q_EMIT bindStatusChanged();
} else {

View File

@@ -11,10 +11,12 @@
#include "windowcontroller.h"
using namespace Qt::StringLiterals;
TrayIcon::TrayIcon(QObject *parent)
: QSystemTrayIcon(parent)
{
setIcon(QIcon(QStringLiteral(":/icons/org.kde.neochat.tray.svg")));
setIcon(QIcon(u":/icons/org.kde.neochat.tray.svg"_s));
QMenu *menu = new QMenu();
auto viewAction_ = new QAction(i18n("Show"), parent);
@@ -32,7 +34,7 @@ TrayIcon::TrayIcon(QObject *parent)
menu->addSeparator();
auto quitAction = new QAction(i18n("Quit"), parent);
quitAction->setIcon(QIcon::fromTheme(QStringLiteral("application-exit")));
quitAction->setIcon(QIcon::fromTheme(u"application-exit"_s));
connect(quitAction, &QAction::triggered, QCoreApplication::instance(), QCoreApplication::quit);
menu->addAction(quitAction);

View File

@@ -6,11 +6,13 @@
#include "windowcontroller.h"
using namespace Qt::StringLiterals;
TrayIcon::TrayIcon(QObject *parent)
: KStatusNotifierItem(parent)
{
setCategory(KStatusNotifierItem::ItemCategory::Communications);
setIconByName(QStringLiteral("org.kde.neochat.tray"));
setIconByName(u"org.kde.neochat.tray"_s);
connect(&WindowController::instance(), &WindowController::windowChanged, this, [this] {
setAssociatedWindow(WindowController::instance().window());

View File

@@ -11,6 +11,8 @@
#include <Quotient/user.h>
using namespace Qt::StringLiterals;
class QmlUtils : public QObject
{
Q_OBJECT
@@ -60,26 +62,23 @@ bool isEmoji(const QString &text);
namespace TextRegex
{
static const QRegularExpression endTagType{QStringLiteral("[> /]")};
static const QRegularExpression endAttributeType{QStringLiteral("[> ]")};
static const QRegularExpression attributeData{QStringLiteral("['\"](.*?)['\"]")};
static const QRegularExpression removeReply{QStringLiteral("> <.*?>.*?\\n\\n"), QRegularExpression::DotMatchesEverythingOption};
static const QRegularExpression removeRichReply{QStringLiteral("<mx-reply>.*?</mx-reply>"), QRegularExpression::DotMatchesEverythingOption};
static const QRegularExpression codePill{QStringLiteral("<pre><code[^>]*>(.*?)</code></pre>"), QRegularExpression::DotMatchesEverythingOption};
static const QRegularExpression userPill{QStringLiteral("(<a href=\"https://matrix.to/#/@.*?:.*?\">.*?</a>)"), QRegularExpression::DotMatchesEverythingOption};
static const QRegularExpression blockQuote{QStringLiteral("<blockquote>\n?(?:<p>)?(.*?)(?:</p>)?\n?</blockquote>"),
QRegularExpression::DotMatchesEverythingOption};
static const QRegularExpression strikethrough{QStringLiteral("<del>(.*?)</del>"), QRegularExpression::DotMatchesEverythingOption};
static const QRegularExpression mxcImage{QStringLiteral(R"AAA(<img(.*?)src="mxc:\/\/(.*?)\/(.*?)"(.*?)>)AAA")};
static const QRegularExpression endTagType{u"[> /]"_s};
static const QRegularExpression endAttributeType{u"[> ]"_s};
static const QRegularExpression attributeData{u"['\"](.*?)['\"]"_s};
static const QRegularExpression removeReply{u"> <.*?>.*?\\n\\n"_s, QRegularExpression::DotMatchesEverythingOption};
static const QRegularExpression removeRichReply{u"<mx-reply>.*?</mx-reply>"_s, QRegularExpression::DotMatchesEverythingOption};
static const QRegularExpression codePill{u"<pre><code[^>]*>(.*?)</code></pre>"_s, QRegularExpression::DotMatchesEverythingOption};
static const QRegularExpression userPill{u"(<a href=\"https://matrix.to/#/@.*?:.*?\">.*?</a>)"_s, QRegularExpression::DotMatchesEverythingOption};
static const QRegularExpression blockQuote{u"<blockquote>\n?(?:<p>)?(.*?)(?:</p>)?\n?</blockquote>"_s, QRegularExpression::DotMatchesEverythingOption};
static const QRegularExpression strikethrough{u"<del>(.*?)</del>"_s, QRegularExpression::DotMatchesEverythingOption};
static const QRegularExpression mxcImage{uR"AAA(<img(.*?)src="mxc:\/\/(.*?)\/(.*?)"(.*?)>)AAA"_s};
static const QRegularExpression plainUrl(
QStringLiteral(
R"(<a.*?<\/a>(*SKIP)(*F)|\b((www\.(?!\.)(?!(\w|\.|-)+@)|(https?|ftp):(//)?\w|(magnet|matrix):)(&(?![lg]t;)|[^&\s<>'"])+(&(?![lg]t;)|[^?&!,.\s<>'"\]):])))"),
uR"(<a.*?<\/a>(*SKIP)(*F)|\b((www\.(?!\.)(?!(\w|\.|-)+@)|(https?|ftp):(//)?\w|(magnet|matrix):)(&(?![lg]t;)|[^&\s<>'"])+(&(?![lg]t;)|[^?&!,.\s<>'"\]):])))"_s,
QRegularExpression::CaseInsensitiveOption | QRegularExpression::UseUnicodePropertiesOption);
static const QRegularExpression
url(QStringLiteral(R"(\b((www\.(?!\.)(?!(\w|\.|-)+@)|https?:(//)?\w)(&(?![lg]t;)|[^&\s<>'"])+(&(?![lg]t;)|[^&!,.\s<>'"\]):])))"),
QRegularExpression::CaseInsensitiveOption | QRegularExpression::UseUnicodePropertiesOption);
static const QRegularExpression emailAddress(QStringLiteral(R"(<a.*?<\/a>(*SKIP)(*F)|\b(mailto:)?((\w|\.|-)+@(\w|\.|-)+\.\w+\b))"),
static const QRegularExpression url(uR"(\b((www\.(?!\.)(?!(\w|\.|-)+@)|https?:(//)?\w)(&(?![lg]t;)|[^&\s<>'"])+(&(?![lg]t;)|[^&!,.\s<>'"\]):])))"_s,
QRegularExpression::CaseInsensitiveOption | QRegularExpression::UseUnicodePropertiesOption);
static const QRegularExpression emailAddress(uR"(<a.*?<\/a>(*SKIP)(*F)|\b(mailto:)?((\w|\.|-)+@(\w|\.|-)+\.\w+\b))"_s,
QRegularExpression::CaseInsensitiveOption | QRegularExpression::UseUnicodePropertiesOption);
static const QRegularExpression mxId(QStringLiteral(R"((?<=^|[][[:space:](){}`'";])([!#@][-a-z0-9_=#/.]{1,252}:\w(?:\w|\.|-)*\.\w+(?::\d{1,5})?))"),
static const QRegularExpression mxId(uR"((?<=^|[][[:space:](){}`'";])([!#@][-a-z0-9_=#/.]{1,252}:\w(?:\w|\.|-)*\.\w+(?::\d{1,5})?))"_s,
QRegularExpression::CaseInsensitiveOption | QRegularExpression::UseUnicodePropertiesOption);
}