Reduce allocations using QStringLiteral

This commit is contained in:
Nicolas Werner 2021-12-29 04:28:08 +01:00
parent a3c4ebc460
commit d8ead9573b
No known key found for this signature in database
GPG key ID: C8D75E610773F2D9
46 changed files with 539 additions and 539 deletions

View file

@ -22,7 +22,7 @@ namespace AvatarProvider {
void void
resolve(QString avatarUrl, int size, QObject *receiver, AvatarCallback callback) resolve(QString avatarUrl, int size, QObject *receiver, AvatarCallback callback)
{ {
const auto cacheKey = QString("%1_size_%2").arg(avatarUrl).arg(size); const auto cacheKey = QStringLiteral("%1_size_%2").arg(avatarUrl).arg(size);
QPixmap pixmap; QPixmap pixmap;
if (avatarUrl.isEmpty()) { if (avatarUrl.isEmpty()) {

View file

@ -14,7 +14,7 @@ void
BlurhashRunnable::run() BlurhashRunnable::run()
{ {
if (m_requestedSize.width() < 0 || m_requestedSize.height() < 0) { if (m_requestedSize.width() < 0 || m_requestedSize.height() < 0) {
emit error("Blurhash needs size request"); emit error(QStringLiteral("Blurhash needs size request"));
return; return;
} }
if (m_requestedSize.width() == 0 || m_requestedSize.height() == 0) { if (m_requestedSize.width() == 0 || m_requestedSize.height() == 0) {

View file

@ -223,12 +223,12 @@ Cache::setup()
// Previous location of the cache directory // Previous location of the cache directory
auto oldCache = auto oldCache =
QString("%1/%2%3").arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation), QStringLiteral("%1/%2%3").arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation),
QString::fromUtf8(localUserId_.toUtf8().toHex()), QString::fromUtf8(localUserId_.toUtf8().toHex()),
QString::fromUtf8(settings->profile().toUtf8().toHex())); QString::fromUtf8(settings->profile().toUtf8().toHex()));
cacheDirectory_ = cacheDirectory_ =
QString("%1/%2%3").arg(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation), QStringLiteral("%1/%2%3").arg(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation),
QString::fromUtf8(localUserId_.toUtf8().toHex()), QString::fromUtf8(localUserId_.toUtf8().toHex()),
QString::fromUtf8(settings->profile().toUtf8().toHex())); QString::fromUtf8(settings->profile().toUtf8().toHex()));
@ -359,7 +359,7 @@ Cache::loadSecrets(std::vector<std::pair<std::string, bool>> toLoad)
return; return;
} }
if (settings->value("run_without_secure_secrets_service", false).toBool()) { if (settings->value(QStringLiteral("run_without_secure_secrets_service"), false).toBool()) {
for (auto &[name_, internal] : toLoad) { for (auto &[name_, internal] : toLoad) {
auto name = secretName(name_, internal); auto name = secretName(name_, internal);
auto value = settings->value("secrets/" + name).toString(); auto value = settings->value("secrets/" + name).toString();
@ -435,7 +435,7 @@ Cache::storeSecret(const std::string name_, const std::string secret, bool inter
} }
auto settings = UserSettings::instance()->qsettings(); auto settings = UserSettings::instance()->qsettings();
if (settings->value("run_without_secure_secrets_service", false).toBool()) { if (settings->value(QStringLiteral("run_without_secure_secrets_service"), false).toBool()) {
settings->setValue("secrets/" + name, QString::fromStdString(secret)); settings->setValue("secrets/" + name, QString::fromStdString(secret));
// if we emit the signal directly it won't be received // if we emit the signal directly it won't be received
QTimer::singleShot(0, this, [this, name_] { emit secretChanged(name_); }); QTimer::singleShot(0, this, [this, name_] { emit secretChanged(name_); });
@ -482,7 +482,7 @@ Cache::deleteSecret(const std::string name, bool internal)
} }
auto settings = UserSettings::instance()->qsettings(); auto settings = UserSettings::instance()->qsettings();
if (settings->value("run_without_secure_secrets_service", false).toBool()) { if (settings->value(QStringLiteral("run_without_secure_secrets_service"), false).toBool()) {
settings->remove("secrets/" + name_); settings->remove("secrets/" + name_);
// if we emit the signal directly it won't be received // if we emit the signal directly it won't be received
QTimer::singleShot(0, this, [this, name] { emit secretChanged(name); }); QTimer::singleShot(0, this, [this, name] { emit secretChanged(name); });
@ -2442,9 +2442,9 @@ Cache::getRoomName(lmdb::txn &txn, lmdb::dbi &statesdb, lmdb::dbi &membersdb)
if (total == 2) if (total == 2)
return first_member; return first_member;
else if (total > 2) else if (total > 2)
return QString("%1 and %2 others").arg(first_member).arg(total - 1); return tr("%1 and %2 others").arg(first_member).arg(total - 1);
return "Empty Room"; return tr("Empty Room");
} }
mtx::events::state::JoinRule mtx::events::state::JoinRule
@ -2531,7 +2531,7 @@ Cache::getRoomVersion(lmdb::txn &txn, lmdb::dbi &statesdb)
} }
nhlog::db()->warn("m.room.create event is missing room version, assuming version \"1\""); nhlog::db()->warn("m.room.create event is missing room version, assuming version \"1\"");
return QString("1"); return QStringLiteral("1");
} }
bool bool
@ -2619,7 +2619,7 @@ Cache::getInviteRoomName(lmdb::txn &txn, lmdb::dbi &statesdb, lmdb::dbi &members
cursor.close(); cursor.close();
return QString("Empty Room"); return tr("Empty Room");
} }
QString QString
@ -3894,7 +3894,7 @@ Cache::avatarUrl(const QString &room_id, const QString &user_id)
info && !info->avatar_url.empty()) info && !info->avatar_url.empty())
return QString::fromStdString(info->avatar_url); return QString::fromStdString(info->avatar_url);
return ""; return QString();
} }
mtx::presence::PresenceState mtx::presence::PresenceState

View file

@ -50,7 +50,7 @@ ChatPage::ChatPage(QSharedPointer<UserSettings> userSettings, QWidget *parent)
, notificationsManager(this) , notificationsManager(this)
, callManager_(new CallManager(this)) , callManager_(new CallManager(this))
{ {
setObjectName("chatPage"); setObjectName(QStringLiteral("chatPage"));
instance_ = this; instance_ = this;
@ -279,12 +279,12 @@ ChatPage::deleteConfigs()
{ {
auto settings = UserSettings::instance()->qsettings(); auto settings = UserSettings::instance()->qsettings();
if (UserSettings::instance()->profile() != "") { if (UserSettings::instance()->profile() != QLatin1String("")) {
settings->beginGroup("profile"); settings->beginGroup(QStringLiteral("profile"));
settings->beginGroup(UserSettings::instance()->profile()); settings->beginGroup(UserSettings::instance()->profile());
} }
settings->beginGroup("auth"); settings->beginGroup(QStringLiteral("auth"));
settings->remove(""); settings->remove(QLatin1String(""));
settings->endGroup(); // auth settings->endGroup(); // auth
http::client()->shutdown(); http::client()->shutdown();
@ -1227,7 +1227,7 @@ static QString
mxidFromSegments(QStringView sigil, QStringView mxid) mxidFromSegments(QStringView sigil, QStringView mxid)
{ {
if (mxid.isEmpty()) if (mxid.isEmpty())
return ""; return QString();
auto mxid_ = QUrl::fromPercentEncoding(mxid.toUtf8()); auto mxid_ = QUrl::fromPercentEncoding(mxid.toUtf8());
@ -1240,7 +1240,7 @@ mxidFromSegments(QStringView sigil, QStringView mxid)
//} else if (sigil == "group") { //} else if (sigil == "group") {
// return "+" + mxid_; // return "+" + mxid_;
} else { } else {
return ""; return QString();
} }
} }
@ -1251,33 +1251,33 @@ ChatPage::handleMatrixUri(QString uri)
QUrl uri_{uri}; QUrl uri_{uri};
// Convert matrix.to URIs to proper format // Convert matrix.to URIs to proper format
if (uri_.scheme() == "https" && uri_.host() == "matrix.to") { if (uri_.scheme() == QLatin1String("https") && uri_.host() == QLatin1String("matrix.to")) {
QString p = uri_.fragment(QUrl::FullyEncoded); QString p = uri_.fragment(QUrl::FullyEncoded);
if (p.startsWith("/")) if (p.startsWith(QLatin1String("/")))
p.remove(0, 1); p.remove(0, 1);
auto temp = p.split("?"); auto temp = p.split(QStringLiteral("?"));
QString query; QString query;
if (temp.size() >= 2) if (temp.size() >= 2)
query = QUrl::fromPercentEncoding(temp.takeAt(1).toUtf8()); query = QUrl::fromPercentEncoding(temp.takeAt(1).toUtf8());
temp = temp.first().split("/"); temp = temp.first().split(QStringLiteral("/"));
auto identifier = QUrl::fromPercentEncoding(temp.takeFirst().toUtf8()); auto identifier = QUrl::fromPercentEncoding(temp.takeFirst().toUtf8());
QString eventId = QUrl::fromPercentEncoding(temp.join('/').toUtf8()); QString eventId = QUrl::fromPercentEncoding(temp.join('/').toUtf8());
if (!identifier.isEmpty()) { if (!identifier.isEmpty()) {
if (identifier.startsWith("@")) { if (identifier.startsWith(QLatin1String("@"))) {
QByteArray newUri = "matrix:u/" + QUrl::toPercentEncoding(identifier.remove(0, 1)); QByteArray newUri = "matrix:u/" + QUrl::toPercentEncoding(identifier.remove(0, 1));
if (!query.isEmpty()) if (!query.isEmpty())
newUri.append("?" + query.toUtf8()); newUri.append("?" + query.toUtf8());
return handleMatrixUri(QUrl::fromEncoded(newUri)); return handleMatrixUri(QUrl::fromEncoded(newUri));
} else if (identifier.startsWith("#")) { } else if (identifier.startsWith(QLatin1String("#"))) {
QByteArray newUri = "matrix:r/" + QUrl::toPercentEncoding(identifier.remove(0, 1)); QByteArray newUri = "matrix:r/" + QUrl::toPercentEncoding(identifier.remove(0, 1));
if (!eventId.isEmpty()) if (!eventId.isEmpty())
newUri.append("/e/" + QUrl::toPercentEncoding(eventId.remove(0, 1))); newUri.append("/e/" + QUrl::toPercentEncoding(eventId.remove(0, 1)));
if (!query.isEmpty()) if (!query.isEmpty())
newUri.append("?" + query.toUtf8()); newUri.append("?" + query.toUtf8());
return handleMatrixUri(QUrl::fromEncoded(newUri)); return handleMatrixUri(QUrl::fromEncoded(newUri));
} else if (identifier.startsWith("!")) { } else if (identifier.startsWith(QLatin1String("!"))) {
QByteArray newUri = QByteArray newUri =
"matrix:roomid/" + QUrl::toPercentEncoding(identifier.remove(0, 1)); "matrix:roomid/" + QUrl::toPercentEncoding(identifier.remove(0, 1));
if (!eventId.isEmpty()) if (!eventId.isEmpty())
@ -1290,7 +1290,7 @@ ChatPage::handleMatrixUri(QString uri)
} }
// non-matrix URIs are not handled by us, return false // non-matrix URIs are not handled by us, return false
if (uri_.scheme() != "matrix") if (uri_.scheme() != QLatin1String("matrix"))
return false; return false;
auto tempPath = uri_.path(QUrl::ComponentFormattingOption::FullyEncoded); auto tempPath = uri_.path(QUrl::ComponentFormattingOption::FullyEncoded);
@ -1322,10 +1322,10 @@ ChatPage::handleMatrixUri(QString uri)
for (QString item : qAsConst(items)) { for (QString item : qAsConst(items)) {
nhlog::ui()->info("item: {}", item.toStdString()); nhlog::ui()->info("item: {}", item.toStdString());
if (item.startsWith("action=")) { if (item.startsWith(QLatin1String("action="))) {
action = item.remove("action="); action = item.remove(QStringLiteral("action="));
} else if (item.startsWith("via=")) { } else if (item.startsWith(QLatin1String("via="))) {
vias.push_back(QUrl::fromPercentEncoding(item.remove("via=").toUtf8()).toStdString()); vias.push_back(QUrl::fromPercentEncoding(item.remove(QStringLiteral("via=")).toUtf8()).toStdString());
} }
} }
@ -1402,5 +1402,5 @@ ChatPage::currentRoom() const
if (view_manager_->rooms()->currentRoom()) if (view_manager_->rooms()->currentRoom())
return view_manager_->rooms()->currentRoom()->roomId(); return view_manager_->rooms()->currentRoom()->roomId();
else else
return ""; return QString();
} }

View file

@ -17,7 +17,7 @@ CombinedImagePackModel::CombinedImagePackModel(const std::string &roomId,
for (const auto &pack : packs) { for (const auto &pack : packs) {
QString packname = QString packname =
pack.pack.pack ? QString::fromStdString(pack.pack.pack->display_name) : ""; pack.pack.pack ? QString::fromStdString(pack.pack.pack->display_name) : QString();
for (const auto &img : pack.pack.images) { for (const auto &img : pack.pack.images) {
ImageDesc i{}; ImageDesc i{};
@ -56,7 +56,7 @@ CombinedImagePackModel::data(const QModelIndex &index, int role) const
if (hasIndex(index.row(), index.column(), index.parent())) { if (hasIndex(index.row(), index.column(), index.parent())) {
switch (role) { switch (role) {
case CompletionModel::CompletionRole: case CompletionModel::CompletionRole:
return QString("<img data-mx-emoticon height=32 src=\"%1\" alt=\"%2\" title=\"%2\">") return QStringLiteral("<img data-mx-emoticon height=32 src=\"%1\" alt=\"%2\" title=\"%2\">")
.arg(QString::fromStdString(images[index.row()].image.url).toHtmlEscaped(), .arg(QString::fromStdString(images[index.row()].image.url).toHtmlEscaped(),
QString::fromStdString(images[index.row()].image.body)); QString::fromStdString(images[index.row()].image.body));
case Roles::Url: case Roles::Url:

View file

@ -396,7 +396,7 @@ mtx::accessors::formattedBodyWithFallback(const mtx::events::collections::Timeli
if (!formatted.empty()) if (!formatted.empty())
return QString::fromStdString(formatted); return QString::fromStdString(formatted);
else else
return QString::fromStdString(body(event)).toHtmlEscaped().replace("\n", "<br>"); return QString::fromStdString(body(event)).toHtmlEscaped().replace(QLatin1String("\n"), QLatin1String("<br>"));
} }
std::optional<mtx::crypto::EncryptedFile> std::optional<mtx::crypto::EncryptedFile>

View file

@ -26,7 +26,7 @@ getJdenticonInterface()
static bool interfaceExists{true}; static bool interfaceExists{true};
if (interface == nullptr && interfaceExists) { if (interface == nullptr && interfaceExists) {
QPluginLoader pluginLoader("qtjdenticon"); QPluginLoader pluginLoader(QStringLiteral("qtjdenticon"));
QObject *plugin = pluginLoader.instance(); QObject *plugin = pluginLoader.instance();
if (plugin) { if (plugin) {
interface = qobject_cast<JdenticonInterface *>(plugin); interface = qobject_cast<JdenticonInterface *>(plugin);

View file

@ -49,13 +49,13 @@ LoginPage::LoginPage(QWidget *parent)
top_bar_layout_->addStretch(1); top_bar_layout_->addStretch(1);
QIcon icon; QIcon icon;
icon.addFile(":/icons/icons/ui/angle-arrow-left.svg"); icon.addFile(QStringLiteral(":/icons/icons/ui/angle-arrow-left.svg"));
back_button_->setIcon(icon); back_button_->setIcon(icon);
back_button_->setIconSize(QSize(32, 32)); back_button_->setIconSize(QSize(32, 32));
QIcon logo; QIcon logo;
logo.addFile(":/logos/login.png"); logo.addFile(QStringLiteral(":/logos/login.png"));
logo_ = new QLabel(this); logo_ = new QLabel(this);
logo_->setPixmap(logo.pixmap(128)); logo_->setPixmap(logo.pixmap(128));
@ -79,7 +79,7 @@ LoginPage::LoginPage(QWidget *parent)
matrixid_input_ = new TextField(this); matrixid_input_ = new TextField(this);
matrixid_input_->setLabel(tr("Matrix ID")); matrixid_input_->setLabel(tr("Matrix ID"));
matrixid_input_->setRegexp(QRegularExpression("@.+?:.{3,}")); matrixid_input_->setRegexp(QRegularExpression(QStringLiteral("@.+?:.{3,}")));
matrixid_input_->setPlaceholderText(tr("e.g @joe:matrix.org")); matrixid_input_->setPlaceholderText(tr("e.g @joe:matrix.org"));
matrixid_input_->setToolTip( matrixid_input_->setToolTip(
tr("Your login name. A mxid should start with @ followed by the user id. After the user " tr("Your login name. A mxid should start with @ followed by the user id. After the user "
@ -94,7 +94,7 @@ LoginPage::LoginPage(QWidget *parent)
spinner_->hide(); spinner_->hide();
errorIcon_ = new QLabel(this); errorIcon_ = new QLabel(this);
errorIcon_->setPixmap(QPixmap(":/icons/icons/error.png")); errorIcon_->setPixmap(QPixmap(QStringLiteral(":/icons/icons/error.png")));
errorIcon_->hide(); errorIcon_->hide();
matrixidLayout_ = new QHBoxLayout(); matrixidLayout_ = new QHBoxLayout();
@ -215,7 +215,7 @@ LoginPage::showError(QLabel *label, const QString &msg)
void void
LoginPage::onMatrixIdEntered() LoginPage::onMatrixIdEntered()
{ {
error_label_->setText(""); error_label_->setText(QLatin1String(""));
User user; User user;
@ -225,7 +225,7 @@ LoginPage::onMatrixIdEntered()
tr("You have entered an invalid Matrix ID e.g @joe:matrix.org")); tr("You have entered an invalid Matrix ID e.g @joe:matrix.org"));
return; return;
} else { } else {
error_matrixid_label_->setText(""); error_matrixid_label_->setText(QLatin1String(""));
error_matrixid_label_->hide(); error_matrixid_label_->hide();
} }
@ -334,7 +334,7 @@ LoginPage::checkHomeserverVersion()
void void
LoginPage::onServerAddressEntered() LoginPage::onServerAddressEntered()
{ {
error_label_->setText(""); error_label_->setText(QLatin1String(""));
http::client()->verify_certificates(!UserSettings::instance()->disableCertificateValidation()); http::client()->verify_certificates(!UserSettings::instance()->disableCertificateValidation());
http::client()->set_server(serverInput_->text().toStdString()); http::client()->set_server(serverInput_->text().toStdString());
checkHomeserverVersion(); checkHomeserverVersion();
@ -380,7 +380,7 @@ LoginPage::versionOk(bool passwordSupported_, bool ssoSupported_)
void void
LoginPage::onLoginButtonClicked(LoginMethod loginMethod) LoginPage::onLoginButtonClicked(LoginMethod loginMethod)
{ {
error_label_->setText(""); error_label_->setText(QLatin1String(""));
User user; User user;
if (!matrixid_input_->isValid()) { if (!matrixid_input_->isValid()) {
@ -389,7 +389,7 @@ LoginPage::onLoginButtonClicked(LoginMethod loginMethod)
tr("You have entered an invalid Matrix ID e.g @joe:matrix.org")); tr("You have entered an invalid Matrix ID e.g @joe:matrix.org"));
return; return;
} else { } else {
error_matrixid_label_->setText(""); error_matrixid_label_->setText(QLatin1String(""));
error_matrixid_label_->hide(); error_matrixid_label_->hide();
} }

View file

@ -43,7 +43,7 @@ MainWindow::MainWindow(QWidget *parent)
instance_ = this; instance_ = this;
QMainWindow::setWindowTitle(0); QMainWindow::setWindowTitle(0);
setObjectName("MainWindow"); setObjectName(QStringLiteral("MainWindow"));
modal_ = new OverlayModal(this); modal_ = new OverlayModal(this);
@ -53,7 +53,7 @@ MainWindow::MainWindow(QWidget *parent)
font.setStyleStrategy(QFont::PreferAntialias); font.setStyleStrategy(QFont::PreferAntialias);
setFont(font); setFont(font);
trayIcon_ = new TrayIcon(":/logos/nheko.svg", this); trayIcon_ = new TrayIcon(QStringLiteral(":/logos/nheko.svg"), this);
welcome_page_ = new WelcomePage(this); welcome_page_ = new WelcomePage(this);
login_page_ = new LoginPage(this); login_page_ = new LoginPage(this);
@ -150,12 +150,12 @@ MainWindow::MainWindow(QWidget *parent)
void void
MainWindow::setWindowTitle(int notificationCount) MainWindow::setWindowTitle(int notificationCount)
{ {
QString name = "nheko"; QString name = QStringLiteral("nheko");
if (!userSettings_.data()->profile().isEmpty()) if (!userSettings_.data()->profile().isEmpty())
name += " | " + userSettings_.data()->profile(); name += " | " + userSettings_.data()->profile();
if (notificationCount > 0) { if (notificationCount > 0) {
name.append(QString{" (%1)"}.arg(notificationCount)); name.append(QString{QStringLiteral(" (%1)")}.arg(notificationCount));
} }
QMainWindow::setWindowTitle(name); QMainWindow::setWindowTitle(name);
} }
@ -176,8 +176,8 @@ MainWindow::event(QEvent *event)
void void
MainWindow::restoreWindowSize() MainWindow::restoreWindowSize()
{ {
int savedWidth = userSettings_->qsettings()->value("window/width").toInt(); int savedWidth = userSettings_->qsettings()->value(QStringLiteral("window/width")).toInt();
int savedheight = userSettings_->qsettings()->value("window/height").toInt(); int savedheight = userSettings_->qsettings()->value(QStringLiteral("window/height")).toInt();
nhlog::ui()->info("Restoring window size {}x{}", savedWidth, savedheight); nhlog::ui()->info("Restoring window size {}x{}", savedWidth, savedheight);
@ -193,8 +193,8 @@ MainWindow::saveCurrentWindowSize()
auto settings = userSettings_->qsettings(); auto settings = userSettings_->qsettings();
QSize current = size(); QSize current = size();
settings->setValue("window/width", current.width()); settings->setValue(QStringLiteral("window/width"), current.width());
settings->setValue("window/height", current.height()); settings->setValue(QStringLiteral("window/height"), current.height());
} }
void void
@ -261,7 +261,7 @@ void
MainWindow::closeEvent(QCloseEvent *event) MainWindow::closeEvent(QCloseEvent *event)
{ {
if (WebRTCSession::instance().state() != webrtc::State::DISCONNECTED) { if (WebRTCSession::instance().state() != webrtc::State::DISCONNECTED) {
if (QMessageBox::question(this, "nheko", "A call is in progress. Quit?") != if (QMessageBox::question(this, QStringLiteral("nheko"), QStringLiteral("A call is in progress. Quit?")) !=
QMessageBox::Yes) { QMessageBox::Yes) {
event->ignore(); event->ignore();
return; return;
@ -295,7 +295,7 @@ MainWindow::hasActiveUser()
{ {
auto settings = userSettings_->qsettings(); auto settings = userSettings_->qsettings();
QString prefix; QString prefix;
if (userSettings_->profile() != "") if (userSettings_->profile() != QLatin1String(""))
prefix = "profile/" + userSettings_->profile() + "/"; prefix = "profile/" + userSettings_->profile() + "/";
return settings->contains(prefix + "auth/access_token") && return settings->contains(prefix + "auth/access_token") &&
@ -309,7 +309,7 @@ MainWindow::showOverlayProgressBar()
spinner_ = new LoadingIndicator(this); spinner_ = new LoadingIndicator(this);
spinner_->setFixedHeight(100); spinner_->setFixedHeight(100);
spinner_->setFixedWidth(100); spinner_->setFixedWidth(100);
spinner_->setObjectName("ChatPageLoadSpinner"); spinner_->setObjectName(QStringLiteral("ChatPageLoadSpinner"));
spinner_->start(); spinner_->start();
showSolidOverlayModal(spinner_); showSolidOverlayModal(spinner_);

View file

@ -63,7 +63,7 @@ MxcImageRunnable::run()
m_requestedSize, m_requestedSize,
[this](QString, QSize, QImage image, QString) { [this](QString, QSize, QImage image, QString) {
if (image.isNull()) { if (image.isNull()) {
emit error("Failed to download image."); emit error(QStringLiteral("Failed to download image."));
} else { } else {
emit done(image); emit done(image);
} }
@ -172,7 +172,7 @@ MxcImageProvider::download(const QString &id,
image = clipRadius(std::move(image), radius); image = clipRadius(std::move(image), radius);
} }
} }
image.setText("mxc url", "mxc://" + id); image.setText(QStringLiteral("mxc url"), "mxc://" + id);
if (image.save(fileInfo.absoluteFilePath(), "png")) if (image.save(fileInfo.absoluteFilePath(), "png"))
nhlog::ui()->debug("Wrote: {}", fileInfo.absoluteFilePath().toStdString()); nhlog::ui()->debug("Wrote: {}", fileInfo.absoluteFilePath().toStdString());
else else
@ -183,7 +183,7 @@ MxcImageProvider::download(const QString &id,
}); });
} else { } else {
try { try {
QString fileName = QString("%1_radius%2") QString fileName = QStringLiteral("%1_radius%2")
.arg(QString::fromUtf8(id.toUtf8().toBase64( .arg(QString::fromUtf8(id.toUtf8().toBase64(
QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals))) QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals)))
.arg(radius); .arg(radius);
@ -203,7 +203,7 @@ MxcImageProvider::download(const QString &id,
mtx::crypto::decrypt_file(fileData.toStdString(), encryptionInfo.value())); mtx::crypto::decrypt_file(fileData.toStdString(), encryptionInfo.value()));
auto data = QByteArray(tempData.data(), (int)tempData.size()); auto data = QByteArray(tempData.data(), (int)tempData.size());
QImage image = utils::readImage(data); QImage image = utils::readImage(data);
image.setText("mxc url", "mxc://" + id); image.setText(QStringLiteral("mxc url"), "mxc://" + id);
if (!image.isNull()) { if (!image.isNull()) {
if (radius != 0) { if (radius != 0) {
image = clipRadius(std::move(image), radius); image = clipRadius(std::move(image), radius);
@ -233,14 +233,14 @@ MxcImageProvider::download(const QString &id,
const std::string &originalFilename, const std::string &originalFilename,
mtx::http::RequestErr err) { mtx::http::RequestErr err) {
if (err) { if (err) {
then(id, QSize(), {}, ""); then(id, QSize(), {}, QLatin1String(""));
return; return;
} }
auto tempData = res; auto tempData = res;
QFile f(fileInfo.absoluteFilePath()); QFile f(fileInfo.absoluteFilePath());
if (!f.open(QIODevice::Truncate | QIODevice::WriteOnly)) { if (!f.open(QIODevice::Truncate | QIODevice::WriteOnly)) {
then(id, QSize(), {}, ""); then(id, QSize(), {}, QLatin1String(""));
return; return;
} }
f.write(tempData.data(), tempData.size()); f.write(tempData.data(), tempData.size());
@ -255,8 +255,8 @@ MxcImageProvider::download(const QString &id,
image = clipRadius(std::move(image), radius); image = clipRadius(std::move(image), radius);
} }
image.setText("original filename", QString::fromStdString(originalFilename)); image.setText(QStringLiteral("original filename"), QString::fromStdString(originalFilename));
image.setText("mxc url", "mxc://" + id); image.setText(QStringLiteral("mxc url"), "mxc://" + id);
then(id, requestedSize, image, fileInfo.absoluteFilePath()); then(id, requestedSize, image, fileInfo.absoluteFilePath());
return; return;
} }
@ -266,8 +266,8 @@ MxcImageProvider::download(const QString &id,
image = clipRadius(std::move(image), radius); image = clipRadius(std::move(image), radius);
} }
image.setText("original filename", QString::fromStdString(originalFilename)); image.setText(QStringLiteral("original filename"), QString::fromStdString(originalFilename));
image.setText("mxc url", "mxc://" + id); image.setText(QStringLiteral("mxc url"), "mxc://" + id);
then(id, requestedSize, image, fileInfo.absoluteFilePath()); then(id, requestedSize, image, fileInfo.absoluteFilePath());
}); });
} catch (std::exception &e) { } catch (std::exception &e) {

View file

@ -112,7 +112,7 @@ ReadReceiptsModel::dateFormat(const QDateTime &then) const
else if (days < 7) else if (days < 7)
//: %1 is the name of the current day, %2 is the time the read receipt was read. The //: %1 is the name of the current day, %2 is the time the read receipt was read. The
//: result may look like this: Monday, 7:15 //: result may look like this: Monday, 7:15
return QString("%1, %2").arg(then.toString("dddd"), return QStringLiteral("%1, %2").arg(then.toString(QStringLiteral("dddd")),
QLocale::system().toString(then.time(), QLocale::ShortFormat)); QLocale::system().toString(then.time(), QLocale::ShortFormat));
return QLocale::system().toString(then.time(), QLocale::ShortFormat); return QLocale::system().toString(then.time(), QLocale::ShortFormat);

View file

@ -46,7 +46,7 @@ RegisterPage::RegisterPage(QWidget *parent)
back_button_->setMinimumSize(QSize(30, 30)); back_button_->setMinimumSize(QSize(30, 30));
QIcon icon; QIcon icon;
icon.addFile(":/icons/icons/ui/angle-arrow-left.svg"); icon.addFile(QStringLiteral(":/icons/icons/ui/angle-arrow-left.svg"));
back_button_->setIcon(icon); back_button_->setIcon(icon);
back_button_->setIconSize(QSize(32, 32)); back_button_->setIconSize(QSize(32, 32));
@ -55,7 +55,7 @@ RegisterPage::RegisterPage(QWidget *parent)
back_layout_->addStretch(1); back_layout_->addStretch(1);
QIcon logo; QIcon logo;
logo.addFile(":/logos/register.png"); logo.addFile(QStringLiteral(":/logos/register.png"));
logo_ = new QLabel(this); logo_ = new QLabel(this);
logo_->setPixmap(logo.pixmap(128)); logo_->setPixmap(logo.pixmap(128));
@ -79,13 +79,13 @@ RegisterPage::RegisterPage(QWidget *parent)
username_input_ = new TextField(); username_input_ = new TextField();
username_input_->setLabel(tr("Username")); username_input_->setLabel(tr("Username"));
username_input_->setRegexp(QRegularExpression("[a-z0-9._=/-]+")); username_input_->setRegexp(QRegularExpression(QStringLiteral("[a-z0-9._=/-]+")));
username_input_->setToolTip(tr("The username must not be empty, and must contain only the " username_input_->setToolTip(tr("The username must not be empty, and must contain only the "
"characters a-z, 0-9, ., _, =, -, and /.")); "characters a-z, 0-9, ., _, =, -, and /."));
password_input_ = new TextField(); password_input_ = new TextField();
password_input_->setLabel(tr("Password")); password_input_->setLabel(tr("Password"));
password_input_->setRegexp(QRegularExpression("^.{8,}$")); password_input_->setRegexp(QRegularExpression(QStringLiteral("^.{8,}$")));
password_input_->setEchoMode(QLineEdit::Password); password_input_->setEchoMode(QLineEdit::Password);
password_input_->setToolTip(tr("Please choose a secure password. The exact requirements " password_input_->setToolTip(tr("Please choose a secure password. The exact requirements "
"for password strength may depend on your server.")); "for password strength may depend on your server."));
@ -96,7 +96,7 @@ RegisterPage::RegisterPage(QWidget *parent)
server_input_ = new TextField(); server_input_ = new TextField();
server_input_->setLabel(tr("Homeserver")); server_input_->setLabel(tr("Homeserver"));
server_input_->setRegexp(QRegularExpression(".+")); server_input_->setRegexp(QRegularExpression(QStringLiteral(".+")));
server_input_->setToolTip( server_input_->setToolTip(
tr("A server that allows registration. Since matrix is decentralized, you need to first " tr("A server that allows registration. Since matrix is decentralized, you need to first "
"find a server you can register on or host your own.")); "find a server you can register on or host your own."));
@ -364,7 +364,7 @@ RegisterPage::doRegistration()
disconnect(UIA::instance(), &UIA::error, this, nullptr); disconnect(UIA::instance(), &UIA::error, this, nullptr);
}); });
http::client()->registration( http::client()->registration(
username, password, ::UIA::instance()->genericHandler("Registration"), registrationCb()); username, password, ::UIA::instance()->genericHandler(QStringLiteral("Registration")), registrationCb());
} }
} }

View file

@ -71,7 +71,7 @@ signals:
void reachedEndOfPaginationChanged(); void reachedEndOfPaginationChanged();
public slots: public slots:
void setMatrixServer(const QString &s = ""); void setMatrixServer(const QString &s = QLatin1String(""));
void setSearchTerm(const QString &f); void setSearchTerm(const QString &f);
private slots: private slots:

View file

@ -32,7 +32,7 @@ RoomsModel::RoomsModel(bool showOnlyRoomWithAliases, QObject *parent)
} else { } else {
roomids.push_back(QString::fromStdString(r)); roomids.push_back(QString::fromStdString(r));
roomAliases.push_back(roomAliasesList ? QString::fromStdString(roomAliasesList->alias) roomAliases.push_back(roomAliasesList ? QString::fromStdString(roomAliasesList->alias)
: ""); : QLatin1String(""));
} }
} }
} }
@ -57,7 +57,7 @@ RoomsModel::data(const QModelIndex &index, int role) const
case CompletionModel::CompletionRole: { case CompletionModel::CompletionRole: {
if (UserSettings::instance()->markdown()) { if (UserSettings::instance()->markdown()) {
QString percentEncoding = QUrl::toPercentEncoding(roomAliases[index.row()]); QString percentEncoding = QUrl::toPercentEncoding(roomAliases[index.row()]);
return QString("[%1](https://matrix.to/#/%2)") return QStringLiteral("[%1](https://matrix.to/#/%2)")
.arg(roomAliases[index.row()], percentEncoding); .arg(roomAliases[index.row()], percentEncoding);
} else { } else {
return roomAliases[index.row()]; return roomAliases[index.row()];

View file

@ -224,7 +224,7 @@ SingleImagePackModel::avatarUrl() const
else if (!pack.images.empty()) else if (!pack.images.empty())
return QString::fromStdString(pack.images.begin()->second.url); return QString::fromStdString(pack.images.begin()->second.url);
else else
return ""; return QString();
} }
void void

View file

@ -60,58 +60,58 @@ UserSettings::initialize(std::optional<QString> profile)
void void
UserSettings::load(std::optional<QString> profile) UserSettings::load(std::optional<QString> profile)
{ {
tray_ = settings.value("user/window/tray", false).toBool(); tray_ = settings.value(QStringLiteral("user/window/tray"), false).toBool();
startInTray_ = settings.value("user/window/start_in_tray", false).toBool(); startInTray_ = settings.value(QStringLiteral("user/window/start_in_tray"), false).toBool();
roomListWidth_ = settings.value("user/sidebar/room_list_width", -1).toInt(); roomListWidth_ = settings.value(QStringLiteral("user/sidebar/room_list_width"), -1).toInt();
communityListWidth_ = settings.value("user/sidebar/community_list_width", -1).toInt(); communityListWidth_ = settings.value(QStringLiteral("user/sidebar/community_list_width"), -1).toInt();
hasDesktopNotifications_ = settings.value("user/desktop_notifications", true).toBool(); hasDesktopNotifications_ = settings.value(QStringLiteral("user/desktop_notifications"), true).toBool();
hasAlertOnNotification_ = settings.value("user/alert_on_notification", false).toBool(); hasAlertOnNotification_ = settings.value(QStringLiteral("user/alert_on_notification"), false).toBool();
groupView_ = settings.value("user/group_view", true).toBool(); groupView_ = settings.value(QStringLiteral("user/group_view"), true).toBool();
buttonsInTimeline_ = settings.value("user/timeline/buttons", true).toBool(); buttonsInTimeline_ = settings.value(QStringLiteral("user/timeline/buttons"), true).toBool();
timelineMaxWidth_ = settings.value("user/timeline/max_width", 0).toInt(); timelineMaxWidth_ = settings.value(QStringLiteral("user/timeline/max_width"), 0).toInt();
messageHoverHighlight_ = messageHoverHighlight_ =
settings.value("user/timeline/message_hover_highlight", false).toBool(); settings.value(QStringLiteral("user/timeline/message_hover_highlight"), false).toBool();
enlargeEmojiOnlyMessages_ = enlargeEmojiOnlyMessages_ =
settings.value("user/timeline/enlarge_emoji_only_msg", false).toBool(); settings.value(QStringLiteral("user/timeline/enlarge_emoji_only_msg"), false).toBool();
markdown_ = settings.value("user/markdown_enabled", true).toBool(); markdown_ = settings.value(QStringLiteral("user/markdown_enabled"), true).toBool();
animateImagesOnHover_ = settings.value("user/animate_images_on_hover", false).toBool(); animateImagesOnHover_ = settings.value(QStringLiteral("user/animate_images_on_hover"), false).toBool();
typingNotifications_ = settings.value("user/typing_notifications", true).toBool(); typingNotifications_ = settings.value(QStringLiteral("user/typing_notifications"), true).toBool();
sortByImportance_ = settings.value("user/sort_by_unread", true).toBool(); sortByImportance_ = settings.value(QStringLiteral("user/sort_by_unread"), true).toBool();
readReceipts_ = settings.value("user/read_receipts", true).toBool(); readReceipts_ = settings.value(QStringLiteral("user/read_receipts"), true).toBool();
theme_ = settings.value("user/theme", defaultTheme_).toString(); theme_ = settings.value(QStringLiteral("user/theme"), defaultTheme_).toString();
font_ = settings.value("user/font_family", "default").toString(); font_ = settings.value(QStringLiteral("user/font_family"), "default").toString();
avatarCircles_ = settings.value("user/avatar_circles", true).toBool(); avatarCircles_ = settings.value(QStringLiteral("user/avatar_circles"), true).toBool();
useIdenticon_ = settings.value("user/use_identicon", true).toBool(); useIdenticon_ = settings.value(QStringLiteral("user/use_identicon"), true).toBool();
decryptSidebar_ = settings.value("user/decrypt_sidebar", true).toBool(); decryptSidebar_ = settings.value(QStringLiteral("user/decrypt_sidebar"), true).toBool();
privacyScreen_ = settings.value("user/privacy_screen", false).toBool(); privacyScreen_ = settings.value(QStringLiteral("user/privacy_screen"), false).toBool();
privacyScreenTimeout_ = settings.value("user/privacy_screen_timeout", 0).toInt(); privacyScreenTimeout_ = settings.value(QStringLiteral("user/privacy_screen_timeout"), 0).toInt();
mobileMode_ = settings.value("user/mobile_mode", false).toBool(); mobileMode_ = settings.value(QStringLiteral("user/mobile_mode"), false).toBool();
emojiFont_ = settings.value("user/emoji_font_family", "default").toString(); emojiFont_ = settings.value(QStringLiteral("user/emoji_font_family"), "default").toString();
baseFontSize_ = settings.value("user/font_size", QFont().pointSizeF()).toDouble(); baseFontSize_ = settings.value(QStringLiteral("user/font_size"), QFont().pointSizeF()).toDouble();
auto tempPresence = settings.value("user/presence", "").toString().toStdString(); auto tempPresence = settings.value(QStringLiteral("user/presence"), "").toString().toStdString();
auto presenceValue = QMetaEnum::fromType<Presence>().keyToValue(tempPresence.c_str()); auto presenceValue = QMetaEnum::fromType<Presence>().keyToValue(tempPresence.c_str());
if (presenceValue < 0) if (presenceValue < 0)
presenceValue = 0; presenceValue = 0;
presence_ = static_cast<Presence>(presenceValue); presence_ = static_cast<Presence>(presenceValue);
ringtone_ = settings.value("user/ringtone", "Default").toString(); ringtone_ = settings.value(QStringLiteral("user/ringtone"), "Default").toString();
microphone_ = settings.value("user/microphone", QString()).toString(); microphone_ = settings.value(QStringLiteral("user/microphone"), QString()).toString();
camera_ = settings.value("user/camera", QString()).toString(); camera_ = settings.value(QStringLiteral("user/camera"), QString()).toString();
cameraResolution_ = settings.value("user/camera_resolution", QString()).toString(); cameraResolution_ = settings.value(QStringLiteral("user/camera_resolution"), QString()).toString();
cameraFrameRate_ = settings.value("user/camera_frame_rate", QString()).toString(); cameraFrameRate_ = settings.value(QStringLiteral("user/camera_frame_rate"), QString()).toString();
screenShareFrameRate_ = settings.value("user/screen_share_frame_rate", 5).toInt(); screenShareFrameRate_ = settings.value(QStringLiteral("user/screen_share_frame_rate"), 5).toInt();
screenSharePiP_ = settings.value("user/screen_share_pip", true).toBool(); screenSharePiP_ = settings.value(QStringLiteral("user/screen_share_pip"), true).toBool();
screenShareRemoteVideo_ = settings.value("user/screen_share_remote_video", false).toBool(); screenShareRemoteVideo_ = settings.value(QStringLiteral("user/screen_share_remote_video"), false).toBool();
screenShareHideCursor_ = settings.value("user/screen_share_hide_cursor", false).toBool(); screenShareHideCursor_ = settings.value(QStringLiteral("user/screen_share_hide_cursor"), false).toBool();
useStunServer_ = settings.value("user/use_stun_server", false).toBool(); useStunServer_ = settings.value(QStringLiteral("user/use_stun_server"), false).toBool();
if (profile) // set to "" if it's the default to maintain compatibility if (profile) // set to "" if it's the default to maintain compatibility
profile_ = (*profile == "default") ? "" : *profile; profile_ = (*profile == QLatin1String("default")) ? QLatin1String("") : *profile;
else else
profile_ = settings.value("user/currentProfile", "").toString(); profile_ = settings.value(QStringLiteral("user/currentProfile"), "").toString();
QString prefix = (profile_ != "" && profile_ != "default") ? "profile/" + profile_ + "/" : ""; QString prefix = (profile_ != QLatin1String("") && profile_ != QLatin1String("default")) ? "profile/" + profile_ + "/" : QLatin1String("");
accessToken_ = settings.value(prefix + "auth/access_token", "").toString(); accessToken_ = settings.value(prefix + "auth/access_token", "").toString();
homeserver_ = settings.value(prefix + "auth/home_server", "").toString(); homeserver_ = settings.value(prefix + "auth/home_server", "").toString();
userId_ = settings.value(prefix + "auth/user_id", "").toString(); userId_ = settings.value(prefix + "auth/user_id", "").toString();
@ -133,7 +133,7 @@ UserSettings::load(std::optional<QString> profile)
useOnlineKeyBackup_ = settings.value(prefix + "user/online_key_backup", false).toBool(); useOnlineKeyBackup_ = settings.value(prefix + "user/online_key_backup", false).toBool();
disableCertificateValidation_ = disableCertificateValidation_ =
settings.value("disable_certificate_validation", false).toBool(); settings.value(QStringLiteral("disable_certificate_validation"), false).toBool();
applyTheme(); applyTheme();
} }
@ -403,7 +403,7 @@ UserSettings::setEmojiFontFamily(QString family)
return; return;
if (family == tr("Default")) { if (family == tr("Default")) {
emojiFont_ = "default"; emojiFont_ = QStringLiteral("default");
} else { } else {
emojiFont_ = family; emojiFont_ = family;
} }
@ -641,12 +641,12 @@ UserSettings::applyTheme()
{ {
QFile stylefile; QFile stylefile;
if (this->theme() == "light") { if (this->theme() == QLatin1String("light")) {
stylefile.setFileName(":/styles/styles/nheko.qss"); stylefile.setFileName(QStringLiteral(":/styles/styles/nheko.qss"));
} else if (this->theme() == "dark") { } else if (this->theme() == QLatin1String("dark")) {
stylefile.setFileName(":/styles/styles/nheko-dark.qss"); stylefile.setFileName(QStringLiteral(":/styles/styles/nheko-dark.qss"));
} else { } else {
stylefile.setFileName(":/styles/styles/system.qss"); stylefile.setFileName(QStringLiteral(":/styles/styles/system.qss"));
} }
QApplication::setPalette(Theme::paletteFromTheme(this->theme().toStdString())); QApplication::setPalette(Theme::paletteFromTheme(this->theme().toStdString()));
@ -659,62 +659,62 @@ UserSettings::applyTheme()
void void
UserSettings::save() UserSettings::save()
{ {
settings.beginGroup("user"); settings.beginGroup(QStringLiteral("user"));
settings.beginGroup("window"); settings.beginGroup(QStringLiteral("window"));
settings.setValue("tray", tray_); settings.setValue(QStringLiteral("tray"), tray_);
settings.setValue("start_in_tray", startInTray_); settings.setValue(QStringLiteral("start_in_tray"), startInTray_);
settings.endGroup(); // window settings.endGroup(); // window
settings.beginGroup("sidebar"); settings.beginGroup(QStringLiteral("sidebar"));
settings.setValue("community_list_width", communityListWidth_); settings.setValue(QStringLiteral("community_list_width"), communityListWidth_);
settings.setValue("room_list_width", roomListWidth_); settings.setValue(QStringLiteral("room_list_width"), roomListWidth_);
settings.endGroup(); // window settings.endGroup(); // window
settings.beginGroup("timeline"); settings.beginGroup(QStringLiteral("timeline"));
settings.setValue("buttons", buttonsInTimeline_); settings.setValue(QStringLiteral("buttons"), buttonsInTimeline_);
settings.setValue("message_hover_highlight", messageHoverHighlight_); settings.setValue(QStringLiteral("message_hover_highlight"), messageHoverHighlight_);
settings.setValue("enlarge_emoji_only_msg", enlargeEmojiOnlyMessages_); settings.setValue(QStringLiteral("enlarge_emoji_only_msg"), enlargeEmojiOnlyMessages_);
settings.setValue("max_width", timelineMaxWidth_); settings.setValue(QStringLiteral("max_width"), timelineMaxWidth_);
settings.endGroup(); // timeline settings.endGroup(); // timeline
settings.setValue("avatar_circles", avatarCircles_); settings.setValue(QStringLiteral("avatar_circles"), avatarCircles_);
settings.setValue("decrypt_sidebar", decryptSidebar_); settings.setValue(QStringLiteral("decrypt_sidebar"), decryptSidebar_);
settings.setValue("privacy_screen", privacyScreen_); settings.setValue(QStringLiteral("privacy_screen"), privacyScreen_);
settings.setValue("privacy_screen_timeout", privacyScreenTimeout_); settings.setValue(QStringLiteral("privacy_screen_timeout"), privacyScreenTimeout_);
settings.setValue("mobile_mode", mobileMode_); settings.setValue(QStringLiteral("mobile_mode"), mobileMode_);
settings.setValue("font_size", baseFontSize_); settings.setValue(QStringLiteral("font_size"), baseFontSize_);
settings.setValue("typing_notifications", typingNotifications_); settings.setValue(QStringLiteral("typing_notifications"), typingNotifications_);
settings.setValue("sort_by_unread", sortByImportance_); settings.setValue(QStringLiteral("sort_by_unread"), sortByImportance_);
settings.setValue("minor_events", sortByImportance_); settings.setValue(QStringLiteral("minor_events"), sortByImportance_);
settings.setValue("read_receipts", readReceipts_); settings.setValue(QStringLiteral("read_receipts"), readReceipts_);
settings.setValue("group_view", groupView_); settings.setValue(QStringLiteral("group_view"), groupView_);
settings.setValue("markdown_enabled", markdown_); settings.setValue(QStringLiteral("markdown_enabled"), markdown_);
settings.setValue("animate_images_on_hover", animateImagesOnHover_); settings.setValue(QStringLiteral("animate_images_on_hover"), animateImagesOnHover_);
settings.setValue("desktop_notifications", hasDesktopNotifications_); settings.setValue(QStringLiteral("desktop_notifications"), hasDesktopNotifications_);
settings.setValue("alert_on_notification", hasAlertOnNotification_); settings.setValue(QStringLiteral("alert_on_notification"), hasAlertOnNotification_);
settings.setValue("theme", theme()); settings.setValue(QStringLiteral("theme"), theme());
settings.setValue("font_family", font_); settings.setValue(QStringLiteral("font_family"), font_);
settings.setValue("emoji_font_family", emojiFont_); settings.setValue(QStringLiteral("emoji_font_family"), emojiFont_);
settings.setValue( settings.setValue(
"presence", QStringLiteral("presence"),
QString::fromUtf8(QMetaEnum::fromType<Presence>().valueToKey(static_cast<int>(presence_)))); QString::fromUtf8(QMetaEnum::fromType<Presence>().valueToKey(static_cast<int>(presence_))));
settings.setValue("ringtone", ringtone_); settings.setValue(QStringLiteral("ringtone"), ringtone_);
settings.setValue("microphone", microphone_); settings.setValue(QStringLiteral("microphone"), microphone_);
settings.setValue("camera", camera_); settings.setValue(QStringLiteral("camera"), camera_);
settings.setValue("camera_resolution", cameraResolution_); settings.setValue(QStringLiteral("camera_resolution"), cameraResolution_);
settings.setValue("camera_frame_rate", cameraFrameRate_); settings.setValue(QStringLiteral("camera_frame_rate"), cameraFrameRate_);
settings.setValue("screen_share_frame_rate", screenShareFrameRate_); settings.setValue(QStringLiteral("screen_share_frame_rate"), screenShareFrameRate_);
settings.setValue("screen_share_pip", screenSharePiP_); settings.setValue(QStringLiteral("screen_share_pip"), screenSharePiP_);
settings.setValue("screen_share_remote_video", screenShareRemoteVideo_); settings.setValue(QStringLiteral("screen_share_remote_video"), screenShareRemoteVideo_);
settings.setValue("screen_share_hide_cursor", screenShareHideCursor_); settings.setValue(QStringLiteral("screen_share_hide_cursor"), screenShareHideCursor_);
settings.setValue("use_stun_server", useStunServer_); settings.setValue(QStringLiteral("use_stun_server"), useStunServer_);
settings.setValue("currentProfile", profile_); settings.setValue(QStringLiteral("currentProfile"), profile_);
settings.setValue("use_identicon", useIdenticon_); settings.setValue(QStringLiteral("use_identicon"), useIdenticon_);
settings.endGroup(); // user settings.endGroup(); // user
QString prefix = (profile_ != "" && profile_ != "default") ? "profile/" + profile_ + "/" : ""; QString prefix = (profile_ != QLatin1String("") && profile_ != QLatin1String("default")) ? "profile/" + profile_ + "/" : QLatin1String("");
settings.setValue(prefix + "auth/access_token", accessToken_); settings.setValue(prefix + "auth/access_token", accessToken_);
settings.setValue(prefix + "auth/home_server", homeserver_); settings.setValue(prefix + "auth/home_server", homeserver_);
settings.setValue(prefix + "auth/user_id", userId_); settings.setValue(prefix + "auth/user_id", userId_);
@ -734,7 +734,7 @@ UserSettings::save()
v.push_back(e); v.push_back(e);
settings.setValue(prefix + "user/collapsed_spaces", v); settings.setValue(prefix + "user/collapsed_spaces", v);
settings.setValue("disable_certificate_validation", disableCertificateValidation_); settings.setValue(QStringLiteral("disable_certificate_validation"), disableCertificateValidation_);
settings.sync(); settings.sync();
} }
@ -753,7 +753,7 @@ UserSettingsPage::UserSettingsPage(QSharedPointer<UserSettings> settings, QWidge
topLayout_ = new QVBoxLayout{this}; topLayout_ = new QVBoxLayout{this};
QIcon icon; QIcon icon;
icon.addFile(":/icons/icons/ui/angle-arrow-left.svg"); icon.addFile(QStringLiteral(":/icons/icons/ui/angle-arrow-left.svg"));
auto backBtn_ = new FlatButton{this}; auto backBtn_ = new FlatButton{this};
backBtn_->setMinimumSize(QSize(24, 24)); backBtn_->setMinimumSize(QSize(24, 24));
@ -763,8 +763,8 @@ UserSettingsPage::UserSettingsPage(QSharedPointer<UserSettings> settings, QWidge
QFont font; QFont font;
font.setPointSizeF(font.pointSizeF() * 1.1); font.setPointSizeF(font.pointSizeF() * 1.1);
auto versionInfo = new QLabel(QString("%1 | %2").arg(nheko::version, nheko::build_os)); auto versionInfo = new QLabel(QStringLiteral("%1 | %2").arg(nheko::version, nheko::build_os));
if (QCoreApplication::applicationName() != "nheko") if (QCoreApplication::applicationName() != QLatin1String("nheko"))
versionInfo->setText(versionInfo->text() + " | " + versionInfo->setText(versionInfo->text() + " | " +
tr("profile: %1").arg(QCoreApplication::applicationName())); tr("profile: %1").arg(QCoreApplication::applicationName()));
versionInfo->setTextInteractionFlags(Qt::TextBrowserInteraction); versionInfo->setTextInteractionFlags(Qt::TextBrowserInteraction);
@ -863,7 +863,7 @@ UserSettingsPage::UserSettingsPage(QSharedPointer<UserSettings> settings, QWidge
for (double option = 1; option <= 3; option += 0.25) for (double option = 1; option <= 3; option += 0.25)
scaleFactorCombo_->addItem(QString::number(option)); scaleFactorCombo_->addItem(QString::number(option));
for (double option = 6; option <= 24; option += 0.5) for (double option = 6; option <= 24; option += 0.5)
fontSizeCombo_->addItem(QString("%1 ").arg(QString::number(option))); fontSizeCombo_->addItem(QStringLiteral("%1 ").arg(QString::number(option)));
QFontDatabase fontDb; QFontDatabase fontDb;
@ -876,7 +876,7 @@ UserSettingsPage::UserSettingsPage(QSharedPointer<UserSettings> settings, QWidge
} }
QString currentFont = settings_->font(); QString currentFont = settings_->font();
if (currentFont != "default" || currentFont != "") { if (currentFont != QLatin1String("default") || currentFont != QLatin1String("")) {
fontSelectionCombo_->setCurrentIndex(fontSelectionCombo_->findText(currentFont)); fontSelectionCombo_->setCurrentIndex(fontSelectionCombo_->findText(currentFont));
} }
@ -884,9 +884,9 @@ UserSettingsPage::UserSettingsPage(QSharedPointer<UserSettings> settings, QWidge
emojiFontSelectionCombo_->findText(settings_->emojiFont())); emojiFontSelectionCombo_->findText(settings_->emojiFont()));
themeCombo_ = new QComboBox{this}; themeCombo_ = new QComboBox{this};
themeCombo_->addItem("Light"); themeCombo_->addItem(QStringLiteral("Light"));
themeCombo_->addItem("Dark"); themeCombo_->addItem(QStringLiteral("Dark"));
themeCombo_->addItem("System"); themeCombo_->addItem(QStringLiteral("System"));
QString themeStr = settings_->theme(); QString themeStr = settings_->theme();
themeStr.replace(0, 1, themeStr[0].toUpper()); themeStr.replace(0, 1, themeStr[0].toUpper());
@ -912,7 +912,7 @@ UserSettingsPage::UserSettingsPage(QSharedPointer<UserSettings> settings, QWidge
encryptionLabel_->setFont(font); encryptionLabel_->setFont(font);
QFont monospaceFont; QFont monospaceFont;
monospaceFont.setFamily("Monospace"); monospaceFont.setFamily(QStringLiteral("Monospace"));
monospaceFont.setStyleHint(QFont::Monospace); monospaceFont.setStyleHint(QFont::Monospace);
monospaceFont.setPointSizeF(monospaceFont.pointSizeF() * 0.9); monospaceFont.setPointSizeF(monospaceFont.pointSizeF() * 0.9);
@ -943,7 +943,7 @@ UserSettingsPage::UserSettingsPage(QSharedPointer<UserSettings> settings, QWidge
auto sessionKeysExportBtn = new QPushButton{tr("EXPORT"), this}; auto sessionKeysExportBtn = new QPushButton{tr("EXPORT"), this};
auto sessionKeysLayout = new QHBoxLayout; auto sessionKeysLayout = new QHBoxLayout;
sessionKeysLayout->addWidget(new QLabel{"", this}, 1, Qt::AlignRight); sessionKeysLayout->addWidget(new QLabel{QLatin1String(""), this}, 1, Qt::AlignRight);
sessionKeysLayout->addWidget(sessionKeysExportBtn, 0, Qt::AlignRight); sessionKeysLayout->addWidget(sessionKeysExportBtn, 0, Qt::AlignRight);
sessionKeysLayout->addWidget(sessionKeysImportBtn, 0, Qt::AlignRight); sessionKeysLayout->addWidget(sessionKeysImportBtn, 0, Qt::AlignRight);
@ -955,11 +955,11 @@ UserSettingsPage::UserSettingsPage(QSharedPointer<UserSettings> settings, QWidge
auto crossSigningDownloadBtn = new QPushButton{tr("DOWNLOAD"), this}; auto crossSigningDownloadBtn = new QPushButton{tr("DOWNLOAD"), this};
auto crossSigningKeysLayout = new QHBoxLayout; auto crossSigningKeysLayout = new QHBoxLayout;
crossSigningKeysLayout->addWidget(new QLabel{"", this}, 1, Qt::AlignRight); crossSigningKeysLayout->addWidget(new QLabel{QLatin1String(""), this}, 1, Qt::AlignRight);
crossSigningKeysLayout->addWidget(crossSigningRequestBtn, 0, Qt::AlignRight); crossSigningKeysLayout->addWidget(crossSigningRequestBtn, 0, Qt::AlignRight);
crossSigningKeysLayout->addWidget(crossSigningDownloadBtn, 0, Qt::AlignRight); crossSigningKeysLayout->addWidget(crossSigningDownloadBtn, 0, Qt::AlignRight);
auto boxWrap = [this, &font](QString labelText, QWidget *field, QString tooltipText = "") { auto boxWrap = [this, &font](QString labelText, QWidget *field, QString tooltipText = QLatin1String("")) {
auto label = new QLabel{labelText, this}; auto label = new QLabel{labelText, this};
label->setFont(font); label->setFont(font);
label->setMargin(OptionMargin); label->setMargin(OptionMargin);
@ -1083,11 +1083,11 @@ UserSettingsPage::UserSettingsPage(QSharedPointer<UserSettings> settings, QWidge
boxWrap(tr("Camera frame rate"), cameraFrameRateCombo_); boxWrap(tr("Camera frame rate"), cameraFrameRateCombo_);
ringtoneCombo_->setSizeAdjustPolicy(QComboBox::AdjustToContents); ringtoneCombo_->setSizeAdjustPolicy(QComboBox::AdjustToContents);
ringtoneCombo_->addItem("Mute"); ringtoneCombo_->addItem(QStringLiteral("Mute"));
ringtoneCombo_->addItem("Default"); ringtoneCombo_->addItem(QStringLiteral("Default"));
ringtoneCombo_->addItem("Other..."); ringtoneCombo_->addItem(QStringLiteral("Other..."));
const QString &ringtone = settings_->ringtone(); const QString &ringtone = settings_->ringtone();
if (!ringtone.isEmpty() && ringtone != "Mute" && ringtone != "Default") if (!ringtone.isEmpty() && ringtone != QLatin1String("Mute") && ringtone != QLatin1String("Default"))
ringtoneCombo_->addItem(ringtone); ringtoneCombo_->addItem(ringtone);
microphoneCombo_->setSizeAdjustPolicy(QComboBox::AdjustToContents); microphoneCombo_->setSizeAdjustPolicy(QComboBox::AdjustToContents);
cameraCombo_->setSizeAdjustPolicy(QComboBox::AdjustToContents); cameraCombo_->setSizeAdjustPolicy(QComboBox::AdjustToContents);
@ -1153,7 +1153,7 @@ UserSettingsPage::UserSettingsPage(QSharedPointer<UserSettings> settings, QWidge
spacingAroundForm->addStretch(1); spacingAroundForm->addStretch(1);
auto scrollAreaContents_ = new QWidget{this}; auto scrollAreaContents_ = new QWidget{this};
scrollAreaContents_->setObjectName("UserSettingScrollWidget"); scrollAreaContents_->setObjectName(QStringLiteral("UserSettingScrollWidget"));
scrollAreaContents_->setLayout(spacingAroundForm); scrollAreaContents_->setLayout(spacingAroundForm);
scrollArea_->setWidget(scrollAreaContents_); scrollArea_->setWidget(scrollAreaContents_);
@ -1190,14 +1190,14 @@ UserSettingsPage::UserSettingsPage(QSharedPointer<UserSettings> settings, QWidge
static_cast<void (QComboBox::*)(const QString &)>(&QComboBox::currentTextChanged), static_cast<void (QComboBox::*)(const QString &)>(&QComboBox::currentTextChanged),
this, this,
[this](const QString &ringtone) { [this](const QString &ringtone) {
if (ringtone == "Other...") { if (ringtone == QLatin1String("Other...")) {
QString homeFolder = QString homeFolder =
QStandardPaths::writableLocation(QStandardPaths::HomeLocation); QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
auto filepath = QFileDialog::getOpenFileName( auto filepath = QFileDialog::getOpenFileName(
this, tr("Select a file"), homeFolder, tr("All Files (*)")); this, tr("Select a file"), homeFolder, tr("All Files (*)"));
if (!filepath.isEmpty()) { if (!filepath.isEmpty()) {
const auto &oldSetting = settings_->ringtone(); const auto &oldSetting = settings_->ringtone();
if (oldSetting != "Mute" && oldSetting != "Default") if (oldSetting != QLatin1String("Mute") && oldSetting != QLatin1String("Default"))
ringtoneCombo_->removeItem(ringtoneCombo_->findText(oldSetting)); ringtoneCombo_->removeItem(ringtoneCombo_->findText(oldSetting));
settings_->setRingtone(filepath); settings_->setRingtone(filepath);
ringtoneCombo_->addItem(filepath); ringtoneCombo_->addItem(filepath);
@ -1205,9 +1205,9 @@ UserSettingsPage::UserSettingsPage(QSharedPointer<UserSettings> settings, QWidge
} else { } else {
ringtoneCombo_->setCurrentText(settings_->ringtone()); ringtoneCombo_->setCurrentText(settings_->ringtone());
} }
} else if (ringtone == "Mute" || ringtone == "Default") { } else if (ringtone == QLatin1String("Mute") || ringtone == QLatin1String("Default")) {
const auto &oldSetting = settings_->ringtone(); const auto &oldSetting = settings_->ringtone();
if (oldSetting != "Mute" && oldSetting != "Default") if (oldSetting != QLatin1String("Mute") && oldSetting != QLatin1String("Default"))
ringtoneCombo_->removeItem(ringtoneCombo_->findText(oldSetting)); ringtoneCombo_->removeItem(ringtoneCombo_->findText(oldSetting));
settings_->setRingtone(ringtone); settings_->setRingtone(ringtone);
} }
@ -1463,7 +1463,7 @@ UserSettingsPage::importSessionKeys()
{ {
const QString homeFolder = QStandardPaths::writableLocation(QStandardPaths::HomeLocation); const QString homeFolder = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
const QString fileName = const QString fileName =
QFileDialog::getOpenFileName(this, tr("Open Sessions File"), homeFolder, ""); QFileDialog::getOpenFileName(this, tr("Open Sessions File"), homeFolder, QLatin1String(""));
QFile file(fileName); QFile file(fileName);
if (!file.open(QIODevice::ReadOnly)) { if (!file.open(QIODevice::ReadOnly)) {
@ -1479,7 +1479,7 @@ UserSettingsPage::importSessionKeys()
tr("File Password"), tr("File Password"),
tr("Enter the passphrase to decrypt the file:"), tr("Enter the passphrase to decrypt the file:"),
QLineEdit::Password, QLineEdit::Password,
"", QLatin1String(""),
&ok); &ok);
if (!ok) if (!ok)
return; return;
@ -1506,7 +1506,7 @@ UserSettingsPage::exportSessionKeys()
tr("File Password"), tr("File Password"),
tr("Enter passphrase to encrypt your session keys:"), tr("Enter passphrase to encrypt your session keys:"),
QLineEdit::Password, QLineEdit::Password,
"", QLatin1String(""),
&ok); &ok);
if (!ok) if (!ok)
return; return;
@ -1534,9 +1534,9 @@ UserSettingsPage::exportSessionKeys()
QString b64 = QString::fromStdString(mtx::crypto::bin2base64(encrypted_blob)); QString b64 = QString::fromStdString(mtx::crypto::bin2base64(encrypted_blob));
QString prefix("-----BEGIN MEGOLM SESSION DATA-----"); QString prefix(QStringLiteral("-----BEGIN MEGOLM SESSION DATA-----"));
QString suffix("-----END MEGOLM SESSION DATA-----"); QString suffix(QStringLiteral("-----END MEGOLM SESSION DATA-----"));
QString newline("\n"); QString newline(QStringLiteral("\n"));
QTextStream out(&file); QTextStream out(&file);
out << prefix << newline << b64 << newline << suffix << newline; out << prefix << newline << b64 << newline << suffix << newline;
file.close(); file.close();
@ -1548,8 +1548,8 @@ UserSettingsPage::exportSessionKeys()
void void
UserSettingsPage::updateSecretStatus() UserSettingsPage::updateSecretStatus()
{ {
QString ok = "QLabel { color : #00cc66; }"; QString ok = QStringLiteral("QLabel { color : #00cc66; }");
QString notSoOk = "QLabel { color : #ff9933; }"; QString notSoOk = QStringLiteral("QLabel { color : #ff9933; }");
auto updateLabel = [&ok, &notSoOk](QLabel *label, const std::string &secretName) { auto updateLabel = [&ok, &notSoOk](QLabel *label, const std::string &secretName) {
if (cache::secret(secretName)) { if (cache::secret(secretName)) {

View file

@ -207,7 +207,7 @@ public:
QString font() const { return font_; } QString font() const { return font_; }
QString emojiFont() const QString emojiFont() const
{ {
if (emojiFont_ == "Default") { if (emojiFont_ == QLatin1String("Default")) {
return tr("Default"); return tr("Default");
} }
@ -292,7 +292,7 @@ signals:
private: private:
// Default to system theme if QT_QPA_PLATFORMTHEME var is set. // Default to system theme if QT_QPA_PLATFORMTHEME var is set.
QString defaultTheme_ = QString defaultTheme_ =
QProcessEnvironment::systemEnvironment().value("QT_QPA_PLATFORMTHEME", "").isEmpty() QProcessEnvironment::systemEnvironment().value(QStringLiteral("QT_QPA_PLATFORMTHEME"), QLatin1String("")).isEmpty()
? "light" ? "light"
: "system"; : "system";
QString theme_; QString theme_;

View file

@ -41,7 +41,7 @@ UsersModel::data(const QModelIndex &index, int role) const
switch (role) { switch (role) {
case CompletionModel::CompletionRole: case CompletionModel::CompletionRole:
if (UserSettings::instance()->markdown()) if (UserSettings::instance()->markdown())
return QString("[%1](https://matrix.to/#/%2)") return QStringLiteral("[%1](https://matrix.to/#/%2)")
.arg(displayNames[index.row()].toHtmlEscaped(), .arg(displayNames[index.row()].toHtmlEscaped(),
QString(QUrl::toPercentEncoding(userids[index.row()]))); QString(QUrl::toPercentEncoding(userids[index.row()])));
else else

View file

@ -58,7 +58,7 @@ std::string
utils::stripReplyFromBody(const std::string &bodyi) utils::stripReplyFromBody(const std::string &bodyi)
{ {
QString body = QString::fromStdString(bodyi); QString body = QString::fromStdString(bodyi);
if (body.startsWith("> <")) { if (body.startsWith(QLatin1String("> <"))) {
auto segments = body.split('\n'); auto segments = body.split('\n');
while (!segments.isEmpty() && segments.begin()->startsWith('>')) while (!segments.isEmpty() && segments.begin()->startsWith('>'))
segments.erase(segments.begin()); segments.erase(segments.begin());
@ -67,7 +67,7 @@ utils::stripReplyFromBody(const std::string &bodyi)
body = segments.join('\n'); body = segments.join('\n');
} }
body.replace("@room", QString::fromUtf8("@\u2060room")); body.replace(QLatin1String("@room"), QString::fromUtf8("@\u2060room"));
return body.toStdString(); return body.toStdString();
} }
@ -75,9 +75,9 @@ std::string
utils::stripReplyFromFormattedBody(const std::string &formatted_bodyi) utils::stripReplyFromFormattedBody(const std::string &formatted_bodyi)
{ {
QString formatted_body = QString::fromStdString(formatted_bodyi); QString formatted_body = QString::fromStdString(formatted_bodyi);
formatted_body.remove(QRegularExpression("<mx-reply>.*</mx-reply>", formatted_body.remove(QRegularExpression(QStringLiteral("<mx-reply>.*</mx-reply>"),
QRegularExpression::DotMatchesEverythingOption)); QRegularExpression::DotMatchesEverythingOption));
formatted_body.replace("@room", QString::fromUtf8("@\u2060room")); formatted_body.replace(QLatin1String("@room"), QString::fromUtf8("@\u2060room"));
return formatted_body.toStdString(); return formatted_body.toStdString();
} }
@ -164,14 +164,14 @@ utils::setScaleFactor(float factor)
return; return;
QSettings settings; QSettings settings;
settings.setValue("settings/scale_factor", factor); settings.setValue(QStringLiteral("settings/scale_factor"), factor);
} }
float float
utils::scaleFactor() utils::scaleFactor()
{ {
QSettings settings; QSettings settings;
return settings.value("settings/scale_factor", -1).toFloat(); return settings.value(QStringLiteral("settings/scale_factor"), -1).toFloat();
} }
QString QString
@ -185,7 +185,7 @@ utils::descriptiveTime(const QDateTime &then)
else if (days < 2) else if (days < 2)
return QString(QCoreApplication::translate("descriptiveTime", "Yesterday")); return QString(QCoreApplication::translate("descriptiveTime", "Yesterday"));
else if (days < 7) else if (days < 7)
return then.toString("dddd"); return then.toString(QStringLiteral("dddd"));
return QLocale::system().toString(then.date(), QLocale::ShortFormat); return QLocale::system().toString(then.date(), QLocale::ShortFormat);
} }
@ -238,7 +238,7 @@ utils::getMessageDescription(const TimelineEvent &event,
DescInfo info; DescInfo info;
info.userid = sender; info.userid = sender;
info.body = info.body =
QString(" %1").arg(messageDescription<Encrypted>(username, "", sender == localUser)); QStringLiteral(" %1").arg(messageDescription<Encrypted>(username, QLatin1String(""), sender == localUser));
info.timestamp = msg->origin_server_ts; info.timestamp = msg->origin_server_ts;
info.descriptiveTime = utils::descriptiveTime(ts); info.descriptiveTime = utils::descriptiveTime(ts);
info.event_id = QString::fromStdString(msg->event_id); info.event_id = QString::fromStdString(msg->event_id);
@ -257,7 +257,7 @@ utils::firstChar(const QString &input)
return input; return input;
for (auto const &c : input.toStdU32String()) { for (auto const &c : input.toStdU32String()) {
if (QString::fromUcs4(&c, 1) != QString("#")) if (QString::fromUcs4(&c, 1) != QStringLiteral("#"))
return QString::fromUcs4(&c, 1).toUpper(); return QString::fromUcs4(&c, 1).toUpper();
} }
@ -326,7 +326,7 @@ utils::event_body(const mtx::events::collections::TimelineEvents &e)
if (auto ev = std::get_if<RoomEvent<msg::Video>>(&e); ev != nullptr) if (auto ev = std::get_if<RoomEvent<msg::Video>>(&e); ev != nullptr)
return QString::fromStdString(ev->content.body); return QString::fromStdString(ev->content.body);
return ""; return QString();
} }
QPixmap QPixmap
@ -371,7 +371,7 @@ utils::mxcToHttp(const QUrl &url, const QString &server, int port)
{ {
auto mxcParts = mtx::client::utils::parse_mxc_url(url.toString().toStdString()); auto mxcParts = mtx::client::utils::parse_mxc_url(url.toString().toStdString());
return QString("https://%1:%2/_matrix/media/r0/download/%3/%4") return QStringLiteral("https://%1:%2/_matrix/media/r0/download/%3/%4")
.arg(server) .arg(server)
.arg(port) .arg(port)
.arg(QString::fromStdString(mxcParts.server), QString::fromStdString(mxcParts.media_id)); .arg(QString::fromStdString(mxcParts.server), QString::fromStdString(mxcParts.media_id));
@ -402,7 +402,7 @@ utils::linkifyMessage(const QString &body)
// Convert to valid XML. // Convert to valid XML.
auto doc = body; auto doc = body;
doc.replace(conf::strings::url_regex, conf::strings::url_html); doc.replace(conf::strings::url_regex, conf::strings::url_html);
doc.replace(QRegularExpression("\\b(?<![\"'])(?>(matrix:[\\S]{5,}))(?![\"'])\\b"), doc.replace(QRegularExpression(QStringLiteral("\\b(?<![\"'])(?>(matrix:[\\S]{5,}))(?![\"'])\\b")),
conf::strings::url_html); conf::strings::url_html);
return doc; return doc;
@ -528,7 +528,7 @@ utils::markdownToHtml(const QString &text, bool rainbowify)
auto colorString = color.name(QColor::NameFormat::HexRgb); auto colorString = color.name(QColor::NameFormat::HexRgb);
// create HTML element for current char // create HTML element for current char
auto curCharColored = auto curCharColored =
QString("<font color=\"%0\">%1</font>").arg(colorString).arg(curChar); QStringLiteral("<font color=\"%0\">%1</font>").arg(colorString).arg(curChar);
// append colored HTML element to buffer // append colored HTML element to buffer
buf.append(curCharColored); buf.append(curCharColored);
} }
@ -555,7 +555,7 @@ utils::markdownToHtml(const QString &text, bool rainbowify)
auto result = linkifyMessage(escapeBlacklistedHtml(QString::fromStdString(html))).trimmed(); auto result = linkifyMessage(escapeBlacklistedHtml(QString::fromStdString(html))).trimmed();
if (result.count("<p>") == 1 && result.startsWith("<p>") && result.endsWith("</p>")) { if (result.count(QStringLiteral("<p>")) == 1 && result.startsWith(QLatin1String("<p>")) && result.endsWith(QLatin1String("</p>"))) {
result = result.mid(3, result.size() - 3 - 4); result = result.mid(3, result.size() - 3 - 4);
} }
@ -570,16 +570,16 @@ utils::getFormattedQuoteBody(const RelatedInfo &related, const QString &html)
switch (related.type) { switch (related.type) {
case MsgType::File: { case MsgType::File: {
return "sent a file."; return QStringLiteral("sent a file.");
} }
case MsgType::Image: { case MsgType::Image: {
return "sent an image."; return QStringLiteral("sent an image.");
} }
case MsgType::Audio: { case MsgType::Audio: {
return "sent an audio file."; return QStringLiteral("sent an audio file.");
} }
case MsgType::Video: { case MsgType::Video: {
return "sent a video"; return QStringLiteral("sent a video");
} }
default: { default: {
return related.quoted_formatted_body; return related.quoted_formatted_body;
@ -605,16 +605,16 @@ utils::getQuoteBody(const RelatedInfo &related)
switch (related.type) { switch (related.type) {
case MsgType::File: { case MsgType::File: {
return "sent a file."; return QStringLiteral("sent a file.");
} }
case MsgType::Image: { case MsgType::Image: {
return "sent an image."; return QStringLiteral("sent an image.");
} }
case MsgType::Audio: { case MsgType::Audio: {
return "sent an audio file."; return QStringLiteral("sent an audio file.");
} }
case MsgType::Video: { case MsgType::Video: {
return "sent a video"; return QStringLiteral("sent a video");
} }
default: { default: {
return related.quoted_body; return related.quoted_body;
@ -627,10 +627,10 @@ utils::linkColor()
{ {
const auto theme = UserSettings::instance()->theme(); const auto theme = UserSettings::instance()->theme();
if (theme == "light") { if (theme == QLatin1String("light")) {
return "#0077b5"; return QStringLiteral("#0077b5");
} else if (theme == "dark") { } else if (theme == QLatin1String("dark")) {
return "#38A3D8"; return QStringLiteral("#38A3D8");
} else { } else {
return QPalette().color(QPalette::Link).name(); return QPalette().color(QPalette::Link).name();
} }

View file

@ -115,7 +115,7 @@ PreviewUploadOverlay::init()
void void
PreviewUploadOverlay::setLabels(const QString &type, const QString &mime, uint64_t upload_size) PreviewUploadOverlay::setLabels(const QString &type, const QString &mime, uint64_t upload_size)
{ {
if (mediaType_.split('/')[0] == "image") { if (mediaType_.split('/')[0] == QLatin1String("image")) {
if (!image_.loadFromData(data_)) { if (!image_.loadFromData(data_)) {
titleLabel_.setText(QString{tr(ERR_MSG)}.arg(type)); titleLabel_.setText(QString{tr(ERR_MSG)}.arg(type));
} else { } else {
@ -127,7 +127,7 @@ PreviewUploadOverlay::setLabels(const QString &type, const QString &mime, uint64
"Media size: %2\n")} "Media size: %2\n")}
.arg(mime, utils::humanReadableFileSize(upload_size)); .arg(mime, utils::humanReadableFileSize(upload_size));
titleLabel_.setText(QString{tr(DEFAULT)}.arg("file")); titleLabel_.setText(QString{tr(DEFAULT)}.arg(QStringLiteral("file")));
infoLabel_.setText(info); infoLabel_.setText(info);
} }
} }
@ -144,7 +144,7 @@ PreviewUploadOverlay::setPreview(const QImage &src, const QString &mime)
QBuffer buffer(&data_); QBuffer buffer(&data_);
buffer.open(QIODevice::WriteOnly); buffer.open(QIODevice::WriteOnly);
if (src.save(&buffer, type.toStdString().c_str())) if (src.save(&buffer, type.toStdString().c_str()))
titleLabel_.setText(QString{tr(DEFAULT)}.arg("image")); titleLabel_.setText(QString{tr(DEFAULT)}.arg(QStringLiteral("image")));
else else
titleLabel_.setText(QString{tr(ERR_MSG)}.arg(type)); titleLabel_.setText(QString{tr(ERR_MSG)}.arg(type));
@ -153,7 +153,7 @@ PreviewUploadOverlay::setPreview(const QImage &src, const QString &mime)
image_.convertFromImage(src); image_.convertFromImage(src);
isImage_ = true; isImage_ = true;
titleLabel_.setText(QString{tr(DEFAULT)}.arg("image")); titleLabel_.setText(QString{tr(DEFAULT)}.arg(QStringLiteral("image")));
init(); init();
} }
@ -170,7 +170,7 @@ PreviewUploadOverlay::setPreview(const QByteArray data, const QString &mime)
filePath_ = "clipboard." + type; filePath_ = "clipboard." + type;
isImage_ = false; isImage_ = false;
if (mime == "image/svg+xml") { if (mime == QLatin1String("image/svg+xml")) {
isImage_ = true; isImage_ = true;
image_.loadFromData(data_, mediaType_.toStdString().c_str()); image_.loadFromData(data_, mediaType_.toStdString().c_str());
} }

View file

@ -429,23 +429,23 @@ DeviceVerificationFlow::state()
{ {
switch (state_) { switch (state_) {
case PromptStartVerification: case PromptStartVerification:
return "PromptStartVerification"; return QStringLiteral("PromptStartVerification");
case CompareEmoji: case CompareEmoji:
return "CompareEmoji"; return QStringLiteral("CompareEmoji");
case CompareNumber: case CompareNumber:
return "CompareNumber"; return QStringLiteral("CompareNumber");
case WaitingForKeys: case WaitingForKeys:
return "WaitingForKeys"; return QStringLiteral("WaitingForKeys");
case WaitingForOtherToAccept: case WaitingForOtherToAccept:
return "WaitingForOtherToAccept"; return QStringLiteral("WaitingForOtherToAccept");
case WaitingForMac: case WaitingForMac:
return "WaitingForMac"; return QStringLiteral("WaitingForMac");
case Success: case Success:
return "Success"; return QStringLiteral("Success");
case Failed: case Failed:
return "Failed"; return QStringLiteral("Failed");
default: default:
return ""; return QString();
} }
} }

View file

@ -211,8 +211,8 @@ SelfVerificationStatus::verifyMasterKey()
(void)sig; (void)sig;
auto d = QString::fromStdString(dev); auto d = QString::fromStdString(dev);
if (d.startsWith("ed25519:")) { if (d.startsWith(QLatin1String("ed25519:"))) {
d.remove("ed25519:"); d.remove(QStringLiteral("ed25519:"));
if (keys->device_keys.count(d.toStdString())) if (keys->device_keys.count(d.toStdString()))
devices.push_back(std::move(d)); devices.push_back(std::move(d));

View file

@ -124,9 +124,9 @@ createStandardDirectory(QStandardPaths::StandardLocation path)
int int
main(int argc, char *argv[]) main(int argc, char *argv[])
{ {
QCoreApplication::setApplicationName("nheko"); QCoreApplication::setApplicationName(QStringLiteral("nheko"));
QCoreApplication::setApplicationVersion(nheko::version); QCoreApplication::setApplicationVersion(nheko::version);
QCoreApplication::setOrganizationName("nheko"); QCoreApplication::setOrganizationName(QStringLiteral("nheko"));
QCoreApplication::setAttribute(Qt::AA_DontCreateNativeWidgetSiblings); QCoreApplication::setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
@ -144,24 +144,24 @@ main(int argc, char *argv[])
// This is some hacky programming, but it's necessary (AFAIK?) to get the unique config name // This is some hacky programming, but it's necessary (AFAIK?) to get the unique config name
// parsed before the SingleApplication userdata is set. // parsed before the SingleApplication userdata is set.
QString userdata{""}; QString userdata{QLatin1String("")};
QString matrixUri; QString matrixUri;
for (int i = 1; i < argc; ++i) { for (int i = 1; i < argc; ++i) {
QString arg{argv[i]}; QString arg{argv[i]};
if (arg.startsWith("--profile=")) { if (arg.startsWith(QLatin1String("--profile="))) {
arg.remove("--profile="); arg.remove(QStringLiteral("--profile="));
userdata = arg; userdata = arg;
} else if (arg.startsWith("--p=")) { } else if (arg.startsWith(QLatin1String("--p="))) {
arg.remove("-p="); arg.remove(QStringLiteral("-p="));
userdata = arg; userdata = arg;
} else if (arg == "--profile" || arg == "-p") { } else if (arg == QLatin1String("--profile") || arg == QLatin1String("-p")) {
if (i < argc - 1) // if i is less than argc - 1, we still have a parameter if (i < argc - 1) // if i is less than argc - 1, we still have a parameter
// left to process as the name // left to process as the name
{ {
++i; // the next arg is the name, so increment ++i; // the next arg is the name, so increment
userdata = QString{argv[i]}; userdata = QString{argv[i]};
} }
} else if (arg.startsWith("matrix:")) { } else if (arg.startsWith(QLatin1String("matrix:"))) {
matrixUri = arg; matrixUri = arg;
} }
} }
@ -173,20 +173,20 @@ main(int argc, char *argv[])
SingleApplication::Mode::ExcludeAppVersion | SingleApplication::Mode::ExcludeAppVersion |
SingleApplication::Mode::SecondaryNotification, SingleApplication::Mode::SecondaryNotification,
100, 100,
userdata == "default" ? "" : userdata); userdata == QLatin1String("default") ? QLatin1String("") : userdata);
QCommandLineParser parser; QCommandLineParser parser;
parser.addHelpOption(); parser.addHelpOption();
parser.addVersionOption(); parser.addVersionOption();
QCommandLineOption debugOption("debug", "Enable debug output"); QCommandLineOption debugOption(QStringLiteral("debug"), QStringLiteral("Enable debug output"));
parser.addOption(debugOption); parser.addOption(debugOption);
// This option is not actually parsed via Qt due to the need to parse it before the app // This option is not actually parsed via Qt due to the need to parse it before the app
// name is set. It only exists to keep Qt from complaining about the --profile/-p // name is set. It only exists to keep Qt from complaining about the --profile/-p
// option and thereby crashing the app. // option and thereby crashing the app.
QCommandLineOption configName( QCommandLineOption configName(
QStringList() << "p" QStringList() << QStringLiteral("p")
<< "profile", << QStringLiteral("profile"),
QCoreApplication::tr("Create a unique profile, which allows you to log into several " QCoreApplication::tr("Create a unique profile, which allows you to log into several "
"accounts at the same time and start multiple instances of nheko."), "accounts at the same time and start multiple instances of nheko."),
QCoreApplication::tr("profile"), QCoreApplication::tr("profile"),
@ -206,10 +206,10 @@ main(int argc, char *argv[])
} }
#if !defined(Q_OS_MAC) #if !defined(Q_OS_MAC)
app.setWindowIcon(QIcon::fromTheme("nheko", QIcon{":/logos/nheko.png"})); app.setWindowIcon(QIcon::fromTheme(QStringLiteral("nheko"), QIcon{":/logos/nheko.png"}));
#endif #endif
if (userdata.isEmpty() || userdata == "default") if (userdata.isEmpty() || userdata == QLatin1String("default"))
app.setDesktopFileName("nheko"); app.setDesktopFileName(QStringLiteral("nheko"));
else else
app.setDesktopFileName("nheko[" + userdata + "]"); app.setDesktopFileName("nheko[" + userdata + "]");
@ -224,7 +224,7 @@ main(int argc, char *argv[])
nhlog::enable_debug_log_from_commandline = true; nhlog::enable_debug_log_from_commandline = true;
try { try {
nhlog::init(QString("%1/nheko.log") nhlog::init(QStringLiteral("%1/nheko.log")
.arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)) .arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation))
.toStdString()); .toStdString());
} catch (const spdlog::spdlog_ex &ex) { } catch (const spdlog::spdlog_ex &ex) {
@ -241,7 +241,7 @@ main(int argc, char *argv[])
QFont font; QFont font;
QString userFontFamily = settings.lock()->font(); QString userFontFamily = settings.lock()->font();
if (!userFontFamily.isEmpty() && userFontFamily != "default") { if (!userFontFamily.isEmpty() && userFontFamily != QLatin1String("default")) {
font.setFamily(userFontFamily); font.setFamily(userFontFamily);
} }
font.setPointSizeF(settings.lock()->fontSize()); font.setPointSizeF(settings.lock()->fontSize());
@ -252,11 +252,11 @@ main(int argc, char *argv[])
QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedKingdom)); QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedKingdom));
QTranslator qtTranslator; QTranslator qtTranslator;
qtTranslator.load(QLocale(), "qt", "_", QLibraryInfo::location(QLibraryInfo::TranslationsPath)); qtTranslator.load(QLocale(), QStringLiteral("qt"), QStringLiteral("_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
app.installTranslator(&qtTranslator); app.installTranslator(&qtTranslator);
QTranslator appTranslator; QTranslator appTranslator;
appTranslator.load(QLocale(), "nheko", "_", ":/translations"); appTranslator.load(QLocale(), QStringLiteral("nheko"), QStringLiteral("_"), QStringLiteral(":/translations"));
app.installTranslator(&appTranslator); app.installTranslator(&appTranslator);
MainWindow w; MainWindow w;
@ -304,7 +304,7 @@ main(int argc, char *argv[])
QObject::disconnect(uriConnection); QObject::disconnect(uriConnection);
}); });
} }
QDesktopServices::setUrlHandler("matrix", ChatPage::instance(), "handleMatrixUri"); QDesktopServices::setUrlHandler(QStringLiteral("matrix"), ChatPage::instance(), "handleMatrixUri");
#if defined(Q_OS_MAC) #if defined(Q_OS_MAC)
// Temporary solution for the emoji picker until // Temporary solution for the emoji picker until

View file

@ -23,12 +23,12 @@ NotificationsManager::getMessageTemplate(const mtx::responses::Notification &not
} }
if (mtx::accessors::msg_type(notification.event) == mtx::events::MessageType::Emote) { if (mtx::accessors::msg_type(notification.event) == mtx::events::MessageType::Emote) {
return QString("* %1 %2").arg(sender); return QStringLiteral("* %1 %2").arg(sender);
} else if (utils::isReply(notification.event)) { } else if (utils::isReply(notification.event)) {
return tr("%1 replied: %2", return tr("%1 replied: %2",
"Format a reply in a notification. %1 is the sender, %2 the message") "Format a reply in a notification. %1 is the sender, %2 the message")
.arg(sender); .arg(sender);
} else { } else {
return QString("%1: %2").arg(sender); return QStringLiteral("%1: %2").arg(sender);
} }
} }

View file

@ -28,9 +28,9 @@
NotificationsManager::NotificationsManager(QObject *parent) NotificationsManager::NotificationsManager(QObject *parent)
: QObject(parent) : QObject(parent)
, dbus("org.freedesktop.Notifications", , dbus(QStringLiteral("org.freedesktop.Notifications"),
"/org/freedesktop/Notifications", QStringLiteral("/org/freedesktop/Notifications"),
"org.freedesktop.Notifications", QStringLiteral("org.freedesktop.Notifications"),
QDBusConnection::sessionBus(), QDBusConnection::sessionBus(),
this) this)
, hasMarkup_{std::invoke([this]() -> bool { , hasMarkup_{std::invoke([this]() -> bool {
@ -51,22 +51,22 @@ NotificationsManager::NotificationsManager(QObject *parent)
qDBusRegisterMetaType<QImage>(); qDBusRegisterMetaType<QImage>();
// clang-format off // clang-format off
QDBusConnection::sessionBus().connect("org.freedesktop.Notifications", QDBusConnection::sessionBus().connect(QStringLiteral("org.freedesktop.Notifications"),
"/org/freedesktop/Notifications", QStringLiteral("/org/freedesktop/Notifications"),
"org.freedesktop.Notifications", QStringLiteral("org.freedesktop.Notifications"),
"ActionInvoked", QStringLiteral("ActionInvoked"),
this, this,
SLOT(actionInvoked(uint,QString))); SLOT(actionInvoked(uint,QString)));
QDBusConnection::sessionBus().connect("org.freedesktop.Notifications", QDBusConnection::sessionBus().connect(QStringLiteral("org.freedesktop.Notifications"),
"/org/freedesktop/Notifications", QStringLiteral("/org/freedesktop/Notifications"),
"org.freedesktop.Notifications", QStringLiteral("org.freedesktop.Notifications"),
"NotificationClosed", QStringLiteral("NotificationClosed"),
this, this,
SLOT(notificationClosed(uint,uint))); SLOT(notificationClosed(uint,uint)));
QDBusConnection::sessionBus().connect("org.freedesktop.Notifications", QDBusConnection::sessionBus().connect(QStringLiteral("org.freedesktop.Notifications"),
"/org/freedesktop/Notifications", QStringLiteral("/org/freedesktop/Notifications"),
"org.freedesktop.Notifications", QStringLiteral("org.freedesktop.Notifications"),
"NotificationReplied", QStringLiteral("NotificationReplied"),
this, this,
SLOT(notificationReplied(uint,QString))); SLOT(notificationReplied(uint,QString)));
// clang-format on // clang-format on
@ -108,17 +108,17 @@ NotificationsManager::postNotification(const mtx::responses::Notification &notif
if (hasImages_ && if (hasImages_ &&
mtx::accessors::msg_type(notification.event) == mtx::events::MessageType::Image) { mtx::accessors::msg_type(notification.event) == mtx::events::MessageType::Image) {
MxcImageProvider::download( MxcImageProvider::download(
QString::fromStdString(mtx::accessors::url(notification.event)).remove("mxc://"), QString::fromStdString(mtx::accessors::url(notification.event)).remove(QStringLiteral("mxc://")),
QSize(200, 80), QSize(200, 80),
[postNotif, notification, template_](QString, QSize, QImage, QString imgPath) { [postNotif, notification, template_](QString, QSize, QImage, QString imgPath) {
if (imgPath.isEmpty()) if (imgPath.isEmpty())
postNotif(template_ postNotif(template_
.arg(utils::stripReplyFallbacks(notification.event, {}, {}) .arg(utils::stripReplyFallbacks(notification.event, {}, {})
.quoted_formatted_body) .quoted_formatted_body)
.replace("<em>", "<i>") .replace(QLatin1String("<em>"), QLatin1String("<i>"))
.replace("</em>", "</i>") .replace(QLatin1String("</em>"), QLatin1String("</i>"))
.replace("<strong>", "<b>") .replace(QLatin1String("<strong>"), QLatin1String("<b>"))
.replace("</strong>", "</b>")); .replace(QLatin1String("</strong>"), QLatin1String("</b>")));
else else
postNotif(template_.arg( postNotif(template_.arg(
QStringLiteral("<br><img src=\"file:///") % imgPath % "\" alt=\"" % QStringLiteral("<br><img src=\"file:///") % imgPath % "\" alt=\"" %
@ -130,10 +130,10 @@ NotificationsManager::postNotification(const mtx::responses::Notification &notif
postNotif( postNotif(
template_ template_
.arg(utils::stripReplyFallbacks(notification.event, {}, {}).quoted_formatted_body) .arg(utils::stripReplyFallbacks(notification.event, {}, {}).quoted_formatted_body)
.replace("<em>", "<i>") .replace(QLatin1String("<em>"), QLatin1String("<i>"))
.replace("</em>", "</i>") .replace(QLatin1String("</em>"), QLatin1String("</i>"))
.replace("<strong>", "<b>") .replace(QLatin1String("<strong>"), QLatin1String("<b>"))
.replace("</strong>", "</b>")); .replace(QLatin1String("</strong>"), QLatin1String("</b>")));
return; return;
} }
@ -154,10 +154,10 @@ NotificationsManager::systemPostNotification(const QString &room_id,
const QImage &icon) const QImage &icon)
{ {
QVariantMap hints; QVariantMap hints;
hints["image-data"] = icon; hints[QStringLiteral("image-data")] = icon;
hints["sound-name"] = "message-new-instant"; hints[QStringLiteral("sound-name")] = "message-new-instant";
hints["desktop-entry"] = "nheko"; hints[QStringLiteral("desktop-entry")] = "nheko";
hints["category"] = "im.received"; hints[QStringLiteral("category")] = "im.received";
uint replace_id = 0; uint replace_id = 0;
if (!event_id.isEmpty()) { if (!event_id.isEmpty()) {
@ -182,13 +182,13 @@ NotificationsManager::systemPostNotification(const QString &room_id,
// The list of actions has always the action name and then a localized version of that // The list of actions has always the action name and then a localized version of that
// action. Currently we just use an empty string for that. // action. Currently we just use an empty string for that.
// TODO(Nico): Look into what to actually put there. // TODO(Nico): Look into what to actually put there.
argumentList << (QStringList("default") << "" argumentList << (QStringList(QStringLiteral("default"))
<< "inline-reply" << QLatin1String("") << QStringLiteral("inline-reply")
<< ""); // actions << QLatin1String("")); // actions
argumentList << hints; // hints argumentList << hints; // hints
argumentList << (int)-1; // timeout in ms argumentList << (int)-1; // timeout in ms
QDBusPendingCall call = dbus.asyncCallWithArgumentList("Notify", argumentList); QDBusPendingCall call = dbus.asyncCallWithArgumentList(QStringLiteral("Notify"), argumentList);
auto watcher = new QDBusPendingCallWatcher{call, this}; auto watcher = new QDBusPendingCallWatcher{call, this};
connect( connect(
watcher, &QDBusPendingCallWatcher::finished, this, [watcher, this, room_id, event_id]() { watcher, &QDBusPendingCallWatcher::finished, this, [watcher, this, room_id, event_id]() {
@ -204,7 +204,7 @@ NotificationsManager::systemPostNotification(const QString &room_id,
void void
NotificationsManager::closeNotification(uint id) NotificationsManager::closeNotification(uint id)
{ {
auto call = dbus.asyncCall("CloseNotification", (uint)id); // replace_id auto call = dbus.asyncCall(QStringLiteral("CloseNotification"), (uint)id); // replace_id
auto watcher = new QDBusPendingCallWatcher{call, this}; auto watcher = new QDBusPendingCallWatcher{call, this};
connect(watcher, &QDBusPendingCallWatcher::finished, this, [watcher]() { connect(watcher, &QDBusPendingCallWatcher::finished, this, [watcher]() {
if (watcher->reply().type() == QDBusMessage::ErrorMessage) { if (watcher->reply().type() == QDBusMessage::ErrorMessage) {
@ -242,7 +242,7 @@ NotificationsManager::actionInvoked(uint id, QString action)
{ {
if (notificationIds.contains(id)) { if (notificationIds.contains(id)) {
roomEventId idEntry = notificationIds[id]; roomEventId idEntry = notificationIds[id];
if (action == "default") { if (action == QLatin1String("default")) {
emit notificationClicked(idEntry.roomId, idEntry.eventId); emit notificationClicked(idEntry.roomId, idEntry.eventId);
} }
} }

View file

@ -52,7 +52,7 @@ CommunitiesModel::data(const QModelIndex &index, int role) const
if (index.row() == 0) { if (index.row() == 0) {
switch (role) { switch (role) {
case CommunitiesModel::Roles::AvatarUrl: case CommunitiesModel::Roles::AvatarUrl:
return QString(":/icons/icons/ui/world.svg"); return QStringLiteral(":/icons/icons/ui/world.svg");
case CommunitiesModel::Roles::DisplayName: case CommunitiesModel::Roles::DisplayName:
return tr("All rooms"); return tr("All rooms");
case CommunitiesModel::Roles::Tooltip: case CommunitiesModel::Roles::Tooltip:
@ -73,7 +73,7 @@ CommunitiesModel::data(const QModelIndex &index, int role) const
} else if (index.row() == 1) { } else if (index.row() == 1) {
switch (role) { switch (role) {
case CommunitiesModel::Roles::AvatarUrl: case CommunitiesModel::Roles::AvatarUrl:
return QString(":/icons/icons/ui/people.svg"); return QStringLiteral(":/icons/icons/ui/people.svg");
case CommunitiesModel::Roles::DisplayName: case CommunitiesModel::Roles::DisplayName:
return tr("Direct Chats"); return tr("Direct Chats");
case CommunitiesModel::Roles::Tooltip: case CommunitiesModel::Roles::Tooltip:
@ -83,7 +83,7 @@ CommunitiesModel::data(const QModelIndex &index, int role) const
case CommunitiesModel::Roles::Collapsible: case CommunitiesModel::Roles::Collapsible:
return false; return false;
case CommunitiesModel::Roles::Hidden: case CommunitiesModel::Roles::Hidden:
return hiddentTagIds_.contains("dm"); return hiddentTagIds_.contains(QStringLiteral("dm"));
case CommunitiesModel::Roles::Parent: case CommunitiesModel::Roles::Parent:
return ""; return "";
case CommunitiesModel::Roles::Depth: case CommunitiesModel::Roles::Depth:
@ -120,28 +120,28 @@ CommunitiesModel::data(const QModelIndex &index, int role) const
} }
} else if (index.row() - 2 < tags_.size() + spaceOrder_.size()) { } else if (index.row() - 2 < tags_.size() + spaceOrder_.size()) {
auto tag = tags_.at(index.row() - 2 - spaceOrder_.size()); auto tag = tags_.at(index.row() - 2 - spaceOrder_.size());
if (tag == "m.favourite") { if (tag == QLatin1String("m.favourite")) {
switch (role) { switch (role) {
case CommunitiesModel::Roles::AvatarUrl: case CommunitiesModel::Roles::AvatarUrl:
return QString(":/icons/icons/ui/star.svg"); return QStringLiteral(":/icons/icons/ui/star.svg");
case CommunitiesModel::Roles::DisplayName: case CommunitiesModel::Roles::DisplayName:
return tr("Favourites"); return tr("Favourites");
case CommunitiesModel::Roles::Tooltip: case CommunitiesModel::Roles::Tooltip:
return tr("Rooms you have favourited."); return tr("Rooms you have favourited.");
} }
} else if (tag == "m.lowpriority") { } else if (tag == QLatin1String("m.lowpriority")) {
switch (role) { switch (role) {
case CommunitiesModel::Roles::AvatarUrl: case CommunitiesModel::Roles::AvatarUrl:
return QString(":/icons/icons/ui/lowprio.svg"); return QStringLiteral(":/icons/icons/ui/lowprio.svg");
case CommunitiesModel::Roles::DisplayName: case CommunitiesModel::Roles::DisplayName:
return tr("Low Priority"); return tr("Low Priority");
case CommunitiesModel::Roles::Tooltip: case CommunitiesModel::Roles::Tooltip:
return tr("Rooms with low priority."); return tr("Rooms with low priority.");
} }
} else if (tag == "m.server_notice") { } else if (tag == QLatin1String("m.server_notice")) {
switch (role) { switch (role) {
case CommunitiesModel::Roles::AvatarUrl: case CommunitiesModel::Roles::AvatarUrl:
return QString(":/icons/icons/ui/tag.svg"); return QStringLiteral(":/icons/icons/ui/tag.svg");
case CommunitiesModel::Roles::DisplayName: case CommunitiesModel::Roles::DisplayName:
return tr("Server Notices"); return tr("Server Notices");
case CommunitiesModel::Roles::Tooltip: case CommunitiesModel::Roles::Tooltip:
@ -150,7 +150,7 @@ CommunitiesModel::data(const QModelIndex &index, int role) const
} else { } else {
switch (role) { switch (role) {
case CommunitiesModel::Roles::AvatarUrl: case CommunitiesModel::Roles::AvatarUrl:
return QString(":/icons/icons/ui/tag.svg"); return QStringLiteral(":/icons/icons/ui/tag.svg");
case CommunitiesModel::Roles::DisplayName: case CommunitiesModel::Roles::DisplayName:
case CommunitiesModel::Roles::Tooltip: case CommunitiesModel::Roles::Tooltip:
return tag.mid(2); return tag.mid(2);
@ -392,7 +392,7 @@ CommunitiesModel::sync(const mtx::responses::Sync &sync_)
void void
CommunitiesModel::setCurrentTagId(QString tagId) CommunitiesModel::setCurrentTagId(QString tagId)
{ {
if (tagId.startsWith("tag:")) { if (tagId.startsWith(QLatin1String("tag:"))) {
auto tag = tagId.mid(4); auto tag = tagId.mid(4);
for (const auto &t : qAsConst(tags_)) { for (const auto &t : qAsConst(tags_)) {
if (t == tag) { if (t == tag) {
@ -401,7 +401,7 @@ CommunitiesModel::setCurrentTagId(QString tagId)
return; return;
} }
} }
} else if (tagId.startsWith("space:")) { } else if (tagId.startsWith(QLatin1String("space:"))) {
auto tag = tagId.mid(6); auto tag = tagId.mid(6);
for (const auto &t : spaceOrder_.tree) { for (const auto &t : spaceOrder_.tree) {
if (t.name == tag) { if (t.name == tag) {
@ -410,13 +410,13 @@ CommunitiesModel::setCurrentTagId(QString tagId)
return; return;
} }
} }
} else if (tagId == "dm") { } else if (tagId == QLatin1String("dm")) {
this->currentTagId_ = tagId; this->currentTagId_ = tagId;
emit currentTagIdChanged(currentTagId_); emit currentTagIdChanged(currentTagId_);
return; return;
} }
this->currentTagId_ = ""; this->currentTagId_ = QLatin1String("");
emit currentTagIdChanged(currentTagId_); emit currentTagIdChanged(currentTagId_);
} }
@ -431,16 +431,16 @@ CommunitiesModel::toggleTagId(QString tagId)
UserSettings::instance()->setHiddenTags(hiddentTagIds_); UserSettings::instance()->setHiddenTags(hiddentTagIds_);
} }
if (tagId.startsWith("tag:")) { if (tagId.startsWith(QLatin1String("tag:"))) {
auto idx = tags_.indexOf(tagId.mid(4)); auto idx = tags_.indexOf(tagId.mid(4));
if (idx != -1) if (idx != -1)
emit dataChanged( emit dataChanged(
index(idx + 1 + spaceOrder_.size()), index(idx + 1 + spaceOrder_.size()), {Hidden}); index(idx + 1 + spaceOrder_.size()), index(idx + 1 + spaceOrder_.size()), {Hidden});
} else if (tagId.startsWith("space:")) { } else if (tagId.startsWith(QLatin1String("space:"))) {
auto idx = spaceOrder_.indexOf(tagId.mid(6)); auto idx = spaceOrder_.indexOf(tagId.mid(6));
if (idx != -1) if (idx != -1)
emit dataChanged(index(idx + 1), index(idx + 1), {Hidden}); emit dataChanged(index(idx + 1), index(idx + 1), {Hidden});
} else if (tagId == "dm") { } else if (tagId == QLatin1String("dm")) {
emit dataChanged(index(1), index(1), {Hidden}); emit dataChanged(index(1), index(1), {Hidden});
} }
@ -472,15 +472,15 @@ tagIdToCat(QString tagId)
{ {
if (tagId.isEmpty()) if (tagId.isEmpty())
return World; return World;
else if (tagId == "dm") else if (tagId == QLatin1String("dm"))
return Direct; return Direct;
else if (tagId == "tag:m.favourite") else if (tagId == QLatin1String("tag:m.favourite"))
return Favourites; return Favourites;
else if (tagId == "tag:m.server_notice") else if (tagId == QLatin1String("tag:m.server_notice"))
return Server; return Server;
else if (tagId == "tag:m.lowpriority") else if (tagId == QLatin1String("tag:m.lowpriority"))
return LowPrio; return LowPrio;
else if (tagId.startsWith("space:")) else if (tagId.startsWith(QLatin1String("space:")))
return Space; return Space;
else else
return UserTag; return UserTag;

View file

@ -130,9 +130,9 @@ public slots:
QStringList tagsWithDefault() const QStringList tagsWithDefault() const
{ {
QStringList tagsWD = tags_; QStringList tagsWD = tags_;
tagsWD.prepend("m.lowpriority"); tagsWD.prepend(QStringLiteral("m.lowpriority"));
tagsWD.prepend("m.favourite"); tagsWD.prepend(QStringLiteral("m.favourite"));
tagsWD.removeOne("m.server_notice"); tagsWD.removeOne(QStringLiteral("m.server_notice"));
tagsWD.removeDuplicates(); tagsWD.removeDuplicates();
return tagsWD; return tagsWD;
} }

View file

@ -537,7 +537,7 @@ EventStore::reactions(const std::string &event_id)
if (firstReaction) if (firstReaction)
firstReaction = false; firstReaction = false;
else else
reaction.users_ += ", "; reaction.users_ += QLatin1String(", ");
reaction.users_ += QString::fromStdString(user); reaction.users_ += QString::fromStdString(user);
} }

View file

@ -56,22 +56,22 @@ InputBar::insertMimeData(const QMimeData *md)
if (!md) if (!md)
return; return;
nhlog::ui()->debug("Got mime formats: {}", md->formats().join(", ").toStdString()); nhlog::ui()->debug("Got mime formats: {}", md->formats().join(QStringLiteral(", ")).toStdString());
const auto formats = md->formats().filter("/"); const auto formats = md->formats().filter(QStringLiteral("/"));
const auto image = formats.filter("image/", Qt::CaseInsensitive); const auto image = formats.filter(QStringLiteral("image/"), Qt::CaseInsensitive);
const auto audio = formats.filter("audio/", Qt::CaseInsensitive); const auto audio = formats.filter(QStringLiteral("audio/"), Qt::CaseInsensitive);
const auto video = formats.filter("video/", Qt::CaseInsensitive); const auto video = formats.filter(QStringLiteral("video/"), Qt::CaseInsensitive);
if (md->hasImage()) { if (md->hasImage()) {
if (formats.contains("image/svg+xml", Qt::CaseInsensitive)) { if (formats.contains(QStringLiteral("image/svg+xml"), Qt::CaseInsensitive)) {
showPreview(*md, "", QStringList("image/svg+xml")); showPreview(*md, QLatin1String(""), QStringList(QStringLiteral("image/svg+xml")));
} else { } else {
showPreview(*md, "", image); showPreview(*md, QLatin1String(""), image);
} }
} else if (!audio.empty()) { } else if (!audio.empty()) {
showPreview(*md, "", audio); showPreview(*md, QLatin1String(""), audio);
} else if (!video.empty()) { } else if (!video.empty()) {
showPreview(*md, "", video); showPreview(*md, QLatin1String(""), video);
} else if (md->hasUrls()) { } else if (md->hasUrls()) {
// Generic file path for any platform. // Generic file path for any platform.
QString path; QString path;
@ -87,7 +87,7 @@ InputBar::insertMimeData(const QMimeData *md)
} else { } else {
nhlog::ui()->warn("Clipboard does not contain any valid file paths."); nhlog::ui()->warn("Clipboard does not contain any valid file paths.");
} }
} else if (md->hasFormat("x-special/gnome-copied-files")) { } else if (md->hasFormat(QStringLiteral("x-special/gnome-copied-files"))) {
// Special case for X11 users. See "Notes for X11 Users" in md. // Special case for X11 users. See "Notes for X11 Users" in md.
// Source: http://doc.qt.io/qt-5/qclipboard.html // Source: http://doc.qt.io/qt-5/qclipboard.html
@ -99,7 +99,7 @@ InputBar::insertMimeData(const QMimeData *md)
// nautilus_clipboard_get_uri_list_from_selection_data() // nautilus_clipboard_get_uri_list_from_selection_data()
// https://github.com/GNOME/nautilus/blob/master/src/nautilus-clipboard.c // https://github.com/GNOME/nautilus/blob/master/src/nautilus-clipboard.c
auto data = md->data("x-special/gnome-copied-files").split('\n'); auto data = md->data(QStringLiteral("x-special/gnome-copied-files")).split('\n');
if (data.size() < 2) { if (data.size() < 2) {
nhlog::ui()->warn("MIME format is malformed, cannot perform paste."); nhlog::ui()->warn("MIME format is malformed, cannot perform paste.");
return; return;
@ -123,7 +123,7 @@ InputBar::insertMimeData(const QMimeData *md)
} else if (md->hasText()) { } else if (md->hasText()) {
emit insertText(md->text()); emit insertText(md->text());
} else { } else {
nhlog::ui()->debug("formats: {}", md->formats().join(", ").toStdString()); nhlog::ui()->debug("formats: {}", md->formats().join(QStringLiteral(", ")).toStdString());
} }
} }
@ -140,7 +140,7 @@ InputBar::updateAtRoom(const QString &t)
auto start = finder.position(); auto start = finder.position();
finder.toNextBoundary(); finder.toNextBoundary();
auto end = finder.position(); auto end = finder.position();
if (start > 0 && end - start >= 4 && t.mid(start, end - start) == "room" && if (start > 0 && end - start >= 4 && t.mid(start, end - start) == QLatin1String("room") &&
t.at(start - 1) == QChar('@')) { t.at(start - 1) == QChar('@')) {
roomMention = true; roomMention = true;
break; break;
@ -166,7 +166,7 @@ InputBar::setText(const QString &newText)
if (history_.size() == INPUT_HISTORY_SIZE) if (history_.size() == INPUT_HISTORY_SIZE)
history_.pop_back(); history_.pop_back();
updateAtRoom(""); updateAtRoom(QLatin1String(""));
emit textChanged(newText); emit textChanged(newText);
} }
void void
@ -201,7 +201,7 @@ InputBar::text() const
if (history_index_ < history_.size()) if (history_index_ < history_.size())
return history_.at(history_index_); return history_.at(history_index_);
return ""; return QString();
} }
QString QString
@ -239,12 +239,12 @@ InputBar::send()
auto wasEdit = !room->edit().isEmpty(); auto wasEdit = !room->edit().isEmpty();
if (text().startsWith('/')) { if (text().startsWith('/')) {
int command_end = text().indexOf(QRegularExpression("\\s")); int command_end = text().indexOf(QRegularExpression(QStringLiteral("\\s")));
if (command_end == -1) if (command_end == -1)
command_end = text().size(); command_end = text().size();
auto name = text().mid(1, command_end - 1); auto name = text().mid(1, command_end - 1);
auto args = text().mid(command_end + 1); auto args = text().mid(command_end + 1);
if (name.isEmpty() || name == "/") { if (name.isEmpty() || name == QLatin1String("/")) {
message(args); message(args);
} else { } else {
command(name, args); command(name, args);
@ -254,8 +254,8 @@ InputBar::send()
} }
if (!wasEdit) { if (!wasEdit) {
history_.push_front(""); history_.push_front(QLatin1String(""));
setText(""); setText(QLatin1String(""));
} }
} }
@ -276,7 +276,7 @@ InputBar::openFileSelection()
if (!file.open(QIODevice::ReadOnly)) { if (!file.open(QIODevice::ReadOnly)) {
emit ChatPage::instance()->showNotification( emit ChatPage::instance()->showNotification(
QString("Error while reading media: %1").arg(file.errorString())); QStringLiteral("Error while reading media: %1").arg(file.errorString()));
return; return;
} }
@ -328,13 +328,13 @@ InputBar::message(const QString &msg, MarkdownOverride useMarkdown, bool rainbow
for (auto line : qAsConst(lines)) { for (auto line : qAsConst(lines)) {
if (firstLine) { if (firstLine) {
firstLine = false; firstLine = false;
body = QString("> <%1> %2\n").arg(related.quoted_user, line); body = QStringLiteral("> <%1> %2\n").arg(related.quoted_user, line);
} else { } else {
body += QString("> %1\n").arg(line); body += QStringLiteral("> %1\n").arg(line);
} }
} }
text.body = QString("%1\n%2").arg(body, msg).toStdString(); text.body = QStringLiteral("%1\n%2").arg(body, msg).toStdString();
// NOTE(Nico): rich replies always need a formatted_body! // NOTE(Nico): rich replies always need a formatted_body!
text.format = "org.matrix.custom.html"; text.format = "org.matrix.custom.html";
@ -568,25 +568,25 @@ InputBar::sticker(CombinedImagePackModel *model, int row)
void void
InputBar::command(const QString &command, QString args) InputBar::command(const QString &command, QString args)
{ {
if (command == "me") { if (command == QLatin1String("me")) {
emote(args, false); emote(args, false);
} else if (command == "react") { } else if (command == QLatin1String("react")) {
auto eventId = room->reply(); auto eventId = room->reply();
if (!eventId.isEmpty()) if (!eventId.isEmpty())
reaction(eventId, args.trimmed()); reaction(eventId, args.trimmed());
} else if (command == "join") { } else if (command == QLatin1String("join")) {
ChatPage::instance()->joinRoom(args); ChatPage::instance()->joinRoom(args);
} else if (command == "part" || command == "leave") { } else if (command == QLatin1String("part") || command == QLatin1String("leave")) {
ChatPage::instance()->timelineManager()->openLeaveRoomDialog(room->roomId()); ChatPage::instance()->timelineManager()->openLeaveRoomDialog(room->roomId());
} else if (command == "invite") { } else if (command == QLatin1String("invite")) {
ChatPage::instance()->inviteUser(args.section(' ', 0, 0), args.section(' ', 1, -1)); ChatPage::instance()->inviteUser(args.section(' ', 0, 0), args.section(' ', 1, -1));
} else if (command == "kick") { } else if (command == QLatin1String("kick")) {
ChatPage::instance()->kickUser(args.section(' ', 0, 0), args.section(' ', 1, -1)); ChatPage::instance()->kickUser(args.section(' ', 0, 0), args.section(' ', 1, -1));
} else if (command == "ban") { } else if (command == QLatin1String("ban")) {
ChatPage::instance()->banUser(args.section(' ', 0, 0), args.section(' ', 1, -1)); ChatPage::instance()->banUser(args.section(' ', 0, 0), args.section(' ', 1, -1));
} else if (command == "unban") { } else if (command == QLatin1String("unban")) {
ChatPage::instance()->unbanUser(args.section(' ', 0, 0), args.section(' ', 1, -1)); ChatPage::instance()->unbanUser(args.section(' ', 0, 0), args.section(' ', 1, -1));
} else if (command == "roomnick") { } else if (command == QLatin1String("roomnick")) {
mtx::events::state::Member member; mtx::events::state::Member member;
member.display_name = args.toStdString(); member.display_name = args.toStdString();
member.avatar_url = member.avatar_url =
@ -604,31 +604,31 @@ InputBar::command(const QString &command, QString args)
nhlog::net()->error("Failed to set room displayname: {}", nhlog::net()->error("Failed to set room displayname: {}",
err->matrix_error.error); err->matrix_error.error);
}); });
} else if (command == "shrug") { } else if (command == QLatin1String("shrug")) {
message("¯\\_(ツ)_/¯" + (args.isEmpty() ? "" : " " + args)); message("¯\\_(ツ)_/¯" + (args.isEmpty() ? QLatin1String("") : " " + args));
} else if (command == "fliptable") { } else if (command == QLatin1String("fliptable")) {
message("(╯°□°)╯︵ ┻━┻"); message(QStringLiteral("(╯°□°)╯︵ ┻━┻"));
} else if (command == "unfliptable") { } else if (command == QLatin1String("unfliptable")) {
message(" ┯━┯╭( º _ º╭)"); message(QStringLiteral(" ┯━┯╭( º _ º╭)"));
} else if (command == "sovietflip") { } else if (command == QLatin1String("sovietflip")) {
message("ノ┬─┬ノ ︵ ( \\o°o)\\"); message(QStringLiteral("ノ┬─┬ノ ︵ ( \\o°o)\\"));
} else if (command == "clear-timeline") { } else if (command == QLatin1String("clear-timeline")) {
room->clearTimeline(); room->clearTimeline();
} else if (command == "rotate-megolm-session") { } else if (command == QLatin1String("rotate-megolm-session")) {
cache::dropOutboundMegolmSession(room->roomId().toStdString()); cache::dropOutboundMegolmSession(room->roomId().toStdString());
} else if (command == "md") { } else if (command == QLatin1String("md")) {
message(args, MarkdownOverride::ON); message(args, MarkdownOverride::ON);
} else if (command == "plain") { } else if (command == QLatin1String("plain")) {
message(args, MarkdownOverride::OFF); message(args, MarkdownOverride::OFF);
} else if (command == "rainbow") { } else if (command == QLatin1String("rainbow")) {
message(args, MarkdownOverride::ON, true); message(args, MarkdownOverride::ON, true);
} else if (command == "rainbowme") { } else if (command == QLatin1String("rainbowme")) {
emote(args, true); emote(args, true);
} else if (command == "notice") { } else if (command == QLatin1String("notice")) {
notice(args, false); notice(args, false);
} else if (command == "rainbownotice") { } else if (command == QLatin1String("rainbownotice")) {
notice(args, true); notice(args, true);
} else if (command == "goto") { } else if (command == QLatin1String("goto")) {
// Goto has three different modes: // Goto has three different modes:
// 1 - Going directly to a given event ID // 1 - Going directly to a given event ID
if (args[0] == '$') { if (args[0] == '$') {
@ -645,10 +645,10 @@ InputBar::command(const QString &command, QString args)
return; return;
} }
nhlog::net()->error("Could not resolve goto: {}", args.toStdString()); nhlog::net()->error("Could not resolve goto: {}", args.toStdString());
} else if (command == "converttodm") { } else if (command == QLatin1String("converttodm")) {
utils::markRoomAsDirect(this->room->roomId(), utils::markRoomAsDirect(this->room->roomId(),
cache::getMembers(this->room->roomId().toStdString(), 0, -1)); cache::getMembers(this->room->roomId().toStdString(), 0, -1));
} else if (command == "converttoroom") { } else if (command == QLatin1String("converttoroom")) {
utils::removeDirectFromRoom(this->room->roomId()); utils::removeDirectFromRoom(this->room->roomId());
} }
} }
@ -660,13 +660,13 @@ InputBar::showPreview(const QMimeData &source, const QString &path, const QStrin
previewDialog_->setAttribute(Qt::WA_DeleteOnClose); previewDialog_->setAttribute(Qt::WA_DeleteOnClose);
// Force SVG to _not_ be handled as an image, but as raw data // Force SVG to _not_ be handled as an image, but as raw data
if (source.hasImage() && (formats.empty() || formats.front() != "image/svg+xml")) { if (source.hasImage() && (formats.empty() || formats.front() != QLatin1String("image/svg+xml"))) {
if (!formats.empty() && formats.front().startsWith("image/")) { if (!formats.empty() && formats.front().startsWith(QLatin1String("image/"))) {
// known format, keep as-is // known format, keep as-is
previewDialog_->setPreview(qvariant_cast<QImage>(source.imageData()), formats.front()); previewDialog_->setPreview(qvariant_cast<QImage>(source.imageData()), formats.front());
} else { } else {
// unknown image format, default to image/png // unknown image format, default to image/png
previewDialog_->setPreview(qvariant_cast<QImage>(source.imageData()), "image/png"); previewDialog_->setPreview(qvariant_cast<QImage>(source.imageData()), QStringLiteral("image/png"));
} }
} else if (!path.isEmpty()) } else if (!path.isEmpty())
previewDialog_->setPreview(path); previewDialog_->setPreview(path);
@ -696,7 +696,7 @@ InputBar::showPreview(const QMimeData &source, const QString &path, const QStrin
} }
setUploading(true); setUploading(true);
setText(""); setText(QLatin1String(""));
auto payload = std::string(data.data(), data.size()); auto payload = std::string(data.data(), data.size());
std::optional<mtx::crypto::EncryptedFile> encryptedFile; std::optional<mtx::crypto::EncryptedFile> encryptedFile;
@ -817,7 +817,7 @@ InputBar::reaction(const QString &reactedEvent, const QString &reactionKey)
} }
} }
if (selfReactedEvent.startsWith("m")) if (selfReactedEvent.startsWith(QLatin1String("m")))
return; return;
// If selfReactedEvent is empty, that means we haven't previously reacted // If selfReactedEvent is empty, that means we haven't previously reacted

View file

@ -98,7 +98,7 @@ RoomlistModel::data(const QModelIndex &index, int role) const
} else if (role == Roles::IsDirect) { } else if (role == Roles::IsDirect) {
return directChatToUser.count(roomid) > 0; return directChatToUser.count(roomid) > 0;
} else if (role == Roles::DirectChatOtherUserId) { } else if (role == Roles::DirectChatOtherUserId) {
return directChatToUser.count(roomid) ? directChatToUser.at(roomid).front() : ""; return directChatToUser.count(roomid) ? directChatToUser.at(roomid).front() : QLatin1String("");
} }
if (models.contains(roomid)) { if (models.contains(roomid)) {
@ -833,7 +833,7 @@ FilteredRoomlistModel::updateHiddenTagsAndSpaces()
hiddenTags.push_back(t.mid(4)); hiddenTags.push_back(t.mid(4));
else if (t.startsWith(u"space:")) else if (t.startsWith(u"space:"))
hiddenSpaces.push_back(t.mid(6)); hiddenSpaces.push_back(t.mid(6));
else if (t == "dm") else if (t == QLatin1String("dm"))
hideDMs = true; hideDMs = true;
} }

View file

@ -159,7 +159,7 @@ public slots:
} }
void joinPreview(QString roomid) void joinPreview(QString roomid)
{ {
roomlistmodel->joinPreview(roomid, filterType == FilterBy::Space ? filterStr : ""); roomlistmodel->joinPreview(roomid, filterType == FilterBy::Space ? filterStr : QLatin1String(""));
} }
void acceptInvite(QString roomid) { roomlistmodel->acceptInvite(roomid); } void acceptInvite(QString roomid) { roomlistmodel->acceptInvite(roomid); }
void declineInvite(QString roomid) { roomlistmodel->declineInvite(roomid); } void declineInvite(QString roomid) { roomlistmodel->declineInvite(roomid); }
@ -181,13 +181,13 @@ public slots:
void updateFilterTag(QString tagId) void updateFilterTag(QString tagId)
{ {
if (tagId.startsWith("tag:")) { if (tagId.startsWith(QLatin1String("tag:"))) {
filterType = FilterBy::Tag; filterType = FilterBy::Tag;
filterStr = tagId.mid(4); filterStr = tagId.mid(4);
} else if (tagId.startsWith("space:")) { } else if (tagId.startsWith(QLatin1String("space:"))) {
filterType = FilterBy::Space; filterType = FilterBy::Space;
filterStr = tagId.mid(6); filterStr = tagId.mid(6);
} else if (tagId.startsWith("dm")) { } else if (tagId.startsWith(QLatin1String("dm"))) {
filterType = FilterBy::DirectChats; filterType = FilterBy::DirectChats;
filterStr.clear(); filterStr.clear();
} else { } else {
@ -215,7 +215,7 @@ private:
DirectChats, DirectChats,
Nothing, Nothing,
}; };
QString filterStr = ""; QString filterStr = QLatin1String("");
FilterBy filterType = FilterBy::Nothing; FilterBy filterType = FilterBy::Nothing;
QStringList hiddenTags, hiddenSpaces; QStringList hiddenTags, hiddenSpaces;
bool hideDMs = false; bool hideDMs = false;

View file

@ -540,7 +540,7 @@ TimelineModel::data(const mtx::events::collections::TimelineEvents &event, int r
return QVariant(utils::replaceEmoji(QString::fromStdString(body(event)).toHtmlEscaped())); return QVariant(utils::replaceEmoji(QString::fromStdString(body(event)).toHtmlEscaped()));
case FormattedBody: { case FormattedBody: {
const static QRegularExpression replyFallback( const static QRegularExpression replyFallback(
"<mx-reply>.*</mx-reply>", QRegularExpression::DotMatchesEverythingOption); QStringLiteral("<mx-reply>.*</mx-reply>"), QRegularExpression::DotMatchesEverythingOption);
auto ascent = QFontMetrics(UserSettings::instance()->font()).ascent(); auto ascent = QFontMetrics(UserSettings::instance()->font()).ascent();
@ -551,19 +551,19 @@ TimelineModel::data(const mtx::events::collections::TimelineEvents &event, int r
auto body_ = QString::fromStdString(body(event)); auto body_ = QString::fromStdString(body(event));
if (isReply) { if (isReply) {
while (body_.startsWith("> ")) while (body_.startsWith(QLatin1String("> ")))
body_ = body_.right(body_.size() - body_.indexOf('\n') - 1); body_ = body_.right(body_.size() - body_.indexOf('\n') - 1);
if (body_.startsWith('\n')) if (body_.startsWith('\n'))
body_ = body_.right(body_.size() - 1); body_ = body_.right(body_.size() - 1);
} }
formattedBody_ = body_.toHtmlEscaped().replace('\n', "<br>"); formattedBody_ = body_.toHtmlEscaped().replace('\n', QLatin1String("<br>"));
} else { } else {
if (isReply) if (isReply)
formattedBody_ = formattedBody_.remove(replyFallback); formattedBody_ = formattedBody_.remove(replyFallback);
} }
// TODO(Nico): Don't parse html with a regex // TODO(Nico): Don't parse html with a regex
const static QRegularExpression matchIsImg("<img [^>]+>"); const static QRegularExpression matchIsImg(QStringLiteral("<img [^>]+>"));
auto itIsImg = matchIsImg.globalMatch(formattedBody_); auto itIsImg = matchIsImg.globalMatch(formattedBody_);
while (itIsImg.hasNext()) { while (itIsImg.hasNext()) {
// The current <img> tag. // The current <img> tag.
@ -573,23 +573,23 @@ TimelineModel::data(const mtx::events::collections::TimelineEvents &event, int r
// Construct image parameters later used by MxcImageProvider. // Construct image parameters later used by MxcImageProvider.
QString imgParams; QString imgParams;
if (curImg.contains("height")) { if (curImg.contains(QLatin1String("height"))) {
const static QRegularExpression matchImgHeight("height=([\"\']?)(\\d+)([\"\']?)"); const static QRegularExpression matchImgHeight(QStringLiteral("height=([\"\']?)(\\d+)([\"\']?)"));
// Make emoticons twice as high as the font. // Make emoticons twice as high as the font.
if (curImg.contains("data-mx-emoticon")) { if (curImg.contains(QLatin1String("data-mx-emoticon"))) {
imgReplacement = imgReplacement =
imgReplacement.replace(matchImgHeight, "height=\\1%1\\3").arg(ascent * 2); imgReplacement.replace(matchImgHeight, "height=\\1%1\\3").arg(ascent * 2);
} }
const auto height = matchImgHeight.match(imgReplacement).captured(2).toInt(); const auto height = matchImgHeight.match(imgReplacement).captured(2).toInt();
imgParams = QString("?scale&height=%1").arg(height); imgParams = QStringLiteral("?scale&height=%1").arg(height);
} }
// Replace src in current <img>. // Replace src in current <img>.
const static QRegularExpression matchImgUri("src=\"mxc://([^\"]*)\""); const static QRegularExpression matchImgUri(QStringLiteral("src=\"mxc://([^\"]*)\""));
imgReplacement.replace(matchImgUri, imgReplacement.replace(matchImgUri,
QString("src=\"image://mxcImage/\\1%1\"").arg(imgParams)); QString("src=\"image://mxcImage/\\1%1\"").arg(imgParams));
// Same regex but for single quotes around the src // Same regex but for single quotes around the src
const static QRegularExpression matchImgUri2("src=\'mxc://([^\']*)\'"); const static QRegularExpression matchImgUri2(QStringLiteral("src=\'mxc://([^\']*)\'"));
imgReplacement.replace(matchImgUri2, imgReplacement.replace(matchImgUri2,
QString("src=\'image://mxcImage/\\1%1\'").arg(imgParams)); QString("src=\'image://mxcImage/\\1%1\'").arg(imgParams));
@ -694,7 +694,7 @@ TimelineModel::data(const mtx::events::collections::TimelineEvents &event, int r
utils::replaceEmoji(QString::fromStdString(room_name(event)).toHtmlEscaped())); utils::replaceEmoji(QString::fromStdString(room_name(event)).toHtmlEscaped()));
case RoomTopic: case RoomTopic:
return QVariant(utils::replaceEmoji(utils::linkifyMessage( return QVariant(utils::replaceEmoji(utils::linkifyMessage(
QString::fromStdString(room_topic(event)).toHtmlEscaped().replace("\n", "<br>")))); QString::fromStdString(room_topic(event)).toHtmlEscaped().replace(QLatin1String("\n"), QLatin1String("<br>")))));
case CallType: case CallType:
return QVariant(QString::fromStdString(call_type(event))); return QVariant(QString::fromStdString(call_type(event)));
case Dump: { case Dump: {
@ -1073,7 +1073,7 @@ TimelineModel::formatDateSeparator(QDate date) const
QString fmt = QLocale::system().dateFormat(QLocale::LongFormat); QString fmt = QLocale::system().dateFormat(QLocale::LongFormat);
if (now.date().year() == date.year()) { if (now.date().year() == date.year()) {
QRegularExpression rx("[^a-zA-Z]*y+[^a-zA-Z]*"); QRegularExpression rx(QStringLiteral("[^a-zA-Z]*y+[^a-zA-Z]*"));
fmt = fmt.remove(rx); fmt = fmt.remove(rx);
} }
@ -1255,7 +1255,7 @@ QString
TimelineModel::indexToId(int index) const TimelineModel::indexToId(int index) const
{ {
auto id = events.indexToId(events.size() - index - 1); auto id = events.indexToId(events.size() - index - 1);
return id ? QString::fromStdString(*id) : ""; return id ? QString::fromStdString(*id) : QLatin1String("");
} }
// Note: this will only be called for our messages // Note: this will only be called for our messages
@ -1546,7 +1546,7 @@ TimelineModel::cacheMedia(const QString &eventId,
auto encryptionInfo = mtx::accessors::file(*event); auto encryptionInfo = mtx::accessors::file(*event);
// If the message is a link to a non mxcUrl, don't download it // If the message is a link to a non mxcUrl, don't download it
if (!mxcUrl.startsWith("mxc://")) { if (!mxcUrl.startsWith(QLatin1String("mxc://"))) {
emit mediaCached(mxcUrl, mxcUrl); emit mediaCached(mxcUrl, mxcUrl);
return; return;
} }
@ -1554,9 +1554,9 @@ TimelineModel::cacheMedia(const QString &eventId,
QString suffix = QMimeDatabase().mimeTypeForName(mimeType).preferredSuffix(); QString suffix = QMimeDatabase().mimeTypeForName(mimeType).preferredSuffix();
const auto url = mxcUrl.toStdString(); const auto url = mxcUrl.toStdString();
const auto name = QString(mxcUrl).remove("mxc://"); const auto name = QString(mxcUrl).remove(QStringLiteral("mxc://"));
QFileInfo filename( QFileInfo filename(
QString("%1/media_cache/%2.%3") QStringLiteral("%1/media_cache/%2.%3")
.arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation), name, suffix)); .arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation), name, suffix));
if (QDir::cleanPath(name) != name) { if (QDir::cleanPath(name) != name) {
nhlog::net()->warn("mxcUrl '{}' is not safe, not downloading file", url); nhlog::net()->warn("mxcUrl '{}' is not safe, not downloading file", url);
@ -1704,7 +1704,7 @@ TimelineModel::copyLinkToEvent(const QString &eventId) const
if (room.isEmpty()) if (room.isEmpty())
room = room_id_; room = room_id_;
vias.push_back(QString("via=%1").arg(QString( vias.push_back(QStringLiteral("via=%1").arg(QString(
QUrl::toPercentEncoding(QString::fromStdString(http::client()->user_id().hostname()))))); QUrl::toPercentEncoding(QString::fromStdString(http::client()->user_id().hostname())))));
auto members = cache::getMembers(room_id_.toStdString(), 0, 100); auto members = cache::getMembers(room_id_.toStdString(), 0, 100);
for (const auto &m : members) { for (const auto &m : members) {
@ -1712,14 +1712,14 @@ TimelineModel::copyLinkToEvent(const QString &eventId) const
break; break;
auto user_id = mtx::identifiers::parse<mtx::identifiers::User>(m.user_id.toStdString()); auto user_id = mtx::identifiers::parse<mtx::identifiers::User>(m.user_id.toStdString());
QString server = QString("via=%1").arg( QString server = QStringLiteral("via=%1").arg(
QString(QUrl::toPercentEncoding(QString::fromStdString(user_id.hostname())))); QString(QUrl::toPercentEncoding(QString::fromStdString(user_id.hostname()))));
if (!vias.contains(server)) if (!vias.contains(server))
vias.push_back(server); vias.push_back(server);
} }
auto link = QString("https://matrix.to/#/%1/%2?%3") auto link = QStringLiteral("https://matrix.to/#/%1/%2?%3")
.arg(QString(QUrl::toPercentEncoding(room)), .arg(QString(QUrl::toPercentEncoding(room)),
QString(QUrl::toPercentEncoding(eventId)), QString(QUrl::toPercentEncoding(eventId)),
vias.join('&')); vias.join('&'));
@ -1739,7 +1739,7 @@ TimelineModel::formatTypingUsers(const std::vector<QString> &users, const QColor
(int)users.size()); (int)users.size());
if (users.empty()) { if (users.empty()) {
return ""; return QString();
} }
QStringList uidWithoutLast; QStringList uidWithoutLast;
@ -1747,20 +1747,20 @@ TimelineModel::formatTypingUsers(const std::vector<QString> &users, const QColor
auto formatUser = [this, bg](const QString &user_id) -> QString { auto formatUser = [this, bg](const QString &user_id) -> QString {
auto uncoloredUsername = utils::replaceEmoji(displayName(user_id)); auto uncoloredUsername = utils::replaceEmoji(displayName(user_id));
QString prefix = QString prefix =
QString("<font color=\"%1\">").arg(manager_->userColor(user_id, bg).name()); QStringLiteral("<font color=\"%1\">").arg(manager_->userColor(user_id, bg).name());
// color only parts that don't have a font already specified // color only parts that don't have a font already specified
QString coloredUsername; QString coloredUsername;
int index = 0; int index = 0;
do { do {
auto startIndex = uncoloredUsername.indexOf("<font", index); auto startIndex = uncoloredUsername.indexOf(QLatin1String("<font"), index);
if (startIndex - index != 0) if (startIndex - index != 0)
coloredUsername += coloredUsername +=
prefix + uncoloredUsername.mid(index, startIndex > 0 ? startIndex - index : -1) + prefix + uncoloredUsername.mid(index, startIndex > 0 ? startIndex - index : -1) +
QStringLiteral("</font>"); QStringLiteral("</font>");
auto endIndex = uncoloredUsername.indexOf("</font>", startIndex); auto endIndex = uncoloredUsername.indexOf(QLatin1String("</font>"), startIndex);
if (endIndex > 0) if (endIndex > 0)
endIndex += sizeof("</font>") - 1; endIndex += sizeof("</font>") - 1;
@ -1778,7 +1778,7 @@ TimelineModel::formatTypingUsers(const std::vector<QString> &users, const QColor
uidWithoutLast.append(formatUser(users[i])); uidWithoutLast.append(formatUser(users[i]));
} }
return temp.arg(uidWithoutLast.join(", "), formatUser(users.back())); return temp.arg(uidWithoutLast.join(QStringLiteral(", ")), formatUser(users.back()));
} }
QString QString
@ -1786,11 +1786,11 @@ TimelineModel::formatJoinRuleEvent(const QString &id)
{ {
mtx::events::collections::TimelineEvents *e = events.get(id.toStdString(), ""); mtx::events::collections::TimelineEvents *e = events.get(id.toStdString(), "");
if (!e) if (!e)
return ""; return QString();
auto event = std::get_if<mtx::events::StateEvent<mtx::events::state::JoinRules>>(e); auto event = std::get_if<mtx::events::StateEvent<mtx::events::state::JoinRules>>(e);
if (!event) if (!event)
return ""; return QString();
QString user = QString::fromStdString(event->sender); QString user = QString::fromStdString(event->sender);
QString name = utils::replaceEmoji(displayName(user)); QString name = utils::replaceEmoji(displayName(user));
@ -1810,11 +1810,11 @@ TimelineModel::formatJoinRuleEvent(const QString &id)
} }
return tr("%1 allowed members of the following rooms to automatically join this " return tr("%1 allowed members of the following rooms to automatically join this "
"room: %2") "room: %2")
.arg(name, rooms.join(", ")); .arg(name, rooms.join(QStringLiteral(", ")));
} }
default: default:
// Currently, knock and private are reserved keywords and not implemented in Matrix. // Currently, knock and private are reserved keywords and not implemented in Matrix.
return ""; return QString();
} }
} }
@ -1823,11 +1823,11 @@ TimelineModel::formatGuestAccessEvent(const QString &id)
{ {
mtx::events::collections::TimelineEvents *e = events.get(id.toStdString(), ""); mtx::events::collections::TimelineEvents *e = events.get(id.toStdString(), "");
if (!e) if (!e)
return ""; return QString();
auto event = std::get_if<mtx::events::StateEvent<mtx::events::state::GuestAccess>>(e); auto event = std::get_if<mtx::events::StateEvent<mtx::events::state::GuestAccess>>(e);
if (!event) if (!event)
return ""; return QString();
QString user = QString::fromStdString(event->sender); QString user = QString::fromStdString(event->sender);
QString name = utils::replaceEmoji(displayName(user)); QString name = utils::replaceEmoji(displayName(user));
@ -1838,7 +1838,7 @@ TimelineModel::formatGuestAccessEvent(const QString &id)
case mtx::events::state::AccessState::Forbidden: case mtx::events::state::AccessState::Forbidden:
return tr("%1 has closed the room to guest access.").arg(name); return tr("%1 has closed the room to guest access.").arg(name);
default: default:
return ""; return QString();
} }
} }
@ -1847,12 +1847,12 @@ TimelineModel::formatHistoryVisibilityEvent(const QString &id)
{ {
mtx::events::collections::TimelineEvents *e = events.get(id.toStdString(), ""); mtx::events::collections::TimelineEvents *e = events.get(id.toStdString(), "");
if (!e) if (!e)
return ""; return QString();
auto event = std::get_if<mtx::events::StateEvent<mtx::events::state::HistoryVisibility>>(e); auto event = std::get_if<mtx::events::StateEvent<mtx::events::state::HistoryVisibility>>(e);
if (!event) if (!event)
return ""; return QString();
QString user = QString::fromStdString(event->sender); QString user = QString::fromStdString(event->sender);
QString name = utils::replaceEmoji(displayName(user)); QString name = utils::replaceEmoji(displayName(user));
@ -1870,7 +1870,7 @@ TimelineModel::formatHistoryVisibilityEvent(const QString &id)
return tr("%1 set the room history visible to members since they joined the room.") return tr("%1 set the room history visible to members since they joined the room.")
.arg(name); .arg(name);
default: default:
return ""; return QString();
} }
} }
@ -1879,11 +1879,11 @@ TimelineModel::formatPowerLevelEvent(const QString &id)
{ {
mtx::events::collections::TimelineEvents *e = events.get(id.toStdString(), ""); mtx::events::collections::TimelineEvents *e = events.get(id.toStdString(), "");
if (!e) if (!e)
return ""; return QString();
auto event = std::get_if<mtx::events::StateEvent<mtx::events::state::PowerLevels>>(e); auto event = std::get_if<mtx::events::StateEvent<mtx::events::state::PowerLevels>>(e);
if (!event) if (!event)
return ""; return QString();
QString user = QString::fromStdString(event->sender); QString user = QString::fromStdString(event->sender);
QString name = utils::replaceEmoji(displayName(user)); QString name = utils::replaceEmoji(displayName(user));
@ -1905,7 +1905,7 @@ TimelineModel::formatRedactedEvent(const QString &id)
return pair; return pair;
QString dateTime = QDateTime::fromMSecsSinceEpoch(event->origin_server_ts).toString(); QString dateTime = QDateTime::fromMSecsSinceEpoch(event->origin_server_ts).toString();
QString reason = ""; QString reason = QLatin1String("");
auto because = event->unsigned_data.redacted_because; auto because = event->unsigned_data.redacted_because;
// User info about who actually sent the redacted event. // User info about who actually sent the redacted event.
QString redactedUser; QString redactedUser;
@ -1918,12 +1918,12 @@ TimelineModel::formatRedactedEvent(const QString &id)
} }
if (reason.isEmpty()) { if (reason.isEmpty()) {
pair["first"] = tr("Removed by %1").arg(redactedName); pair[QStringLiteral("first")] = tr("Removed by %1").arg(redactedName);
pair["second"] = pair[QStringLiteral("second")] =
tr("%1 (%2) removed this message at %3").arg(redactedName, redactedUser, dateTime); tr("%1 (%2) removed this message at %3").arg(redactedName, redactedUser, dateTime);
} else { } else {
pair["first"] = tr("Removed by %1 because: %2").arg(redactedName, reason); pair[QStringLiteral("first")] = tr("Removed by %1 because: %2").arg(redactedName, reason);
pair["second"] = tr("%1 (%2) removed this message at %3\nReason: %4") pair[QStringLiteral("second")] = tr("%1 (%2) removed this message at %3\nReason: %4")
.arg(redactedName, redactedUser, dateTime, reason); .arg(redactedName, redactedUser, dateTime, reason);
} }
@ -1951,7 +1951,7 @@ TimelineModel::acceptKnock(const QString &id)
if (event->content.membership != Membership::Knock) if (event->content.membership != Membership::Knock)
return; return;
ChatPage::instance()->inviteUser(QString::fromStdString(event->state_key), ""); ChatPage::instance()->inviteUser(QString::fromStdString(event->state_key), QLatin1String(""));
} }
bool bool
@ -1980,11 +1980,11 @@ TimelineModel::formatMemberEvent(const QString &id)
{ {
mtx::events::collections::TimelineEvents *e = events.get(id.toStdString(), ""); mtx::events::collections::TimelineEvents *e = events.get(id.toStdString(), "");
if (!e) if (!e)
return ""; return QString();
auto event = std::get_if<mtx::events::StateEvent<mtx::events::state::Member>>(e); auto event = std::get_if<mtx::events::StateEvent<mtx::events::state::Member>>(e);
if (!event) if (!event)
return ""; return QString();
mtx::events::StateEvent<mtx::events::state::Member> *prevEvent = nullptr; mtx::events::StateEvent<mtx::events::state::Member> *prevEvent = nullptr;
if (!event->unsigned_data.replaces_state.empty()) { if (!event->unsigned_data.replaces_state.empty()) {
@ -2038,7 +2038,7 @@ TimelineModel::formatMemberEvent(const QString &id)
break; break;
case Membership::Leave: case Membership::Leave:
if (!prevEvent) // Should only ever happen temporarily if (!prevEvent) // Should only ever happen temporarily
return ""; return QString();
if (prevEvent->content.membership == Membership::Invite) { if (prevEvent->content.membership == Membership::Invite) {
if (event->state_key == event->sender) if (event->state_key == event->sender)
@ -2126,15 +2126,15 @@ TimelineModel::setEdit(const QString &newEdit)
else else
input()->setText(editText); input()->setText(editText);
} else { } else {
input()->setText(""); input()->setText(QLatin1String(""));
} }
edit_ = newEdit; edit_ = newEdit;
} else { } else {
resetReply(); resetReply();
input()->setText(""); input()->setText(QLatin1String(""));
edit_ = ""; edit_ = QLatin1String("");
} }
emit editChanged(edit_); emit editChanged(edit_);
} }
@ -2144,7 +2144,7 @@ void
TimelineModel::resetEdit() TimelineModel::resetEdit()
{ {
if (!edit_.isEmpty()) { if (!edit_.isEmpty()) {
edit_ = ""; edit_ = QLatin1String("");
emit editChanged(edit_); emit editChanged(edit_);
nhlog::ui()->debug("Restoring: {}", textBeforeEdit.toStdString()); nhlog::ui()->debug("Restoring: {}", textBeforeEdit.toStdString());
input()->setText(textBeforeEdit); input()->setText(textBeforeEdit);
@ -2163,7 +2163,7 @@ TimelineModel::roomName() const
auto info = cache::getRoomInfo({room_id_.toStdString()}); auto info = cache::getRoomInfo({room_id_.toStdString()});
if (!info.count(room_id_)) if (!info.count(room_id_))
return ""; return QString();
else else
return utils::replaceEmoji(QString::fromStdString(info[room_id_].name).toHtmlEscaped()); return utils::replaceEmoji(QString::fromStdString(info[room_id_].name).toHtmlEscaped());
} }
@ -2174,7 +2174,7 @@ TimelineModel::plainRoomName() const
auto info = cache::getRoomInfo({room_id_.toStdString()}); auto info = cache::getRoomInfo({room_id_.toStdString()});
if (!info.count(room_id_)) if (!info.count(room_id_))
return ""; return QString();
else else
return QString::fromStdString(info[room_id_].name); return QString::fromStdString(info[room_id_].name);
} }
@ -2185,7 +2185,7 @@ TimelineModel::roomAvatarUrl() const
auto info = cache::getRoomInfo({room_id_.toStdString()}); auto info = cache::getRoomInfo({room_id_.toStdString()});
if (!info.count(room_id_)) if (!info.count(room_id_))
return ""; return QString();
else else
return QString::fromStdString(info[room_id_].avatar_url); return QString::fromStdString(info[room_id_].avatar_url);
} }
@ -2196,7 +2196,7 @@ TimelineModel::roomTopic() const
auto info = cache::getRoomInfo({room_id_.toStdString()}); auto info = cache::getRoomInfo({room_id_.toStdString()});
if (!info.count(room_id_)) if (!info.count(room_id_))
return ""; return QString();
else else
return utils::replaceEmoji( return utils::replaceEmoji(
utils::linkifyMessage(QString::fromStdString(info[room_id_].topic).toHtmlEscaped())); utils::linkifyMessage(QString::fromStdString(info[room_id_].topic).toHtmlEscaped()));
@ -2244,5 +2244,5 @@ TimelineModel::directChatOtherUserId() const
id = member.user_id; id = member.user_id;
return id; return id;
} else } else
return ""; return QString();
} }

View file

@ -345,7 +345,7 @@ public slots:
void resetReply() void resetReply()
{ {
if (!reply_.isEmpty()) { if (!reply_.isEmpty()) {
reply_ = ""; reply_ = QLatin1String("");
emit replyChanged(reply_); emit replyChanged(reply_);
} }
} }

View file

@ -101,15 +101,15 @@ TimelineViewManager::updateColorPalette()
{ {
userColors.clear(); userColors.clear();
if (ChatPage::instance()->userSettings()->theme() == "light") { if (ChatPage::instance()->userSettings()->theme() == QLatin1String("light")) {
view->rootContext()->setContextProperty("currentActivePalette", QPalette()); view->rootContext()->setContextProperty(QStringLiteral("currentActivePalette"), QPalette());
view->rootContext()->setContextProperty("currentInactivePalette", QPalette()); view->rootContext()->setContextProperty(QStringLiteral("currentInactivePalette"), QPalette());
} else if (ChatPage::instance()->userSettings()->theme() == "dark") { } else if (ChatPage::instance()->userSettings()->theme() == QLatin1String("dark")) {
view->rootContext()->setContextProperty("currentActivePalette", QPalette()); view->rootContext()->setContextProperty(QStringLiteral("currentActivePalette"), QPalette());
view->rootContext()->setContextProperty("currentInactivePalette", QPalette()); view->rootContext()->setContextProperty(QStringLiteral("currentInactivePalette"), QPalette());
} else { } else {
view->rootContext()->setContextProperty("currentActivePalette", QPalette()); view->rootContext()->setContextProperty(QStringLiteral("currentActivePalette"), QPalette());
view->rootContext()->setContextProperty("currentInactivePalette", nullptr); view->rootContext()->setContextProperty(QStringLiteral("currentInactivePalette"), nullptr);
} }
} }
@ -126,7 +126,7 @@ QString
TimelineViewManager::userPresence(QString id) const TimelineViewManager::userPresence(QString id) const
{ {
if (id.isEmpty()) if (id.isEmpty())
return ""; return QString();
else else
return QString::fromStdString( return QString::fromStdString(
mtx::presence::to_string(cache::presenceState(id.toStdString()))); mtx::presence::to_string(cache::presenceState(id.toStdString())));
@ -162,17 +162,17 @@ TimelineViewManager::TimelineViewManager(CallManager *callManager, ChatPage *par
qRegisterMetaType<std::vector<mtx::responses::PublicRoomsChunk>>(); qRegisterMetaType<std::vector<mtx::responses::PublicRoomsChunk>>();
qmlRegisterUncreatableMetaObject( qmlRegisterUncreatableMetaObject(
qml_mtx_events::staticMetaObject, "im.nheko", 1, 0, "MtxEvent", "Can't instantiate enum!"); qml_mtx_events::staticMetaObject, "im.nheko", 1, 0, "MtxEvent", QStringLiteral("Can't instantiate enum!"));
qmlRegisterUncreatableMetaObject( qmlRegisterUncreatableMetaObject(
olm::staticMetaObject, "im.nheko", 1, 0, "Olm", "Can't instantiate enum!"); olm::staticMetaObject, "im.nheko", 1, 0, "Olm", QStringLiteral("Can't instantiate enum!"));
qmlRegisterUncreatableMetaObject( qmlRegisterUncreatableMetaObject(
crypto::staticMetaObject, "im.nheko", 1, 0, "Crypto", "Can't instantiate enum!"); crypto::staticMetaObject, "im.nheko", 1, 0, "Crypto", QStringLiteral("Can't instantiate enum!"));
qmlRegisterUncreatableMetaObject(verification::staticMetaObject, qmlRegisterUncreatableMetaObject(verification::staticMetaObject,
"im.nheko", "im.nheko",
1, 1,
0, 0,
"VerificationStatus", "VerificationStatus",
"Can't instantiate enum!"); QStringLiteral("Can't instantiate enum!"));
qmlRegisterType<DelegateChoice>("im.nheko", 1, 0, "DelegateChoice"); qmlRegisterType<DelegateChoice>("im.nheko", 1, 0, "DelegateChoice");
qmlRegisterType<DelegateChooser>("im.nheko", 1, 0, "DelegateChooser"); qmlRegisterType<DelegateChooser>("im.nheko", 1, 0, "DelegateChooser");
@ -181,39 +181,39 @@ TimelineViewManager::TimelineViewManager(CallManager *callManager, ChatPage *par
qmlRegisterType<MxcAnimatedImage>("im.nheko", 1, 0, "MxcAnimatedImage"); qmlRegisterType<MxcAnimatedImage>("im.nheko", 1, 0, "MxcAnimatedImage");
qmlRegisterType<MxcMediaProxy>("im.nheko", 1, 0, "MxcMedia"); qmlRegisterType<MxcMediaProxy>("im.nheko", 1, 0, "MxcMedia");
qmlRegisterUncreatableType<DeviceVerificationFlow>( qmlRegisterUncreatableType<DeviceVerificationFlow>(
"im.nheko", 1, 0, "DeviceVerificationFlow", "Can't create verification flow from QML!"); "im.nheko", 1, 0, "DeviceVerificationFlow", QStringLiteral("Can't create verification flow from QML!"));
qmlRegisterUncreatableType<UserProfile>( qmlRegisterUncreatableType<UserProfile>(
"im.nheko", 1, 0, "UserProfileModel", "UserProfile needs to be instantiated on the C++ side"); "im.nheko", 1, 0, "UserProfileModel", QStringLiteral("UserProfile needs to be instantiated on the C++ side"));
qmlRegisterUncreatableType<MemberList>( qmlRegisterUncreatableType<MemberList>(
"im.nheko", 1, 0, "MemberList", "MemberList needs to be instantiated on the C++ side"); "im.nheko", 1, 0, "MemberList", QStringLiteral("MemberList needs to be instantiated on the C++ side"));
qmlRegisterUncreatableType<RoomSettings>( qmlRegisterUncreatableType<RoomSettings>(
"im.nheko", "im.nheko",
1, 1,
0, 0,
"RoomSettingsModel", "RoomSettingsModel",
"Room Settings needs to be instantiated on the C++ side"); QStringLiteral("Room Settings needs to be instantiated on the C++ side"));
qmlRegisterUncreatableType<TimelineModel>( qmlRegisterUncreatableType<TimelineModel>(
"im.nheko", 1, 0, "Room", "Room needs to be instantiated on the C++ side"); "im.nheko", 1, 0, "Room", QStringLiteral("Room needs to be instantiated on the C++ side"));
qmlRegisterUncreatableType<ImagePackListModel>( qmlRegisterUncreatableType<ImagePackListModel>(
"im.nheko", "im.nheko",
1, 1,
0, 0,
"ImagePackListModel", "ImagePackListModel",
"ImagePackListModel needs to be instantiated on the C++ side"); QStringLiteral("ImagePackListModel needs to be instantiated on the C++ side"));
qmlRegisterUncreatableType<SingleImagePackModel>( qmlRegisterUncreatableType<SingleImagePackModel>(
"im.nheko", "im.nheko",
1, 1,
0, 0,
"SingleImagePackModel", "SingleImagePackModel",
"SingleImagePackModel needs to be instantiated on the C++ side"); QStringLiteral("SingleImagePackModel needs to be instantiated on the C++ side"));
qmlRegisterUncreatableType<InviteesModel>( qmlRegisterUncreatableType<InviteesModel>(
"im.nheko", 1, 0, "InviteesModel", "InviteesModel needs to be instantiated on the C++ side"); "im.nheko", 1, 0, "InviteesModel", QStringLiteral("InviteesModel needs to be instantiated on the C++ side"));
qmlRegisterUncreatableType<ReadReceiptsProxy>( qmlRegisterUncreatableType<ReadReceiptsProxy>(
"im.nheko", "im.nheko",
1, 1,
0, 0,
"ReadReceiptsProxy", "ReadReceiptsProxy",
"ReadReceiptsProxy needs to be instantiated on the C++ side"); QStringLiteral("ReadReceiptsProxy needs to be instantiated on the C++ side"));
static auto self = this; static auto self = this;
qmlRegisterSingletonInstance("im.nheko", 1, 0, "MainWindow", MainWindow::instance()); qmlRegisterSingletonInstance("im.nheko", 1, 0, "MainWindow", MainWindow::instance());
@ -265,13 +265,13 @@ TimelineViewManager::TimelineViewManager(CallManager *callManager, ChatPage *par
1, 1,
0, 0,
"FilteredCommunitiesModel", "FilteredCommunitiesModel",
"Use Communities.filtered() to create a FilteredCommunitiesModel"); QStringLiteral("Use Communities.filtered() to create a FilteredCommunitiesModel"));
qmlRegisterType<emoji::EmojiModel>("im.nheko.EmojiModel", 1, 0, "EmojiModel"); qmlRegisterType<emoji::EmojiModel>("im.nheko.EmojiModel", 1, 0, "EmojiModel");
qmlRegisterUncreatableType<emoji::Emoji>( qmlRegisterUncreatableType<emoji::Emoji>(
"im.nheko.EmojiModel", 1, 0, "Emoji", "Used by emoji models"); "im.nheko.EmojiModel", 1, 0, "Emoji", QStringLiteral("Used by emoji models"));
qmlRegisterUncreatableMetaObject( qmlRegisterUncreatableMetaObject(
emoji::staticMetaObject, "im.nheko.EmojiModel", 1, 0, "EmojiCategory", "Error: Only enums"); emoji::staticMetaObject, "im.nheko.EmojiModel", 1, 0, "EmojiCategory", QStringLiteral("Error: Only enums"));
qmlRegisterType<RoomDirectoryModel>("im.nheko", 1, 0, "RoomDirectoryModel"); qmlRegisterType<RoomDirectoryModel>("im.nheko", 1, 0, "RoomDirectoryModel");
@ -290,12 +290,12 @@ TimelineViewManager::TimelineViewManager(CallManager *callManager, ChatPage *par
#endif #endif
container->setMinimumSize(200, 200); container->setMinimumSize(200, 200);
updateColorPalette(); updateColorPalette();
view->engine()->addImageProvider("MxcImage", imgProvider); view->engine()->addImageProvider(QStringLiteral("MxcImage"), imgProvider);
view->engine()->addImageProvider("colorimage", colorImgProvider); view->engine()->addImageProvider(QStringLiteral("colorimage"), colorImgProvider);
view->engine()->addImageProvider("blurhash", blurhashProvider); view->engine()->addImageProvider(QStringLiteral("blurhash"), blurhashProvider);
if (JdenticonProvider::isAvailable()) if (JdenticonProvider::isAvailable())
view->engine()->addImageProvider("jdenticon", jdenticonProvider); view->engine()->addImageProvider(QStringLiteral("jdenticon"), jdenticonProvider);
view->setSource(QUrl("qrc:///qml/Root.qml")); view->setSource(QUrl(QStringLiteral("qrc:///qml/Root.qml")));
connect(parent, &ChatPage::themeChanged, this, &TimelineViewManager::updateColorPalette); connect(parent, &ChatPage::themeChanged, this, &TimelineViewManager::updateColorPalette);
connect(dynamic_cast<ChatPage *>(parent), connect(dynamic_cast<ChatPage *>(parent),
@ -362,7 +362,7 @@ void
TimelineViewManager::setVideoCallItem() TimelineViewManager::setVideoCallItem()
{ {
WebRTCSession::instance().setVideoItem( WebRTCSession::instance().setVideoItem(
view->rootObject()->findChild<QQuickItem *>("videoCallItem")); view->rootObject()->findChild<QQuickItem *>(QStringLiteral("videoCallItem")));
} }
void void
@ -405,7 +405,7 @@ TimelineViewManager::openImageOverlay(QString mxcUrl, QString eventId)
} }
MxcImageProvider::download( MxcImageProvider::download(
mxcUrl.remove("mxc://"), QSize(), [this, eventId](QString, QSize, QImage img, QString) { mxcUrl.remove(QStringLiteral("mxc://")), QSize(), [this, eventId](QString, QSize, QImage img, QString) {
if (img.isNull()) { if (img.isNull()) {
nhlog::ui()->error("Error when retrieving image for overlay."); nhlog::ui()->error("Error when retrieving image for overlay.");
return; return;
@ -520,37 +520,37 @@ TimelineViewManager::focusMessageInput()
QObject * QObject *
TimelineViewManager::completerFor(QString completerName, QString roomId) TimelineViewManager::completerFor(QString completerName, QString roomId)
{ {
if (completerName == "user") { if (completerName == QLatin1String("user")) {
auto userModel = new UsersModel(roomId.toStdString()); auto userModel = new UsersModel(roomId.toStdString());
auto proxy = new CompletionProxyModel(userModel); auto proxy = new CompletionProxyModel(userModel);
userModel->setParent(proxy); userModel->setParent(proxy);
return proxy; return proxy;
} else if (completerName == "emoji") { } else if (completerName == QLatin1String("emoji")) {
auto emojiModel = new emoji::EmojiModel(); auto emojiModel = new emoji::EmojiModel();
auto proxy = new CompletionProxyModel(emojiModel); auto proxy = new CompletionProxyModel(emojiModel);
emojiModel->setParent(proxy); emojiModel->setParent(proxy);
return proxy; return proxy;
} else if (completerName == "allemoji") { } else if (completerName == QLatin1String("allemoji")) {
auto emojiModel = new emoji::EmojiModel(); auto emojiModel = new emoji::EmojiModel();
auto proxy = new CompletionProxyModel(emojiModel, 1, static_cast<size_t>(-1) / 4); auto proxy = new CompletionProxyModel(emojiModel, 1, static_cast<size_t>(-1) / 4);
emojiModel->setParent(proxy); emojiModel->setParent(proxy);
return proxy; return proxy;
} else if (completerName == "room") { } else if (completerName == QLatin1String("room")) {
auto roomModel = new RoomsModel(false); auto roomModel = new RoomsModel(false);
auto proxy = new CompletionProxyModel(roomModel, 4); auto proxy = new CompletionProxyModel(roomModel, 4);
roomModel->setParent(proxy); roomModel->setParent(proxy);
return proxy; return proxy;
} else if (completerName == "roomAliases") { } else if (completerName == QLatin1String("roomAliases")) {
auto roomModel = new RoomsModel(true); auto roomModel = new RoomsModel(true);
auto proxy = new CompletionProxyModel(roomModel); auto proxy = new CompletionProxyModel(roomModel);
roomModel->setParent(proxy); roomModel->setParent(proxy);
return proxy; return proxy;
} else if (completerName == "stickers") { } else if (completerName == QLatin1String("stickers")) {
auto stickerModel = new CombinedImagePackModel(roomId.toStdString(), true); auto stickerModel = new CombinedImagePackModel(roomId.toStdString(), true);
auto proxy = new CompletionProxyModel(stickerModel, 1, static_cast<size_t>(-1) / 4); auto proxy = new CompletionProxyModel(stickerModel, 1, static_cast<size_t>(-1) / 4);
stickerModel->setParent(proxy); stickerModel->setParent(proxy);
return proxy; return proxy;
} else if (completerName == "customEmoji") { } else if (completerName == QLatin1String("customEmoji")) {
auto stickerModel = new CombinedImagePackModel(roomId.toStdString(), false); auto stickerModel = new CombinedImagePackModel(roomId.toStdString(), false);
auto proxy = new CompletionProxyModel(stickerModel); auto proxy = new CompletionProxyModel(stickerModel);
stickerModel->setParent(proxy); stickerModel->setParent(proxy);

View file

@ -116,7 +116,7 @@ public slots:
void setVideoCallItem(); void setVideoCallItem();
QObject *completerFor(QString completerName, QString roomId = ""); QObject *completerFor(QString completerName, QString roomId = QLatin1String(QLatin1String("")));
void forwardMessageToRoom(mtx::events::collections::TimelineEvents *e, QString roomId); void forwardMessageToRoom(mtx::events::collections::TimelineEvents *e, QString roomId);
RoomlistModel *rooms() { return rooms_; } RoomlistModel *rooms() { return rooms_; }

View file

@ -127,17 +127,17 @@ FlatButton::foregroundColor() const
{ {
if (!foreground_color_.isValid()) { if (!foreground_color_.isValid()) {
if (bg_mode_ == Qt::OpaqueMode) { if (bg_mode_ == Qt::OpaqueMode) {
return ThemeManager::instance().themeColor("BrightWhite"); return ThemeManager::instance().themeColor(QStringLiteral("BrightWhite"));
} }
switch (role_) { switch (role_) {
case ui::Role::Primary: case ui::Role::Primary:
return ThemeManager::instance().themeColor("Blue"); return ThemeManager::instance().themeColor(QStringLiteral("Blue"));
case ui::Role::Secondary: case ui::Role::Secondary:
return ThemeManager::instance().themeColor("Gray"); return ThemeManager::instance().themeColor(QStringLiteral("Gray"));
case ui::Role::Default: case ui::Role::Default:
default: default:
return ThemeManager::instance().themeColor("Black"); return ThemeManager::instance().themeColor(QStringLiteral("Black"));
} }
} }
@ -157,12 +157,12 @@ FlatButton::backgroundColor() const
if (!background_color_.isValid()) { if (!background_color_.isValid()) {
switch (role_) { switch (role_) {
case ui::Role::Primary: case ui::Role::Primary:
return ThemeManager::instance().themeColor("Blue"); return ThemeManager::instance().themeColor(QStringLiteral("Blue"));
case ui::Role::Secondary: case ui::Role::Secondary:
return ThemeManager::instance().themeColor("Gray"); return ThemeManager::instance().themeColor(QStringLiteral("Gray"));
case ui::Role::Default: case ui::Role::Default:
default: default:
return ThemeManager::instance().themeColor("Black"); return ThemeManager::instance().themeColor(QStringLiteral("Black"));
} }
} }
@ -198,7 +198,7 @@ QColor
FlatButton::disabledForegroundColor() const FlatButton::disabledForegroundColor() const
{ {
if (!disabled_color_.isValid()) { if (!disabled_color_.isValid()) {
return ThemeManager::instance().themeColor("FadedWhite"); return ThemeManager::instance().themeColor(QStringLiteral("FadedWhite"));
} }
return disabled_color_; return disabled_color_;
@ -215,7 +215,7 @@ QColor
FlatButton::disabledBackgroundColor() const FlatButton::disabledBackgroundColor() const
{ {
if (!disabled_background_color_.isValid()) { if (!disabled_background_color_.isValid()) {
return ThemeManager::instance().themeColor("FadedWhite"); return ThemeManager::instance().themeColor(QStringLiteral("FadedWhite"));
} }
return disabled_background_color_; return disabled_background_color_;

View file

@ -44,14 +44,14 @@ MxcAnimatedImage::startDownload()
auto encryptionInfo = mtx::accessors::file(*event); auto encryptionInfo = mtx::accessors::file(*event);
// If the message is a link to a non mxcUrl, don't download it // If the message is a link to a non mxcUrl, don't download it
if (!mxcUrl.startsWith("mxc://")) { if (!mxcUrl.startsWith(QLatin1String("mxc://"))) {
return; return;
} }
QString suffix = QMimeDatabase().mimeTypeForName(mimeType).preferredSuffix(); QString suffix = QMimeDatabase().mimeTypeForName(mimeType).preferredSuffix();
const auto url = mxcUrl.toStdString(); const auto url = mxcUrl.toStdString();
const auto name = QString(mxcUrl).remove("mxc://"); const auto name = QString(mxcUrl).remove(QStringLiteral("mxc://"));
QFileInfo filename( QFileInfo filename(
QStringLiteral("%1/media_cache/media/%2.%3") QStringLiteral("%1/media_cache/media/%2.%3")
.arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation), name, suffix)); .arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation), name, suffix));

View file

@ -66,7 +66,7 @@ MxcMediaProxy::getVideoSurface()
int int
MxcMediaProxy::orientation() const MxcMediaProxy::orientation() const
{ {
nhlog::ui()->debug("metadata: {}", availableMetaData().join(",").toStdString()); nhlog::ui()->debug("metadata: {}", availableMetaData().join(QStringLiteral(",")).toStdString());
auto orientation = metaData(QMediaMetaData::Orientation).toInt(); auto orientation = metaData(QMediaMetaData::Orientation).toInt();
nhlog::ui()->debug("Video orientation: {}", orientation); nhlog::ui()->debug("Video orientation: {}", orientation);
return orientation; return orientation;
@ -93,16 +93,16 @@ MxcMediaProxy::startDownload()
auto encryptionInfo = mtx::accessors::file(*event); auto encryptionInfo = mtx::accessors::file(*event);
// If the message is a link to a non mxcUrl, don't download it // If the message is a link to a non mxcUrl, don't download it
if (!mxcUrl.startsWith("mxc://")) { if (!mxcUrl.startsWith(QLatin1String("mxc://"))) {
return; return;
} }
QString suffix = QMimeDatabase().mimeTypeForName(mimeType).preferredSuffix(); QString suffix = QMimeDatabase().mimeTypeForName(mimeType).preferredSuffix();
const auto url = mxcUrl.toStdString(); const auto url = mxcUrl.toStdString();
const auto name = QString(mxcUrl).remove("mxc://"); const auto name = QString(mxcUrl).remove(QStringLiteral("mxc://"));
QFileInfo filename( QFileInfo filename(
QString("%1/media_cache/media/%2.%3") QStringLiteral("%1/media_cache/media/%2.%3")
.arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation), name, suffix)); .arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation), name, suffix));
if (QDir::cleanPath(name) != name) { if (QDir::cleanPath(name) != name) {
nhlog::net()->warn("mxcUrl '{}' is not safe, not downloading file", url); nhlog::net()->warn("mxcUrl '{}' is not safe, not downloading file", url);

View file

@ -29,7 +29,7 @@ Nheko::updateUserProfile()
{ {
if (cache::client() && cache::client()->isInitialized()) if (cache::client() && cache::client()->isInitialized())
currentUser_.reset( currentUser_.reset(
new UserProfile("", utils::localUser(), ChatPage::instance()->timelineManager())); new UserProfile(QLatin1String(""), utils::localUser(), ChatPage::instance()->timelineManager()));
else else
currentUser_.reset(); currentUser_.reset();
emit profileChanged(); emit profileChanged();

View file

@ -235,7 +235,7 @@ QString
RoomSettings::roomTopic() const RoomSettings::roomTopic() const
{ {
return utils::replaceEmoji(utils::linkifyMessage( return utils::replaceEmoji(utils::linkifyMessage(
QString::fromStdString(info_.topic).toHtmlEscaped().replace("\n", "<br>"))); QString::fromStdString(info_.topic).toHtmlEscaped().replace(QLatin1String("\n"), QLatin1String("<br>"))));
} }
QString QString
@ -563,10 +563,10 @@ RoomSettings::updateAvatar()
QMimeDatabase db; QMimeDatabase db;
QMimeType mime = db.mimeTypeForFile(fileName, QMimeDatabase::MatchContent); QMimeType mime = db.mimeTypeForFile(fileName, QMimeDatabase::MatchContent);
const auto format = mime.name().split("/")[0]; const auto format = mime.name().split(QStringLiteral("/"))[0];
QFile file{fileName, this}; QFile file{fileName, this};
if (format != "image") { if (format != QLatin1String("image")) {
emit displayError(tr("The selected file is not an image")); emit displayError(tr("The selected file is not an image"));
return; return;
} }

View file

@ -29,7 +29,7 @@ TextLabel::TextLabel(QWidget *parent)
TextLabel::TextLabel(const QString &text, QWidget *parent) TextLabel::TextLabel(const QString &text, QWidget *parent)
: QTextBrowser(parent) : QTextBrowser(parent)
{ {
document()->setDefaultStyleSheet(QString("a {color: %1; }").arg(utils::linkColor())); document()->setDefaultStyleSheet(QStringLiteral("a {color: %1; }").arg(utils::linkColor()));
setText(text); setText(text);
setOpenExternalLinks(true); setOpenExternalLinks(true);
@ -108,7 +108,7 @@ TextLabel::handleLinkActivation(const QUrl &url)
auto parts = url.toString().split('/'); auto parts = url.toString().split('/');
auto defaultHandler = [](const QUrl &url) { QDesktopServices::openUrl(url); }; auto defaultHandler = [](const QUrl &url) { QDesktopServices::openUrl(url); };
if (url.host() != "matrix.to" || parts.isEmpty()) if (url.host() != QLatin1String("matrix.to") || parts.isEmpty())
return defaultHandler(url); return defaultHandler(url);
try { try {

View file

@ -9,31 +9,31 @@
QColor QColor
ThemeManager::themeColor(const QString &key) const ThemeManager::themeColor(const QString &key) const
{ {
if (key == "Black") if (key == QLatin1String("Black"))
return QColor(0x17, 0x19, 0x19); return QColor(0x17, 0x19, 0x19);
else if (key == "BrightWhite") else if (key == QLatin1String("BrightWhite"))
return QColor(0xEB, 0xEB, 0xEB); return QColor(0xEB, 0xEB, 0xEB);
else if (key == "FadedWhite") else if (key == QLatin1String("FadedWhite"))
return QColor(0xC9, 0xC9, 0xC9); return QColor(0xC9, 0xC9, 0xC9);
else if (key == "MediumWhite") else if (key == QLatin1String("MediumWhite"))
return QColor(0x92, 0x92, 0x92); return QColor(0x92, 0x92, 0x92);
else if (key == "BrightGreen") else if (key == QLatin1String("BrightGreen"))
return QColor(0x1C, 0x31, 0x33); return QColor(0x1C, 0x31, 0x33);
else if (key == "DarkGreen") else if (key == QLatin1String("DarkGreen"))
return QColor(0x57, 0x72, 0x75); return QColor(0x57, 0x72, 0x75);
else if (key == "LightGreen") else if (key == QLatin1String("LightGreen"))
return QColor(0x46, 0xA4, 0x51); return QColor(0x46, 0xA4, 0x51);
else if (key == "Gray") else if (key == QLatin1String("Gray"))
return QColor(0x5D, 0x65, 0x65); return QColor(0x5D, 0x65, 0x65);
else if (key == "Red") else if (key == QLatin1String("Red"))
return QColor(0xE2, 0x28, 0x26); return QColor(0xE2, 0x28, 0x26);
else if (key == "Blue") else if (key == QLatin1String("Blue"))
return QColor(0x81, 0xB3, 0xA9); return QColor(0x81, 0xB3, 0xA9);
else if (key == "Transparent") else if (key == QLatin1String("Transparent"))
return QColor(0, 0, 0, 0); return QColor(0, 0, 0, 0);
return (QColor(0, 0, 0, 0)); return (QColor(0, 0, 0, 0));

View file

@ -28,7 +28,7 @@ UserProfile::UserProfile(QString roomid,
, manager(manager_) , manager(manager_)
, model(parent) , model(parent)
{ {
globalAvatarUrl = ""; globalAvatarUrl = QLatin1String("");
connect(this, connect(this,
&UserProfile::globalUsernameRetrieved, &UserProfile::globalUsernameRetrieved,
@ -124,7 +124,7 @@ UserProfile::avatarUrl()
bool bool
UserProfile::isGlobalUserProfile() const UserProfile::isGlobalUserProfile() const
{ {
return roomid_ == ""; return roomid_ == QLatin1String("");
} }
crypto::Trust crypto::Trust
@ -297,7 +297,7 @@ UserProfile::updateVerificationStatus()
void void
UserProfile::banUser() UserProfile::banUser()
{ {
ChatPage::instance()->banUser(this->userid_, ""); ChatPage::instance()->banUser(this->userid_, QLatin1String(""));
} }
// void ignoreUser(){ // void ignoreUser(){
@ -307,7 +307,7 @@ UserProfile::banUser()
void void
UserProfile::kickUser() UserProfile::kickUser()
{ {
ChatPage::instance()->kickUser(this->userid_, ""); ChatPage::instance()->kickUser(this->userid_, QLatin1String(""));
} }
void void
@ -390,10 +390,10 @@ UserProfile::changeAvatar()
QMimeDatabase db; QMimeDatabase db;
QMimeType mime = db.mimeTypeForFile(fileName, QMimeDatabase::MatchContent); QMimeType mime = db.mimeTypeForFile(fileName, QMimeDatabase::MatchContent);
const auto format = mime.name().split("/")[0]; const auto format = mime.name().split(QStringLiteral("/"))[0];
QFile file{fileName, this}; QFile file{fileName, this};
if (format != "image") { if (format != QLatin1String("image")) {
emit displayError(tr("The selected file is not an image")); emit displayError(tr("The selected file is not an image"));
return; return;
} }

View file

@ -133,8 +133,8 @@ public:
bool isLoading() const; bool isLoading() const;
TimelineModel *room() const { return model; } TimelineModel *room() const { return model; }
Q_INVOKABLE void verify(QString device = ""); Q_INVOKABLE void verify(QString device = QLatin1String(""));
Q_INVOKABLE void unverify(QString device = ""); Q_INVOKABLE void unverify(QString device = QLatin1String(""));
Q_INVOKABLE void fetchDeviceList(const QString &userID); Q_INVOKABLE void fetchDeviceList(const QString &userID);
Q_INVOKABLE void refreshDevices(); Q_INVOKABLE void refreshDevices();
Q_INVOKABLE void banUser(); Q_INVOKABLE void banUser();

View file

@ -70,7 +70,7 @@ CallManager::CallManager(QObject *parent)
QTimer::singleShot(timeoutms_, this, [this, callid]() { QTimer::singleShot(timeoutms_, this, [this, callid]() {
if (session_.state() == webrtc::State::OFFERSENT && callid == callid_) { if (session_.state() == webrtc::State::OFFERSENT && callid == callid_) {
hangUp(CallHangUp::Reason::InviteTimeOut); hangUp(CallHangUp::Reason::InviteTimeOut);
emit ChatPage::instance()->showNotification("The remote side failed to pick up."); emit ChatPage::instance()->showNotification(QStringLiteral("The remote side failed to pick up."));
} }
}); });
}); });
@ -115,13 +115,13 @@ CallManager::CallManager(QObject *parent)
connect(&session_, &WebRTCSession::stateChanged, this, [this](webrtc::State state) { connect(&session_, &WebRTCSession::stateChanged, this, [this](webrtc::State state) {
switch (state) { switch (state) {
case webrtc::State::DISCONNECTED: case webrtc::State::DISCONNECTED:
playRingtone(QUrl("qrc:/media/media/callend.ogg"), false); playRingtone(QUrl(QStringLiteral("qrc:/media/media/callend.ogg")), false);
clear(); clear();
break; break;
case webrtc::State::ICEFAILED: { case webrtc::State::ICEFAILED: {
QString error("Call connection failed."); QString error(QStringLiteral("Call connection failed."));
if (turnURIs_.empty()) if (turnURIs_.empty())
error += " Your homeserver has no configured TURN server."; error += QLatin1String(" Your homeserver has no configured TURN server.");
emit ChatPage::instance()->showNotification(error); emit ChatPage::instance()->showNotification(error);
hangUp(CallHangUp::Reason::ICEFailed); hangUp(CallHangUp::Reason::ICEFailed);
break; break;
@ -177,7 +177,7 @@ CallManager::sendInvite(const QString &roomid, CallType callType, unsigned int w
auto roomInfo = cache::singleRoomInfo(roomid.toStdString()); auto roomInfo = cache::singleRoomInfo(roomid.toStdString());
if (roomInfo.member_count != 2) { if (roomInfo.member_count != 2) {
emit ChatPage::instance()->showNotification("Calls are limited to 1:1 rooms."); emit ChatPage::instance()->showNotification(QStringLiteral("Calls are limited to 1:1 rooms."));
return; return;
} }
@ -203,10 +203,10 @@ CallManager::sendInvite(const QString &roomid, CallType callType, unsigned int w
callPartyDisplayName_ = callee.display_name.isEmpty() ? callee.user_id : callee.display_name; callPartyDisplayName_ = callee.display_name.isEmpty() ? callee.user_id : callee.display_name;
callPartyAvatarUrl_ = QString::fromStdString(roomInfo.avatar_url); callPartyAvatarUrl_ = QString::fromStdString(roomInfo.avatar_url);
emit newInviteState(); emit newInviteState();
playRingtone(QUrl("qrc:/media/media/ringback.ogg"), true); playRingtone(QUrl(QStringLiteral("qrc:/media/media/ringback.ogg")), true);
if (!session_.createOffer(callType, if (!session_.createOffer(callType,
callType == CallType::SCREEN ? windows_[windowIndex].second : 0)) { callType == CallType::SCREEN ? windows_[windowIndex].second : 0)) {
emit ChatPage::instance()->showNotification("Problem setting up call."); emit ChatPage::instance()->showNotification(QStringLiteral("Problem setting up call."));
endCall(); endCall();
} }
} }
@ -290,8 +290,8 @@ CallManager::handleEvent(const RoomEvent<CallInvite> &callInviteEvent)
} }
const QString &ringtone = ChatPage::instance()->userSettings()->ringtone(); const QString &ringtone = ChatPage::instance()->userSettings()->ringtone();
if (ringtone != "Mute") if (ringtone != QLatin1String("Mute"))
playRingtone(ringtone == "Default" ? QUrl("qrc:/media/media/ring.ogg") playRingtone(ringtone == QLatin1String("Default") ? QUrl(QStringLiteral("qrc:/media/media/ring.ogg"))
: QUrl::fromLocalFile(ringtone), : QUrl::fromLocalFile(ringtone),
true); true);
roomid_ = QString::fromStdString(callInviteEvent.room_id); roomid_ = QString::fromStdString(callInviteEvent.room_id);
@ -328,7 +328,7 @@ CallManager::acceptInvite()
session_.setTurnServers(turnURIs_); session_.setTurnServers(turnURIs_);
if (!session_.acceptOffer(inviteSDP_)) { if (!session_.acceptOffer(inviteSDP_)) {
emit ChatPage::instance()->showNotification("Problem setting up call."); emit ChatPage::instance()->showNotification(QStringLiteral("Problem setting up call."));
hangUp(); hangUp();
return; return;
} }
@ -370,7 +370,7 @@ CallManager::handleEvent(const RoomEvent<CallAnswer> &callAnswerEvent)
if (callAnswerEvent.sender == utils::localUser().toStdString() && if (callAnswerEvent.sender == utils::localUser().toStdString() &&
callid_ == callAnswerEvent.content.call_id) { callid_ == callAnswerEvent.content.call_id) {
if (!isOnCall()) { if (!isOnCall()) {
emit ChatPage::instance()->showNotification("Call answered on another device."); emit ChatPage::instance()->showNotification(QStringLiteral("Call answered on another device."));
stopRingtone(); stopRingtone();
haveCallInvite_ = false; haveCallInvite_ = false;
emit newInviteState(); emit newInviteState();
@ -381,7 +381,7 @@ CallManager::handleEvent(const RoomEvent<CallAnswer> &callAnswerEvent)
if (isOnCall() && callid_ == callAnswerEvent.content.call_id) { if (isOnCall() && callid_ == callAnswerEvent.content.call_id) {
stopRingtone(); stopRingtone();
if (!session_.acceptAnswer(callAnswerEvent.content.sdp)) { if (!session_.acceptAnswer(callAnswerEvent.content.sdp)) {
emit ChatPage::instance()->showNotification("Problem setting up call."); emit ChatPage::instance()->showNotification(QStringLiteral("Problem setting up call."));
hangUp(); hangUp();
} }
} }

View file

@ -45,11 +45,11 @@ WebRTCSession::WebRTCSession()
{ {
qRegisterMetaType<webrtc::CallType>(); qRegisterMetaType<webrtc::CallType>();
qmlRegisterUncreatableMetaObject( qmlRegisterUncreatableMetaObject(
webrtc::staticMetaObject, "im.nheko", 1, 0, "CallType", "Can't instantiate enum"); webrtc::staticMetaObject, "im.nheko", 1, 0, "CallType", QStringLiteral("Can't instantiate enum"));
qRegisterMetaType<webrtc::State>(); qRegisterMetaType<webrtc::State>();
qmlRegisterUncreatableMetaObject( qmlRegisterUncreatableMetaObject(
webrtc::staticMetaObject, "im.nheko", 1, 0, "WebRTCState", "Can't instantiate enum"); webrtc::staticMetaObject, "im.nheko", 1, 0, "WebRTCState", QStringLiteral("Can't instantiate enum"));
connect(this, &WebRTCSession::stateChanged, this, &WebRTCSession::setState); connect(this, &WebRTCSession::stateChanged, this, &WebRTCSession::setState);
init(); init();