Apply Clang Format

This commit is contained in:
Carl Schwan
2020-11-02 16:11:24 +01:00
parent 9a2b7c0c83
commit bea870ad75
35 changed files with 5053 additions and 6370 deletions

2
.gitignore vendored
View File

@@ -1,3 +1,3 @@
build
.clang-format
.DS_Store

View File

@@ -7,6 +7,8 @@ find_package(ECM ${REQUIRED_KF5_VERSION} REQUIRED NO_MODULE)
set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake ${ECM_MODULE_PATH})
include(KDEClangFormat)
set(IDENTIFIER "org.kde.neochat")
set(COPYRIGHT "Copyright © 2018-2019 bhat@encom.eu.org, 2020 KDE Community")
@@ -255,3 +257,7 @@ if(LINUX)
DESTINATION ${CMAKE_INSTALL_DATADIR}/icons
)
endif(LINUX)
# add clang-format target for all our real source files
file(GLOB_RECURSE ALL_CLANG_FORMAT_SOURCE_FILES *.cpp *.h)
kde_clang_format(${ALL_CLANG_FORMAT_SOURCE_FILES})

View File

@@ -7,10 +7,13 @@
#include "room.h"
AccountListModel::AccountListModel(QObject* parent)
: QAbstractListModel(parent) {}
AccountListModel::AccountListModel(QObject *parent)
: QAbstractListModel(parent)
{
}
void AccountListModel::setController(Controller* value) {
void AccountListModel::setController(Controller *value)
{
if (m_controller == value) {
return;
}
@@ -21,26 +24,22 @@ void AccountListModel::setController(Controller* value) {
m_controller = value;
m_connections += m_controller->connections();
connect(m_controller, &Controller::connectionAdded, this,
[=](Connection* conn) {
connect(m_controller, &Controller::connectionAdded, this, [=](Connection *conn) {
if (!conn) {
return;
}
beginInsertRows(QModelIndex(), m_connections.count(),
m_connections.count());
beginInsertRows(QModelIndex(), m_connections.count(), m_connections.count());
m_connections.append(conn);
endInsertRows();
});
connect(m_controller, &Controller::connectionDropped, this,
[=](Connection* conn) {
connect(m_controller, &Controller::connectionDropped, this, [=](Connection *conn) {
qDebug() << "Dropping connection" << conn->userId();
if (!conn) {
qDebug() << "Trying to remove null connection";
return;
}
conn->disconnect(this);
const auto it =
std::find(m_connections.begin(), m_connections.end(), conn);
const auto it = std::find(m_connections.begin(), m_connections.end(), conn);
if (it == m_connections.end())
return; // Already deleted, nothing to do
const int row = it - m_connections.begin();
@@ -51,7 +50,8 @@ void AccountListModel::setController(Controller* value) {
emit controllerChanged();
}
QVariant AccountListModel::data(const QModelIndex& index, int role) const {
QVariant AccountListModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return {};
}
@@ -74,7 +74,8 @@ QVariant AccountListModel::data(const QModelIndex& index, int role) const {
return {};
}
int AccountListModel::rowCount(const QModelIndex& parent) const {
int AccountListModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid()) {
return 0;
}
@@ -82,7 +83,8 @@ int AccountListModel::rowCount(const QModelIndex& parent) const {
return m_connections.count();
}
QHash<int, QByteArray> AccountListModel::roleNames() const {
QHash<int, QByteArray> AccountListModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[UserRole] = "user";

View File

@@ -11,28 +11,31 @@
#include <QAbstractListModel>
#include <QObject>
class AccountListModel : public QAbstractListModel {
class AccountListModel : public QAbstractListModel
{
Q_OBJECT
Q_PROPERTY(Controller* controller READ controller WRITE setController NOTIFY
controllerChanged)
public:
Q_PROPERTY(Controller *controller READ controller WRITE setController NOTIFY controllerChanged)
public:
enum EventRoles { UserRole = Qt::UserRole + 1, ConnectionRole };
AccountListModel(QObject* parent = nullptr);
AccountListModel(QObject *parent = nullptr);
QVariant data(const QModelIndex& index, int role = UserRole) const override;
int rowCount(const QModelIndex& parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = UserRole) const override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QHash<int, QByteArray> roleNames() const override;
Controller* controller() const { return m_controller; }
void setController(Controller* value);
Controller *controller() const
{
return m_controller;
}
void setController(Controller *value);
private:
Controller* m_controller = nullptr;
QVector<Connection*> m_connections;
private:
Controller *m_controller = nullptr;
QVector<Connection *> m_connections;
signals:
signals:
void controllerChanged();
};

View File

@@ -37,45 +37,44 @@
#include "spectraluser.h"
#include "utils.h"
Controller::Controller(QObject* parent) : QObject(parent) {
Controller::Controller(QObject *parent)
: QObject(parent)
{
QApplication::setQuitOnLastWindowClosed(false);
Connection::setRoomType<SpectralRoom>();
Connection::setUserType<SpectralUser>();
connect(&m_ncm, &QNetworkConfigurationManager::onlineStateChanged, this,
&Controller::isOnlineChanged);
connect(&m_ncm, &QNetworkConfigurationManager::onlineStateChanged, this, &Controller::isOnlineChanged);
QTimer::singleShot(0, this, [=] { invokeLogin(); });
QTimer::singleShot(0, this, [=] {
invokeLogin();
});
}
Controller::~Controller() {
Controller::~Controller()
{
for (auto c : m_connections) {
c->stopSync();
c->saveState();
}
}
inline QString accessTokenFileName(const AccountSettings& account) {
inline QString accessTokenFileName(const AccountSettings &account)
{
QString fileName = account.userId();
fileName.replace(':', '_');
return QStandardPaths::writableLocation(
QStandardPaths::AppLocalDataLocation) +
'/' + fileName;
return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + '/' + fileName;
}
void Controller::loginWithCredentials(QString serverAddr,
QString user,
QString pass,
QString deviceName) {
void Controller::loginWithCredentials(QString serverAddr, QString user, QString pass, QString deviceName)
{
if (user.isEmpty() || pass.isEmpty()) {
return;
}
if (deviceName.isEmpty()) {
deviceName = "Spectral " + QSysInfo::machineHostName() + " " +
QSysInfo::productType() + " " + QSysInfo::productVersion() +
" " + QSysInfo::currentCpuArchitecture();
deviceName = "Spectral " + QSysInfo::machineHostName() + " " + QSysInfo::productType() + " " + QSysInfo::productVersion() + " " + QSysInfo::currentCpuArchitecture();
}
QUrl serverUrl(serverAddr);
@@ -99,8 +98,7 @@ void Controller::loginWithCredentials(QString serverAddr,
addConnection(conn);
setConnection(conn);
});
connect(conn, &Connection::networkError,
[=](QString error, QString, int, int) {
connect(conn, &Connection::networkError, [=](QString error, QString, int, int) {
emit errorOccured("Network Error", error);
});
connect(conn, &Connection::loginError, [=](QString error, QString) {
@@ -108,10 +106,8 @@ void Controller::loginWithCredentials(QString serverAddr,
});
}
void Controller::loginWithAccessToken(QString serverAddr,
QString user,
QString token,
QString deviceName) {
void Controller::loginWithAccessToken(QString serverAddr, QString user, QString token, QString deviceName)
{
if (user.isEmpty() || token.isEmpty()) {
return;
}
@@ -136,14 +132,14 @@ void Controller::loginWithAccessToken(QString serverAddr,
addConnection(conn);
setConnection(conn);
});
connect(conn, &Connection::networkError,
[=](QString error, QString, int, int) {
connect(conn, &Connection::networkError, [=](QString error, QString, int, int) {
emit errorOccured("Network Error", error);
});
conn->connectWithToken(user, token, deviceName);
}
void Controller::logout(Connection* conn) {
void Controller::logout(Connection *conn)
{
if (!conn) {
qCritical() << "Attempt to logout null connection";
return;
@@ -156,8 +152,7 @@ void Controller::logout(Connection* conn) {
job.setAutoDelete(true);
job.setKey(conn->userId());
QEventLoop loop;
QKeychain::DeletePasswordJob::connect(&job, &QKeychain::Job::finished, &loop,
&QEventLoop::quit);
QKeychain::DeletePasswordJob::connect(&job, &QKeychain::Job::finished, &loop, &QEventLoop::quit);
job.start();
loop.exec();
@@ -174,7 +169,8 @@ void Controller::logout(Connection* conn) {
});
}
void Controller::addConnection(Connection* c) {
void Controller::addConnection(Connection *c)
{
Q_ASSERT_X(c, __FUNCTION__, "Attempt to add a null connection");
m_connections += c;
@@ -189,9 +185,10 @@ void Controller::addConnection(Connection* c) {
c->sync(30000);
c->saveState();
});
connect(c, &Connection::loggedOut, this, [=] { dropConnection(c); });
connect(&m_ncm, &QNetworkConfigurationManager::onlineStateChanged,
[=](bool status) {
connect(c, &Connection::loggedOut, this, [=] {
dropConnection(c);
});
connect(&m_ncm, &QNetworkConfigurationManager::onlineStateChanged, [=](bool status) {
if (!status) {
return;
}
@@ -209,7 +206,8 @@ void Controller::addConnection(Connection* c) {
emit connectionAdded(c);
}
void Controller::dropConnection(Connection* c) {
void Controller::dropConnection(Connection *c)
{
Q_ASSERT_X(c, __FUNCTION__, "Attempt to drop a null connection");
m_connections.removeOne(c);
@@ -217,11 +215,12 @@ void Controller::dropConnection(Connection* c) {
c->deleteLater();
}
void Controller::invokeLogin() {
void Controller::invokeLogin()
{
using namespace Quotient;
const auto accounts = SettingsGroup("Accounts").childGroups();
for (const auto& accountId : accounts) {
AccountSettings account{accountId};
for (const auto &accountId : accounts) {
AccountSettings account {accountId};
if (!account.homeserver().isEmpty()) {
auto accessToken = loadAccessTokenFromKeyChain(account);
@@ -235,8 +234,7 @@ void Controller::invokeLogin() {
emit errorOccured("Login Failed", error);
logout(c);
});
connect(c, &Connection::networkError,
[=](QString error, QString, int, int) {
connect(c, &Connection::networkError, [=](QString error, QString, int, int) {
emit errorOccured("Network Error", error);
});
c->connectWithToken(account.userId(), accessToken, account.deviceId());
@@ -250,32 +248,28 @@ void Controller::invokeLogin() {
emit initiated();
}
QByteArray Controller::loadAccessTokenFromFile(const AccountSettings& account) {
QFile accountTokenFile{accessTokenFileName(account)};
QByteArray Controller::loadAccessTokenFromFile(const AccountSettings &account)
{
QFile accountTokenFile {accessTokenFileName(account)};
if (accountTokenFile.open(QFile::ReadOnly)) {
if (accountTokenFile.size() < 1024)
return accountTokenFile.readAll();
qWarning() << "File" << accountTokenFile.fileName() << "is"
<< accountTokenFile.size()
<< "bytes long - too long for a token, ignoring it.";
qWarning() << "File" << accountTokenFile.fileName() << "is" << accountTokenFile.size() << "bytes long - too long for a token, ignoring it.";
}
qWarning() << "Could not open access token file"
<< accountTokenFile.fileName();
qWarning() << "Could not open access token file" << accountTokenFile.fileName();
return {};
}
QByteArray Controller::loadAccessTokenFromKeyChain(
const AccountSettings& account) {
qDebug() << "Read the access token from the keychain for "
<< account.userId();
QByteArray Controller::loadAccessTokenFromKeyChain(const AccountSettings &account)
{
qDebug() << "Read the access token from the keychain for " << account.userId();
QKeychain::ReadPasswordJob job(qAppName());
job.setAutoDelete(false);
job.setKey(account.userId());
QEventLoop loop;
QKeychain::ReadPasswordJob::connect(&job, &QKeychain::Job::finished, &loop,
&QEventLoop::quit);
QKeychain::ReadPasswordJob::connect(&job, &QKeychain::Job::finished, &loop, &QEventLoop::quit);
job.start();
loop.exec();
@@ -283,18 +277,16 @@ QByteArray Controller::loadAccessTokenFromKeyChain(
return job.binaryData();
}
qWarning() << "Could not read the access token from the keychain: "
<< qPrintable(job.errorString());
qWarning() << "Could not read the access token from the keychain: " << qPrintable(job.errorString());
// no access token from the keychain, try token file
auto accessToken = loadAccessTokenFromFile(account);
if (job.error() == QKeychain::Error::EntryNotFound) {
if (!accessToken.isEmpty()) {
qDebug() << "Migrating the access token from file to the keychain for "
<< account.userId();
qDebug() << "Migrating the access token from file to the keychain for " << account.userId();
bool removed = false;
bool saved = saveAccessTokenToKeyChain(account, accessToken);
if (saved) {
QFile accountTokenFile{accessTokenFileName(account)};
QFile accountTokenFile {accessTokenFileName(account)};
removed = accountTokenFile.remove();
}
if (!(saved && removed)) {
@@ -307,15 +299,14 @@ QByteArray Controller::loadAccessTokenFromKeyChain(
return accessToken;
}
bool Controller::saveAccessTokenToFile(const AccountSettings& account,
const QByteArray& accessToken) {
bool Controller::saveAccessTokenToFile(const AccountSettings &account, const QByteArray &accessToken)
{
// (Re-)Make a dedicated file for access_token.
QFile accountTokenFile{accessTokenFileName(account)};
QFile accountTokenFile {accessTokenFileName(account)};
accountTokenFile.remove(); // Just in case
auto fileDir = QFileInfo(accountTokenFile).dir();
if (!((fileDir.exists() || fileDir.mkpath(".")) &&
accountTokenFile.open(QFile::WriteOnly))) {
if (!((fileDir.exists() || fileDir.mkpath(".")) && accountTokenFile.open(QFile::WriteOnly))) {
emit errorOccured("I/O Denied", "Cannot save access token.");
} else {
accountTokenFile.write(accessToken);
@@ -324,65 +315,66 @@ bool Controller::saveAccessTokenToFile(const AccountSettings& account,
return false;
}
bool Controller::saveAccessTokenToKeyChain(const AccountSettings& account,
const QByteArray& accessToken) {
bool Controller::saveAccessTokenToKeyChain(const AccountSettings &account, const QByteArray &accessToken)
{
qDebug() << "Save the access token to the keychain for " << account.userId();
QKeychain::WritePasswordJob job(qAppName());
job.setAutoDelete(false);
job.setKey(account.userId());
job.setBinaryData(accessToken);
QEventLoop loop;
QKeychain::WritePasswordJob::connect(&job, &QKeychain::Job::finished, &loop,
&QEventLoop::quit);
QKeychain::WritePasswordJob::connect(&job, &QKeychain::Job::finished, &loop, &QEventLoop::quit);
job.start();
loop.exec();
if (job.error()) {
qWarning() << "Could not save access token to the keychain: "
<< qPrintable(job.errorString());
qWarning() << "Could not save access token to the keychain: " << qPrintable(job.errorString());
return saveAccessTokenToFile(account, accessToken);
}
return true;
}
void Controller::joinRoom(Connection* c, const QString& alias) {
void Controller::joinRoom(Connection *c, const QString &alias)
{
if (!alias.contains(":"))
return;
auto knownServer = alias.mid(alias.indexOf(":") + 1);
auto joinRoomJob = c->joinRoom(alias, QStringList{knownServer});
auto joinRoomJob = c->joinRoom(alias, QStringList {knownServer});
joinRoomJob->connect(joinRoomJob, &JoinRoomJob::failure, [=] {
emit errorOccured("Join Room Failed", joinRoomJob->errorString());
});
}
void Controller::createRoom(Connection* c,
const QString& name,
const QString& topic) {
auto createRoomJob =
c->createRoom(Connection::PublishRoom, "", name, topic, QStringList());
void Controller::createRoom(Connection *c, const QString &name, const QString &topic)
{
auto createRoomJob = c->createRoom(Connection::PublishRoom, "", name, topic, QStringList());
createRoomJob->connect(createRoomJob, &CreateRoomJob::failure, [=] {
emit errorOccured("Create Room Failed", createRoomJob->errorString());
});
}
void Controller::createDirectChat(Connection* c, const QString& userID) {
void Controller::createDirectChat(Connection *c, const QString &userID)
{
auto createRoomJob = c->createDirectChat(userID);
createRoomJob->connect(createRoomJob, &CreateRoomJob::failure, [=] {
emit errorOccured("Create Direct Chat Failed",
createRoomJob->errorString());
emit errorOccured("Create Direct Chat Failed", createRoomJob->errorString());
});
}
void Controller::playAudio(QUrl localFile) {
void Controller::playAudio(QUrl localFile)
{
auto player = new QMediaPlayer;
player->setMedia(localFile);
player->play();
connect(player, &QMediaPlayer::stateChanged, [=] { player->deleteLater(); });
connect(player, &QMediaPlayer::stateChanged, [=] {
player->deleteLater();
});
}
void Controller::changeAvatar(Connection* conn, QUrl localFile) {
void Controller::changeAvatar(Connection *conn, QUrl localFile)
{
auto job = conn->uploadFile(localFile.toLocalFile());
if (isJobRunning(job)) {
connect(job, &BaseJob::success, this, [conn, job] {
@@ -391,7 +383,8 @@ void Controller::changeAvatar(Connection* conn, QUrl localFile) {
}
}
void Controller::markAllMessagesAsRead(Connection* conn) {
void Controller::markAllMessagesAsRead(Connection *conn)
{
for (auto room : conn->allRooms()) {
room->markAllMessagesAsRead();
}

View File

@@ -22,37 +22,43 @@
using namespace Quotient;
class Controller : public QObject {
class Controller : public QObject
{
Q_OBJECT
Q_PROPERTY(int accountCount READ accountCount NOTIFY connectionAdded NOTIFY
connectionDropped)
Q_PROPERTY(bool quitOnLastWindowClosed READ quitOnLastWindowClosed WRITE
setQuitOnLastWindowClosed NOTIFY quitOnLastWindowClosedChanged)
Q_PROPERTY(Connection* connection READ connection WRITE setConnection NOTIFY
connectionChanged)
Q_PROPERTY(int accountCount READ accountCount NOTIFY connectionAdded NOTIFY connectionDropped)
Q_PROPERTY(bool quitOnLastWindowClosed READ quitOnLastWindowClosed WRITE setQuitOnLastWindowClosed NOTIFY quitOnLastWindowClosedChanged)
Q_PROPERTY(Connection *connection READ connection WRITE setConnection NOTIFY connectionChanged)
Q_PROPERTY(bool isOnline READ isOnline NOTIFY isOnlineChanged)
Q_PROPERTY(bool busy READ busy WRITE setBusy NOTIFY busyChanged)
public:
explicit Controller(QObject* parent = nullptr);
public:
explicit Controller(QObject *parent = nullptr);
~Controller();
Q_INVOKABLE void loginWithCredentials(QString, QString, QString, QString);
Q_INVOKABLE void loginWithAccessToken(QString, QString, QString, QString);
QVector<Connection*> connections() const { return m_connections; }
QVector<Connection *> connections() const
{
return m_connections;
}
// All the non-Q_INVOKABLE functions.
void addConnection(Connection* c);
void dropConnection(Connection* c);
void addConnection(Connection *c);
void dropConnection(Connection *c);
// All the Q_PROPERTYs.
int accountCount() { return m_connections.count(); }
int accountCount()
{
return m_connections.count();
}
bool quitOnLastWindowClosed() const {
bool quitOnLastWindowClosed() const
{
return QApplication::quitOnLastWindowClosed();
}
void setQuitOnLastWindowClosed(bool value) {
void setQuitOnLastWindowClosed(bool value)
{
if (quitOnLastWindowClosed() != value) {
QApplication::setQuitOnLastWindowClosed(value);
@@ -60,10 +66,17 @@ class Controller : public QObject {
}
}
bool isOnline() const { return m_ncm.isOnline(); }
bool isOnline() const
{
return m_ncm.isOnline();
}
bool busy() const { return m_busy; }
void setBusy(bool busy) {
bool busy() const
{
return m_busy;
}
void setBusy(bool busy)
{
if (m_busy == busy) {
return;
}
@@ -71,45 +84,45 @@ class Controller : public QObject {
emit busyChanged();
}
Connection* connection() const {
Connection *connection() const
{
if (m_connection.isNull())
return nullptr;
return m_connection;
}
void setConnection(Connection* conn) {
void setConnection(Connection *conn)
{
if (conn == m_connection)
return;
m_connection = conn;
emit connectionChanged();
}
private:
QVector<Connection*> m_connections;
private:
QVector<Connection *> m_connections;
QPointer<Connection> m_connection;
QNetworkConfigurationManager m_ncm;
bool m_busy = false;
QByteArray loadAccessTokenFromFile(const AccountSettings& account);
QByteArray loadAccessTokenFromKeyChain(const AccountSettings& account);
QByteArray loadAccessTokenFromFile(const AccountSettings &account);
QByteArray loadAccessTokenFromKeyChain(const AccountSettings &account);
bool saveAccessTokenToFile(const AccountSettings& account,
const QByteArray& accessToken);
bool saveAccessTokenToKeyChain(const AccountSettings& account,
const QByteArray& accessToken);
bool saveAccessTokenToFile(const AccountSettings &account, const QByteArray &accessToken);
bool saveAccessTokenToKeyChain(const AccountSettings &account, const QByteArray &accessToken);
void loadSettings();
void saveSettings() const;
private slots:
private slots:
void invokeLogin();
signals:
signals:
void busyChanged();
void errorOccured(QString error, QString detail);
void syncDone();
void connectionAdded(Connection* conn);
void connectionDropped(Connection* conn);
void connectionAdded(Connection *conn);
void connectionDropped(Connection *conn);
void initiated();
void notificationClicked(const QString roomId, const QString eventId);
void quitOnLastWindowClosedChanged();
@@ -117,14 +130,14 @@ class Controller : public QObject {
void connectionChanged();
void isOnlineChanged();
public slots:
void logout(Connection* conn);
void joinRoom(Connection* c, const QString& alias);
void createRoom(Connection* c, const QString& name, const QString& topic);
void createDirectChat(Connection* c, const QString& userID);
public slots:
void logout(Connection *conn);
void joinRoom(Connection *c, const QString &alias);
void createRoom(Connection *c, const QString &name, const QString &topic);
void createDirectChat(Connection *c, const QString &userID);
void playAudio(QUrl localFile);
void changeAvatar(Connection* conn, QUrl localFile);
void markAllMessagesAsRead(Connection* conn);
void changeAvatar(Connection *conn, QUrl localFile);
void markAllMessagesAsRead(Connection *conn);
};
#endif // CONTROLLER_H

File diff suppressed because it is too large Load Diff

View File

@@ -12,16 +12,24 @@
#include <QVector>
struct Emoji {
Emoji(const QString& u, const QString& s) : unicode(u), shortname(s) {}
Emoji() {}
Emoji(const QString &u, const QString &s)
: unicode(u)
, shortname(s)
{
}
Emoji()
{
}
friend QDataStream& operator<<(QDataStream& arch, const Emoji& object) {
friend QDataStream &operator<<(QDataStream &arch, const Emoji &object)
{
arch << object.unicode;
arch << object.shortname;
return arch;
}
friend QDataStream& operator>>(QDataStream& arch, Emoji& object) {
friend QDataStream &operator>>(QDataStream &arch, Emoji &object)
{
arch >> object.unicode;
arch >> object.shortname;
return arch;
@@ -37,7 +45,8 @@ struct Emoji {
Q_DECLARE_METATYPE(Emoji)
class EmojiModel : public QObject {
class EmojiModel : public QObject
{
Q_OBJECT
Q_PROPERTY(QVariantList history READ history NOTIFY historyChanged)
@@ -51,20 +60,23 @@ class EmojiModel : public QObject {
Q_PROPERTY(QVariantList symbols MEMBER symbols CONSTANT)
Q_PROPERTY(QVariantList flags MEMBER flags CONSTANT)
public:
explicit EmojiModel(QObject* parent = nullptr)
: QObject(parent), m_settings(new QSettings()) {}
public:
explicit EmojiModel(QObject *parent = nullptr)
: QObject(parent)
, m_settings(new QSettings())
{
}
Q_INVOKABLE QVariantList history();
Q_INVOKABLE QVariantList filterModel(const QString& filter);
Q_INVOKABLE QVariantList filterModel(const QString &filter);
signals:
signals:
void historyChanged();
public slots:
public slots:
void emojiUsed(QVariant modelData);
private:
private:
static const QVariantList people;
static const QVariantList nature;
static const QVariantList food;
@@ -74,7 +86,7 @@ class EmojiModel : public QObject {
static const QVariantList symbols;
static const QVariantList flags;
QSettings* m_settings;
QSettings *m_settings;
};
#endif // EMOJIMODEL_H

View File

@@ -11,21 +11,25 @@
#include <QUrl>
#include <QtDebug>
ImageClipboard::ImageClipboard(QObject* parent)
: QObject(parent), m_clipboard(QGuiApplication::clipboard()) {
connect(m_clipboard, &QClipboard::changed, this,
&ImageClipboard::imageChanged);
ImageClipboard::ImageClipboard(QObject *parent)
: QObject(parent)
, m_clipboard(QGuiApplication::clipboard())
{
connect(m_clipboard, &QClipboard::changed, this, &ImageClipboard::imageChanged);
}
bool ImageClipboard::hasImage() const {
bool ImageClipboard::hasImage() const
{
return !image().isNull();
}
QImage ImageClipboard::image() const {
QImage ImageClipboard::image() const
{
return m_clipboard->image();
}
bool ImageClipboard::saveImage(const QUrl& localPath) {
bool ImageClipboard::saveImage(const QUrl &localPath)
{
if (!localPath.isLocalFile())
return false;

View File

@@ -10,23 +10,24 @@
#include <QImage>
#include <QObject>
class ImageClipboard : public QObject {
class ImageClipboard : public QObject
{
Q_OBJECT
Q_PROPERTY(bool hasImage READ hasImage NOTIFY imageChanged)
Q_PROPERTY(QImage image READ image NOTIFY imageChanged)
public:
explicit ImageClipboard(QObject* parent = nullptr);
public:
explicit ImageClipboard(QObject *parent = nullptr);
bool hasImage() const;
QImage image() const;
Q_INVOKABLE bool saveImage(const QUrl& localPath);
Q_INVOKABLE bool saveImage(const QUrl &localPath);
private:
QClipboard* m_clipboard;
private:
QClipboard *m_clipboard;
signals:
signals:
void imageChanged();
};

View File

@@ -30,7 +30,8 @@
using namespace Quotient;
int main(int argc, char* argv[]) {
int main(int argc, char *argv[])
{
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QNetworkProxyFactory::setUseSystemConfiguration(true);
@@ -48,36 +49,32 @@ int main(int argc, char* argv[]) {
qmlRegisterType<UserListModel>("Spectral", 0, 1, "UserListModel");
qmlRegisterType<MessageEventModel>("Spectral", 0, 1, "MessageEventModel");
qmlRegisterType<PublicRoomListModel>("Spectral", 0, 1, "PublicRoomListModel");
qmlRegisterType<UserDirectoryListModel>("Spectral", 0, 1,
"UserDirectoryListModel");
qmlRegisterType<UserDirectoryListModel>("Spectral", 0, 1, "UserDirectoryListModel");
qmlRegisterType<EmojiModel>("Spectral", 0, 1, "EmojiModel");
qmlRegisterType<NotificationsManager>("Spectral", 0, 1,
"NotificationsManager");
qmlRegisterType<NotificationsManager>("Spectral", 0, 1, "NotificationsManager");
qmlRegisterType<TrayIcon>("Spectral", 0, 1, "TrayIcon");
qmlRegisterType<ImageClipboard>("Spectral", 0, 1, "ImageClipboard");
qmlRegisterUncreatableType<RoomMessageEvent>("Spectral", 0, 1,
"RoomMessageEvent", "ENUM");
qmlRegisterUncreatableType<RoomMessageEvent>("Spectral", 0, 1, "RoomMessageEvent", "ENUM");
qmlRegisterUncreatableType<RoomType>("Spectral", 0, 1, "RoomType", "ENUM");
qmlRegisterUncreatableType<UserType>("Spectral", 0, 1, "UserType", "ENUM");
qRegisterMetaType<User*>("User*");
qRegisterMetaType<User*>("const User*");
qRegisterMetaType<User*>("const Quotient::User*");
qRegisterMetaType<Room*>("Room*");
qRegisterMetaType<Connection*>("Connection*");
qRegisterMetaType<User *>("User*");
qRegisterMetaType<User *>("const User*");
qRegisterMetaType<User *>("const Quotient::User*");
qRegisterMetaType<Room *>("Room*");
qRegisterMetaType<Connection *>("Connection*");
qRegisterMetaType<MessageEventType>("MessageEventType");
qRegisterMetaType<SpectralRoom*>("SpectralRoom*");
qRegisterMetaType<SpectralUser*>("SpectralUser*");
qRegisterMetaType<GetRoomEventsJob*>("GetRoomEventsJob*");
qRegisterMetaType<SpectralRoom *>("SpectralRoom*");
qRegisterMetaType<SpectralUser *>("SpectralUser*");
qRegisterMetaType<GetRoomEventsJob *>("GetRoomEventsJob*");
qRegisterMetaTypeStreamOperators<Emoji>();
QQmlApplicationEngine engine;
engine.addImportPath("qrc:/imports");
MatrixImageProvider* matrixImageProvider = new MatrixImageProvider();
engine.rootContext()->setContextProperty("imageProvider",
matrixImageProvider);
MatrixImageProvider *matrixImageProvider = new MatrixImageProvider();
engine.rootContext()->setContextProperty("imageProvider", matrixImageProvider);
engine.addImageProvider(QLatin1String("mxc"), matrixImageProvider);
engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml")));

View File

@@ -14,27 +14,20 @@
using Quotient::BaseJob;
ThumbnailResponse::ThumbnailResponse(Quotient::Connection* c,
QString id,
const QSize& size)
: c(c),
mediaId(std::move(id)),
requestedSize(size),
localFile(QStringLiteral("%1/image_provider/%2-%3x%4.png")
.arg(QStandardPaths::writableLocation(
QStandardPaths::CacheLocation),
mediaId,
QString::number(requestedSize.width()),
QString::number(requestedSize.height()))),
errorStr("Image request hasn't started") {
ThumbnailResponse::ThumbnailResponse(Quotient::Connection *c, QString id, const QSize &size)
: c(c)
, mediaId(std::move(id))
, requestedSize(size)
, localFile(QStringLiteral("%1/image_provider/%2-%3x%4.png").arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation), mediaId, QString::number(requestedSize.width()), QString::number(requestedSize.height())))
, errorStr("Image request hasn't started")
{
if (requestedSize.isEmpty()) {
errorStr.clear();
emit finished();
return;
}
if (mediaId.count('/') != 1) {
errorStr =
tr("Media id '%1' doesn't follow server/mediaId pattern").arg(mediaId);
errorStr = tr("Media id '%1' doesn't follow server/mediaId pattern").arg(mediaId);
emit finished();
return;
}
@@ -54,11 +47,11 @@ ThumbnailResponse::ThumbnailResponse(Quotient::Connection* c,
// Execute a request on the main thread asynchronously
moveToThread(c->thread());
QMetaObject::invokeMethod(this, &ThumbnailResponse::startRequest,
Qt::QueuedConnection);
QMetaObject::invokeMethod(this, &ThumbnailResponse::startRequest, Qt::QueuedConnection);
}
void ThumbnailResponse::startRequest() {
void ThumbnailResponse::startRequest()
{
// Runs in the main thread, not QML thread
Q_ASSERT(QThread::currentThread() == c->thread());
job = c->getThumbnail(mediaId, requestedSize);
@@ -67,7 +60,8 @@ void ThumbnailResponse::startRequest() {
connect(job, &BaseJob::finished, this, &ThumbnailResponse::prepareResult);
}
void ThumbnailResponse::prepareResult() {
void ThumbnailResponse::prepareResult()
{
Q_ASSERT(QThread::currentThread() == job->thread());
Q_ASSERT(job->error() != BaseJob::Pending);
{
@@ -88,15 +82,15 @@ void ThumbnailResponse::prepareResult() {
qDebug() << "ThumbnailResponse: cancelled for" << mediaId;
} else {
errorStr = job->errorString();
qWarning() << "ThumbnailResponse: no valid image for" << mediaId << "-"
<< errorStr;
qWarning() << "ThumbnailResponse: no valid image for" << mediaId << "-" << errorStr;
}
job = nullptr;
}
emit finished();
}
void ThumbnailResponse::doCancel() {
void ThumbnailResponse::doCancel()
{
// Runs in the main thread, not QML thread
if (job) {
Q_ASSERT(QThread::currentThread() == job->thread());
@@ -104,23 +98,24 @@ void ThumbnailResponse::doCancel() {
}
}
QQuickTextureFactory* ThumbnailResponse::textureFactory() const {
QQuickTextureFactory *ThumbnailResponse::textureFactory() const
{
QReadLocker _(&lock);
return QQuickTextureFactory::textureFactoryForImage(image);
}
QString ThumbnailResponse::errorString() const {
QString ThumbnailResponse::errorString() const
{
QReadLocker _(&lock);
return errorStr;
}
void ThumbnailResponse::cancel() {
QMetaObject::invokeMethod(this, &ThumbnailResponse::doCancel,
Qt::QueuedConnection);
void ThumbnailResponse::cancel()
{
QMetaObject::invokeMethod(this, &ThumbnailResponse::doCancel, Qt::QueuedConnection);
}
QQuickImageResponse* MatrixImageProvider::requestImageResponse(
const QString& id,
const QSize& requestedSize) {
QQuickImageResponse *MatrixImageProvider::requestImageResponse(const QString &id, const QSize &requestedSize)
{
return new ThumbnailResponse(m_connection.loadRelaxed(), id, requestedSize);
}

View File

@@ -16,60 +16,62 @@
#include <QtCore/QAtomicPointer>
#include <QtCore/QReadWriteLock>
namespace Quotient {
namespace Quotient
{
class Connection;
}
class ThumbnailResponse : public QQuickImageResponse {
class ThumbnailResponse : public QQuickImageResponse
{
Q_OBJECT
public:
ThumbnailResponse(Quotient::Connection* c,
QString mediaId,
const QSize& requestedSize);
public:
ThumbnailResponse(Quotient::Connection *c, QString mediaId, const QSize &requestedSize);
~ThumbnailResponse() override = default;
private slots:
private slots:
void startRequest();
void prepareResult();
void doCancel();
private:
Quotient::Connection* c;
private:
Quotient::Connection *c;
const QString mediaId;
const QSize requestedSize;
const QString localFile;
Quotient::MediaThumbnailJob* job = nullptr;
Quotient::MediaThumbnailJob *job = nullptr;
QImage image;
QString errorStr;
mutable QReadWriteLock lock; // Guards ONLY these two members above
QQuickTextureFactory* textureFactory() const override;
QQuickTextureFactory *textureFactory() const override;
QString errorString() const override;
void cancel() override;
};
class MatrixImageProvider : public QObject, public QQuickAsyncImageProvider {
class MatrixImageProvider : public QObject, public QQuickAsyncImageProvider
{
Q_OBJECT
Q_PROPERTY(Quotient::Connection* connection READ connection WRITE
setConnection NOTIFY connectionChanged)
public:
Q_PROPERTY(Quotient::Connection *connection READ connection WRITE setConnection NOTIFY connectionChanged)
public:
explicit MatrixImageProvider() = default;
QQuickImageResponse* requestImageResponse(
const QString& id,
const QSize& requestedSize) override;
QQuickImageResponse *requestImageResponse(const QString &id, const QSize &requestedSize) override;
Quotient::Connection* connection() { return m_connection; }
void setConnection(Quotient::Connection* connection) {
Quotient::Connection *connection()
{
return m_connection;
}
void setConnection(Quotient::Connection *connection)
{
m_connection.storeRelaxed(connection);
emit connectionChanged();
}
signals:
signals:
void connectionChanged();
private:
private:
QAtomicPointer<Quotient::Connection> m_connection;
};

View File

@@ -14,7 +14,8 @@
#include "utils.h"
QHash<int, QByteArray> MessageEventModel::roleNames() const {
QHash<int, QByteArray> MessageEventModel::roleNames() const
{
QHash<int, QByteArray> roles = QAbstractItemModel::roleNames();
roles[EventTypeRole] = "eventType";
roles[MessageRole] = "message";
@@ -38,18 +39,22 @@ QHash<int, QByteArray> MessageEventModel::roleNames() const {
return roles;
}
MessageEventModel::MessageEventModel(QObject* parent)
: QAbstractListModel(parent), m_currentRoom(nullptr) {
MessageEventModel::MessageEventModel(QObject *parent)
: QAbstractListModel(parent)
, m_currentRoom(nullptr)
{
using namespace Quotient;
qmlRegisterType<FileTransferInfo>();
qRegisterMetaType<FileTransferInfo>();
qmlRegisterUncreatableType<EventStatus>(
"Spectral", 0, 1, "EventStatus", "EventStatus is not an creatable type");
qmlRegisterUncreatableType<EventStatus>("Spectral", 0, 1, "EventStatus", "EventStatus is not an creatable type");
}
MessageEventModel::~MessageEventModel() {}
MessageEventModel::~MessageEventModel()
{
}
void MessageEventModel::setRoom(SpectralRoom* room) {
void MessageEventModel::setRoom(SpectralRoom *room)
{
if (room == m_currentRoom)
return;
@@ -63,36 +68,28 @@ void MessageEventModel::setRoom(SpectralRoom* room) {
lastReadEventId = room->readMarkerEventId();
using namespace Quotient;
connect(m_currentRoom, &Room::aboutToAddNewMessages, this,
[=](RoomEventsRange events) {
beginInsertRows({}, timelineBaseIndex(),
timelineBaseIndex() + int(events.size()) - 1);
connect(m_currentRoom, &Room::aboutToAddNewMessages, this, [=](RoomEventsRange events) {
beginInsertRows({}, timelineBaseIndex(), timelineBaseIndex() + int(events.size()) - 1);
});
connect(m_currentRoom, &Room::aboutToAddHistoricalMessages, this,
[=](RoomEventsRange events) {
connect(m_currentRoom, &Room::aboutToAddHistoricalMessages, this, [=](RoomEventsRange events) {
if (rowCount() > 0)
rowBelowInserted = rowCount() - 1; // See #312
beginInsertRows({}, rowCount(),
rowCount() + int(events.size()) - 1);
beginInsertRows({}, rowCount(), rowCount() + int(events.size()) - 1);
});
connect(m_currentRoom, &Room::addedMessages, this,
[=](int lowest, int biggest) {
connect(m_currentRoom, &Room::addedMessages, this, [=](int lowest, int biggest) {
endInsertRows();
if (biggest < m_currentRoom->maxTimelineIndex()) {
auto rowBelowInserted = m_currentRoom->maxTimelineIndex() -
biggest + timelineBaseIndex() - 1;
refreshEventRoles(rowBelowInserted,
{ShowAuthorRole});
auto rowBelowInserted = m_currentRoom->maxTimelineIndex() - biggest + timelineBaseIndex() - 1;
refreshEventRoles(rowBelowInserted, {ShowAuthorRole});
}
for (auto i = m_currentRoom->maxTimelineIndex() - biggest;
i <= m_currentRoom->maxTimelineIndex() - lowest; ++i)
for (auto i = m_currentRoom->maxTimelineIndex() - biggest; i <= m_currentRoom->maxTimelineIndex() - lowest; ++i)
refreshLastUserEvents(i);
});
connect(m_currentRoom, &Room::pendingEventAboutToAdd, this,
[this] { beginInsertRows({}, 0, 0); });
connect(m_currentRoom, &Room::pendingEventAboutToAdd, this, [this] {
beginInsertRows({}, 0, 0);
});
connect(m_currentRoom, &Room::pendingEventAdded, this, &MessageEventModel::endInsertRows);
connect(m_currentRoom, &Room::pendingEventAboutToMerge, this,
[this](RoomEvent*, int i) {
connect(m_currentRoom, &Room::pendingEventAboutToMerge, this, [this](RoomEvent *, int i) {
if (i == 0)
return; // No need to move anything, just refresh
@@ -111,77 +108,67 @@ void MessageEventModel::setRoom(SpectralRoom* room) {
if (m_currentRoom->timelineSize() > 1) // Refresh above
refreshEventRoles(timelineBaseIndex() + 1, {ReadMarkerRole});
if (timelineBaseIndex() > 0) // Refresh below, see #312
refreshEventRoles(timelineBaseIndex() - 1,
{ShowAuthorRole});
refreshEventRoles(timelineBaseIndex() - 1, {ShowAuthorRole});
});
connect(m_currentRoom, &Room::pendingEventChanged, this,
&MessageEventModel::refreshRow);
connect(m_currentRoom, &Room::pendingEventAboutToDiscard, this,
[this](int i) { beginRemoveRows({}, i, i); });
connect(m_currentRoom, &Room::pendingEventDiscarded, this,
&MessageEventModel::endRemoveRows);
connect(m_currentRoom, &Room::pendingEventChanged, this, &MessageEventModel::refreshRow);
connect(m_currentRoom, &Room::pendingEventAboutToDiscard, this, [this](int i) {
beginRemoveRows({}, i, i);
});
connect(m_currentRoom, &Room::pendingEventDiscarded, this, &MessageEventModel::endRemoveRows);
connect(m_currentRoom, &Room::readMarkerMoved, this, [this] {
refreshEventRoles(
std::exchange(lastReadEventId, m_currentRoom->readMarkerEventId()),
{ReadMarkerRole});
refreshEventRoles(std::exchange(lastReadEventId, m_currentRoom->readMarkerEventId()), {ReadMarkerRole});
refreshEventRoles(lastReadEventId, {ReadMarkerRole});
});
connect(m_currentRoom, &Room::replacedEvent, this,
[this](const RoomEvent* newEvent) {
refreshLastUserEvents(refreshEvent(newEvent->id()) -
timelineBaseIndex());
connect(m_currentRoom, &Room::replacedEvent, this, [this](const RoomEvent *newEvent) {
refreshLastUserEvents(refreshEvent(newEvent->id()) - timelineBaseIndex());
});
connect(m_currentRoom, &Room::updatedEvent, this,
[this](const QString& eventId) {
connect(m_currentRoom, &Room::updatedEvent, this, [this](const QString &eventId) {
if (eventId.isEmpty()) { // How did we get here?
return;
}
refreshEventRoles(eventId, {ReactionRole, Qt::DisplayRole});
});
connect(m_currentRoom, &Room::fileTransferProgress, this,
&MessageEventModel::refreshEvent);
connect(m_currentRoom, &Room::fileTransferCompleted, this,
&MessageEventModel::refreshEvent);
connect(m_currentRoom, &Room::fileTransferFailed, this,
&MessageEventModel::refreshEvent);
connect(m_currentRoom, &Room::fileTransferCancelled, this,
&MessageEventModel::refreshEvent);
connect(m_currentRoom, &Room::readMarkerForUserMoved, this,
[=](User*, QString fromEventId, QString toEventId) {
connect(m_currentRoom, &Room::fileTransferProgress, this, &MessageEventModel::refreshEvent);
connect(m_currentRoom, &Room::fileTransferCompleted, this, &MessageEventModel::refreshEvent);
connect(m_currentRoom, &Room::fileTransferFailed, this, &MessageEventModel::refreshEvent);
connect(m_currentRoom, &Room::fileTransferCancelled, this, &MessageEventModel::refreshEvent);
connect(m_currentRoom, &Room::readMarkerForUserMoved, this, [=](User *, QString fromEventId, QString toEventId) {
refreshEventRoles(fromEventId, {UserMarkerRole});
refreshEventRoles(toEventId, {UserMarkerRole});
});
connect(m_currentRoom->connection(), &Connection::ignoredUsersListChanged,
this, [=] {
connect(m_currentRoom->connection(), &Connection::ignoredUsersListChanged, this, [=] {
beginResetModel();
endResetModel();
});
qDebug() << "Connected to room" << room->id() << "as"
<< room->localUser()->id();
qDebug() << "Connected to room" << room->id() << "as" << room->localUser()->id();
} else
lastReadEventId.clear();
endResetModel();
}
int MessageEventModel::refreshEvent(const QString& eventId) {
int MessageEventModel::refreshEvent(const QString &eventId)
{
return refreshEventRoles(eventId);
}
void MessageEventModel::refreshRow(int row) {
void MessageEventModel::refreshRow(int row)
{
refreshEventRoles(row);
}
int MessageEventModel::timelineBaseIndex() const {
int MessageEventModel::timelineBaseIndex() const
{
return m_currentRoom ? int(m_currentRoom->pendingEvents().size()) : 0;
}
void MessageEventModel::refreshEventRoles(int row, const QVector<int>& roles) {
void MessageEventModel::refreshEventRoles(int row, const QVector<int> &roles)
{
const auto idx = index(row);
emit dataChanged(idx, idx, roles);
}
int MessageEventModel::refreshEventRoles(const QString& id,
const QVector<int>& roles) {
int MessageEventModel::refreshEventRoles(const QString &id, const QVector<int> &roles)
{
// On 64-bit platforms, difference_type for std containers is long long
// but Qt uses int throughout its interfaces; hence casting to int below.
int row = -1;
@@ -195,20 +182,20 @@ int MessageEventModel::refreshEventRoles(const QString& id,
qWarning() << "Trying to refresh inexistent event:" << id;
return -1;
}
row = int(timelineIt - m_currentRoom->messageEvents().rbegin()) +
timelineBaseIndex();
row = int(timelineIt - m_currentRoom->messageEvents().rbegin()) + timelineBaseIndex();
}
refreshEventRoles(row, roles);
return row;
}
inline bool hasValidTimestamp(const Quotient::TimelineItem& ti) {
inline bool hasValidTimestamp(const Quotient::TimelineItem &ti)
{
return ti->originTimestamp().isValid();
}
QDateTime MessageEventModel::makeMessageTimestamp(
const Quotient::Room::rev_iter_t& baseIt) const {
const auto& timeline = m_currentRoom->messageEvents();
QDateTime MessageEventModel::makeMessageTimestamp(const Quotient::Room::rev_iter_t &baseIt) const
{
const auto &timeline = m_currentRoom->messageEvents();
auto ts = baseIt->event()->originTimestamp();
if (ts.isValid())
return ts;
@@ -228,7 +215,8 @@ QDateTime MessageEventModel::makeMessageTimestamp(
return {};
}
QString MessageEventModel::renderDate(QDateTime timestamp) const {
QString MessageEventModel::renderDate(QDateTime timestamp) const
{
auto date = timestamp.toLocalTime().date();
if (date == QDate::currentDate())
return tr("Today");
@@ -242,16 +230,15 @@ QString MessageEventModel::renderDate(QDateTime timestamp) const {
return QLocale::system().toString(date, QLocale::ShortFormat);
}
void MessageEventModel::refreshLastUserEvents(int baseTimelineRow) {
void MessageEventModel::refreshLastUserEvents(int baseTimelineRow)
{
if (!m_currentRoom || m_currentRoom->timelineSize() <= baseTimelineRow)
return;
const auto& timelineBottom = m_currentRoom->messageEvents().rbegin();
const auto& lastSender = (*(timelineBottom + baseTimelineRow))->senderId();
const auto limit = timelineBottom + std::min(baseTimelineRow + 10,
m_currentRoom->timelineSize());
for (auto it = timelineBottom + std::max(baseTimelineRow - 10, 0);
it != limit; ++it) {
const auto &timelineBottom = m_currentRoom->messageEvents().rbegin();
const auto &lastSender = (*(timelineBottom + baseTimelineRow))->senderId();
const auto limit = timelineBottom + std::min(baseTimelineRow + 10, m_currentRoom->timelineSize());
for (auto it = timelineBottom + std::max(baseTimelineRow - 10, 0); it != limit; ++it) {
if ((*it)->senderId() == lastSender) {
auto idx = index(it - timelineBottom);
emit dataChanged(idx, idx);
@@ -259,16 +246,16 @@ void MessageEventModel::refreshLastUserEvents(int baseTimelineRow) {
}
}
int MessageEventModel::rowCount(const QModelIndex& parent) const {
int MessageEventModel::rowCount(const QModelIndex &parent) const
{
if (!m_currentRoom || parent.isValid())
return 0;
return m_currentRoom->timelineSize();
}
inline QVariantMap userAtEvent(SpectralUser* user,
SpectralRoom* room,
const RoomEvent& evt) {
return QVariantMap{
inline QVariantMap userAtEvent(SpectralUser *user, SpectralRoom *room, const RoomEvent &evt)
{
return QVariantMap {
{"isLocalUser", user->id() == room->localUser()->id()},
{"id", user->id()},
{"avatarMediaId", user->avatarMediaId(room)},
@@ -279,20 +266,17 @@ inline QVariantMap userAtEvent(SpectralUser* user,
};
}
QVariant MessageEventModel::data(const QModelIndex& idx, int role) const {
QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
{
const auto row = idx.row();
if (!m_currentRoom || row < 0 ||
row >= int(m_currentRoom->pendingEvents().size()) +
m_currentRoom->timelineSize())
if (!m_currentRoom || row < 0 || row >= int(m_currentRoom->pendingEvents().size()) + m_currentRoom->timelineSize())
return {};
bool isPending = row < timelineBaseIndex();
const auto timelineIt = m_currentRoom->messageEvents().crbegin() +
std::max(0, row - timelineBaseIndex());
const auto pendingIt = m_currentRoom->pendingEvents().crbegin() +
std::min(row, timelineBaseIndex());
const auto& evt = isPending ? **pendingIt : **timelineIt;
const auto timelineIt = m_currentRoom->messageEvents().crbegin() + std::max(0, row - timelineBaseIndex());
const auto pendingIt = m_currentRoom->pendingEvents().crbegin() + std::min(row, timelineBaseIndex());
const auto &evt = isPending ? **pendingIt : **timelineIt;
if (role == Qt::DisplayRole) {
return m_currentRoom->eventToString(evt, Qt::RichText);
@@ -338,17 +322,14 @@ QVariant MessageEventModel::data(const QModelIndex& idx, int role) const {
return EventTypeRegistry::getMatrixType(evt.type());
if (role == AuthorRole) {
auto author = static_cast<SpectralUser*>(
isPending ? m_currentRoom->localUser()
: m_currentRoom->user(evt.senderId()));
auto author = static_cast<SpectralUser *>(isPending ? m_currentRoom->localUser() : m_currentRoom->user(evt.senderId()));
return userAtEvent(author, m_currentRoom, evt);
}
if (role == ContentTypeRole) {
if (auto e = eventCast<const RoomMessageEvent>(&evt)) {
const auto& contentType = e->mimeType().name();
return contentType == "text/plain" ? QStringLiteral("text/html")
: contentType;
const auto &contentType = e->mimeType().name();
return contentType == "text/plain" ? QStringLiteral("text/html") : contentType;
}
return QStringLiteral("text/plain");
}
@@ -356,18 +337,14 @@ QVariant MessageEventModel::data(const QModelIndex& idx, int role) const {
if (role == ContentRole) {
if (evt.isRedacted()) {
auto reason = evt.redactedBecause()->reason();
return (reason.isEmpty())
? tr("[REDACTED]")
: tr("[REDACTED: %1]").arg(evt.redactedBecause()->reason());
return (reason.isEmpty()) ? tr("[REDACTED]") : tr("[REDACTED: %1]").arg(evt.redactedBecause()->reason());
}
if (auto e = eventCast<const RoomMessageEvent>(&evt)) {
// Cannot use e.contentJson() here because some
// EventContent classes inject values into the copy of the
// content JSON stored in EventContent::Base
return e->hasFileContent()
? QVariant::fromValue(e->content()->originalJson)
: QVariant();
return e->hasFileContent() ? QVariant::fromValue(e->content()->originalJson) : QVariant();
};
}
@@ -381,10 +358,9 @@ QVariant MessageEventModel::data(const QModelIndex& idx, int role) const {
if (isPending)
return pendingIt->deliveryStatus();
auto* memberEvent = timelineIt->viewAs<RoomMemberEvent>();
auto *memberEvent = timelineIt->viewAs<RoomMemberEvent>();
if (memberEvent) {
if ((memberEvent->isJoin() || memberEvent->isLeave()) &&
!Settings().value("UI/show_joinleave", true).toBool())
if ((memberEvent->isJoin() || memberEvent->isLeave()) && !Settings().value("UI/show_joinleave", true).toBool())
return EventStatus::Hidden;
}
@@ -393,8 +369,7 @@ QVariant MessageEventModel::data(const QModelIndex& idx, int role) const {
if (evt.isRedacted())
return EventStatus::Hidden;
if (evt.isStateEvent() &&
static_cast<const StateEventBase&>(evt).repeatsState())
if (evt.isStateEvent() && static_cast<const StateEventBase &>(evt).repeatsState())
return EventStatus::Hidden;
if (auto e = eventCast<const RoomMessageEvent>(&evt)) {
@@ -403,8 +378,7 @@ QVariant MessageEventModel::data(const QModelIndex& idx, int role) const {
}
}
if (m_currentRoom->connection()->isIgnored(
m_currentRoom->user(evt.senderId())))
if (m_currentRoom->connection()->isIgnored(m_currentRoom->user(evt.senderId())))
return EventStatus::Hidden;
return EventStatus::Normal;
@@ -424,14 +398,13 @@ QVariant MessageEventModel::data(const QModelIndex& idx, int role) const {
return pendingIt->annotation();
if (role == TimeRole || role == SectionRole) {
auto ts =
isPending ? pendingIt->lastUpdated() : makeMessageTimestamp(timelineIt);
auto ts = isPending ? pendingIt->lastUpdated() : makeMessageTimestamp(timelineIt);
return role == TimeRole ? QVariant(ts) : renderDate(ts);
}
if (role == UserMarkerRole) {
QVariantList variantList;
for (User* user : m_currentRoom->usersAtEventId(evt.id())) {
for (User *user : m_currentRoom->usersAtEventId(evt.id())) {
if (user == m_currentRoom->localUser())
continue;
variantList.append(QVariant::fromValue(user));
@@ -440,34 +413,22 @@ QVariant MessageEventModel::data(const QModelIndex& idx, int role) const {
}
if (role == ReplyRole) {
const QString& replyEventId = evt.contentJson()["m.relates_to"]
.toObject()["m.in_reply_to"]
.toObject()["event_id"]
.toString();
const QString &replyEventId = evt.contentJson()["m.relates_to"].toObject()["m.in_reply_to"].toObject()["event_id"].toString();
if (replyEventId.isEmpty())
return {};
const auto replyIt = m_currentRoom->findInTimeline(replyEventId);
if (replyIt == m_currentRoom->timelineEdge())
return {};
const auto& replyEvt = **replyIt;
const auto &replyEvt = **replyIt;
return QVariantMap{
{"eventId", replyEventId},
{"display", m_currentRoom->eventToString(replyEvt, Qt::RichText)},
{"author", userAtEvent(static_cast<SpectralUser*>(
m_currentRoom->user(replyEvt.senderId())),
m_currentRoom, evt)}};
return QVariantMap {{"eventId", replyEventId}, {"display", m_currentRoom->eventToString(replyEvt, Qt::RichText)}, {"author", userAtEvent(static_cast<SpectralUser *>(m_currentRoom->user(replyEvt.senderId())), m_currentRoom, evt)}};
}
if (role == ShowAuthorRole) {
for (auto r = row + 1; r < rowCount(); ++r) {
auto i = index(r);
if (data(i, SpecialMarksRole) != EventStatus::Hidden) {
return data(i, AuthorRole) != data(idx, AuthorRole) ||
data(i, EventTypeRole) != data(idx, EventTypeRole) ||
data(idx, TimeRole)
.toDateTime()
.msecsTo(data(i, TimeRole).toDateTime()) > 600000;
return data(i, AuthorRole) != data(idx, AuthorRole) || data(i, EventTypeRole) != data(idx, EventTypeRole) || data(idx, TimeRole).toDateTime().msecsTo(data(i, TimeRole).toDateTime()) > 600000;
}
}
@@ -478,9 +439,7 @@ QVariant MessageEventModel::data(const QModelIndex& idx, int role) const {
for (auto r = row + 1; r < rowCount(); ++r) {
auto i = index(r);
if (data(i, SpecialMarksRole) != EventStatus::Hidden) {
return data(i, TimeRole)
.toDateTime()
.msecsTo(data(idx, TimeRole).toDateTime()) > 600000;
return data(i, TimeRole).toDateTime().msecsTo(data(idx, TimeRole).toDateTime()) > 600000;
}
}
@@ -488,17 +447,15 @@ QVariant MessageEventModel::data(const QModelIndex& idx, int role) const {
}
if (role == ReactionRole) {
const auto& annotations =
m_currentRoom->relatedEvents(evt, EventRelation::Annotation());
const auto &annotations = m_currentRoom->relatedEvents(evt, EventRelation::Annotation());
if (annotations.isEmpty())
return {};
QMap<QString, QList<SpectralUser*>> reactions = {};
for (const auto& a : annotations) {
QMap<QString, QList<SpectralUser *>> reactions = {};
for (const auto &a : annotations) {
if (a->isRedacted()) // Just in case?
continue;
if (auto e = eventCast<const ReactionEvent>(a))
reactions[e->relation().key].append(
static_cast<SpectralUser*>(m_currentRoom->user(e->senderId())));
reactions[e->relation().key].append(static_cast<SpectralUser *>(m_currentRoom->user(e->senderId())));
}
if (reactions.isEmpty()) {
@@ -512,12 +469,8 @@ QVariant MessageEventModel::data(const QModelIndex& idx, int role) const {
for (auto author : i.value()) {
authors.append(userAtEvent(author, m_currentRoom, evt));
}
bool hasLocalUser = i.value().contains(
static_cast<SpectralUser*>(m_currentRoom->localUser()));
res.append(QVariantMap{{"reaction", i.key()},
{"count", i.value().count()},
{"authors", authors},
{"hasLocalUser", hasLocalUser}});
bool hasLocalUser = i.value().contains(static_cast<SpectralUser *>(m_currentRoom->localUser()));
res.append(QVariantMap {{"reaction", i.key()}, {"count", i.value().count()}, {"authors", authors}, {"hasLocalUser", hasLocalUser}});
++i;
}
@@ -527,7 +480,8 @@ QVariant MessageEventModel::data(const QModelIndex& idx, int role) const {
return {};
}
int MessageEventModel::eventIDToIndex(const QString& eventID) const {
int MessageEventModel::eventIDToIndex(const QString &eventID) const
{
const auto it = m_currentRoom->findInTimeline(eventID);
if (it == m_currentRoom->timelineEdge()) {
qWarning() << "Trying to find inexistent event:" << eventID;

View File

@@ -6,11 +6,12 @@
#include "room.h"
#include "spectralroom.h"
class MessageEventModel : public QAbstractListModel {
class MessageEventModel : public QAbstractListModel
{
Q_OBJECT
Q_PROPERTY(SpectralRoom* room READ room WRITE setRoom NOTIFY roomChanged)
Q_PROPERTY(SpectralRoom *room READ room WRITE setRoom NOTIFY roomChanged)
public:
public:
enum EventRoles {
EventTypeRole = Qt::UserRole + 1,
MessageRole,
@@ -46,39 +47,40 @@ class MessageEventModel : public QAbstractListModel {
EndShape,
};
explicit MessageEventModel(QObject* parent = nullptr);
explicit MessageEventModel(QObject *parent = nullptr);
~MessageEventModel() override;
SpectralRoom* room() const { return m_currentRoom; }
void setRoom(SpectralRoom* room);
SpectralRoom *room() const
{
return m_currentRoom;
}
void setRoom(SpectralRoom *room);
int rowCount(const QModelIndex& parent = QModelIndex()) const override;
QVariant data(const QModelIndex& index,
int role = Qt::DisplayRole) const override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QHash<int, QByteArray> roleNames() const override;
Q_INVOKABLE int eventIDToIndex(const QString& eventID) const;
Q_INVOKABLE int eventIDToIndex(const QString &eventID) const;
private slots:
int refreshEvent(const QString& eventId);
private slots:
int refreshEvent(const QString &eventId);
void refreshRow(int row);
private:
SpectralRoom* m_currentRoom = nullptr;
private:
SpectralRoom *m_currentRoom = nullptr;
QString lastReadEventId;
int rowBelowInserted = -1;
bool movingEvent = 0;
int timelineBaseIndex() const;
QDateTime makeMessageTimestamp(
const Quotient::Room::rev_iter_t& baseIt) const;
QDateTime makeMessageTimestamp(const Quotient::Room::rev_iter_t &baseIt) const;
QString renderDate(QDateTime timestamp) const;
void refreshLastUserEvents(int baseRow);
void refreshEventRoles(int row, const QVector<int>& roles = {});
int refreshEventRoles(const QString& eventId, const QVector<int>& roles = {});
void refreshEventRoles(int row, const QVector<int> &roles = {});
int refreshEventRoles(const QString &eventId, const QVector<int> &roles = {});
signals:
signals:
void roomChanged();
};

View File

@@ -16,21 +16,20 @@ struct roomEventId {
QString eventId;
};
class NotificationsManager : public QObject {
class NotificationsManager : public QObject
{
Q_OBJECT
public:
NotificationsManager(QObject* parent = nullptr);
public:
NotificationsManager(QObject *parent = nullptr);
signals:
signals:
void notificationClicked(const QString roomId, const QString eventId);
private:
private:
#if defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD)
QDBusInterface dbus;
bool serverSupportsHtml = false;
uint showNotification(const QString summary,
const QString text,
const QImage image);
uint showNotification(const QString summary, const QString text, const QImage image);
#endif
// notification ID to (room ID, event ID)
@@ -38,19 +37,14 @@ class NotificationsManager : public QObject {
// these slots are platform specific (D-Bus only)
// but Qt slot declarations can not be inside an ifdef!
public slots:
public slots:
void actionInvoked(uint id, QString action);
void notificationClosed(uint id, uint reason);
void postNotification(const QString& roomId,
const QString& eventId,
const QString& roomName,
const QString& senderName,
const QString& text,
const QImage& icon);
void postNotification(const QString &roomId, const QString &eventId, const QString &roomName, const QString &senderName, const QString &text, const QImage &icon);
};
#if defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD)
QDBusArgument& operator<<(QDBusArgument& arg, const QImage& image);
const QDBusArgument& operator>>(const QDBusArgument& arg, QImage&);
QDBusArgument &operator<<(QDBusArgument &arg, const QImage &image);
const QDBusArgument &operator>>(const QDBusArgument &arg, QImage &);
#endif

View File

@@ -8,10 +8,9 @@
#include <QtDBus/QDBusReply>
NotificationsManager::NotificationsManager(QObject *parent)
: QObject(parent),
dbus("org.freedesktop.Notifications", "/org/freedesktop/Notifications",
"org.freedesktop.Notifications", QDBusConnection::sessionBus(),
this) {
: QObject(parent)
, dbus("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications", QDBusConnection::sessionBus(), this)
{
qDBusRegisterMetaType<QImage>();
const QDBusReply<QStringList> capabilitiesReply = dbus.call("GetCapabilities");
@@ -23,21 +22,14 @@ NotificationsManager::NotificationsManager(QObject *parent)
qWarning() << "Could not get notification server capabilities" << capabilitiesReply.error();
}
QDBusConnection::sessionBus().connect(
"org.freedesktop.Notifications", "/org/freedesktop/Notifications",
"org.freedesktop.Notifications", "ActionInvoked", this,
SLOT(actionInvoked(uint, QString)));
QDBusConnection::sessionBus().connect(
"org.freedesktop.Notifications", "/org/freedesktop/Notifications",
"org.freedesktop.Notifications", "NotificationClosed", this,
SLOT(notificationClosed(uint, uint)));
QDBusConnection::sessionBus().connect("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications", "ActionInvoked", this, SLOT(actionInvoked(uint, QString)));
QDBusConnection::sessionBus().connect("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications", "NotificationClosed", this, SLOT(notificationClosed(uint, uint)));
}
void NotificationsManager::postNotification(
const QString &roomid, const QString &eventid, const QString &roomname,
const QString &sender, const QString &text, const QImage &icon) {
void NotificationsManager::postNotification(const QString &roomid, const QString &eventid, const QString &roomname, const QString &sender, const QString &text, const QImage &icon)
{
uint id = showNotification(sender + " (" + roomname + ")", text, icon);
notificationIds[id] = roomEventId{roomid, eventid};
notificationIds[id] = roomEventId {roomid, eventid};
}
/**
* This function is based on code from
@@ -45,19 +37,16 @@ void NotificationsManager::postNotification(
* Copyright (C) 2012 Roland Hieber <rohieb@rohieb.name>
* Licensed under the GNU General Public License, version 3
*/
uint NotificationsManager::showNotification(const QString summary,
const QString text,
const QImage image) {
uint NotificationsManager::showNotification(const QString summary, const QString text, const QImage image)
{
QImage croppedImage;
QRect rect = image.rect();
if (rect.width() != rect.height()) {
if (rect.width() > rect.height()) {
QRect crop((rect.width() - rect.height()) / 2, 0, rect.height(),
rect.height());
QRect crop((rect.width() - rect.height()) / 2, 0, rect.height(), rect.height());
croppedImage = image.copy(crop);
} else {
QRect crop(0, (rect.height() - rect.width()) / 2, rect.width(),
rect.width());
QRect crop(0, (rect.height() - rect.width()) / 2, rect.width(), rect.width());
croppedImage = image.copy(crop);
}
} else {
@@ -79,11 +68,8 @@ uint NotificationsManager::showNotification(const QString summary,
argumentList << hints; // hints
argumentList << int(-1); // timeout in ms
static QDBusInterface notifyApp("org.freedesktop.Notifications",
"/org/freedesktop/Notifications",
"org.freedesktop.Notifications");
QDBusMessage reply =
notifyApp.callWithArgumentList(QDBus::AutoDetect, "Notify", argumentList);
static QDBusInterface notifyApp("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications");
QDBusMessage reply = notifyApp.callWithArgumentList(QDBus::AutoDetect, "Notify", argumentList);
if (reply.type() == QDBusMessage::ErrorMessage) {
qDebug() << "D-Bus Error:" << reply.errorMessage();
return 0;
@@ -92,14 +78,16 @@ uint NotificationsManager::showNotification(const QString summary,
}
}
void NotificationsManager::actionInvoked(uint id, QString action) {
void NotificationsManager::actionInvoked(uint id, QString action)
{
if (action == "default" && notificationIds.contains(id)) {
roomEventId idEntry = notificationIds[id];
emit notificationClicked(idEntry.roomId, idEntry.eventId);
}
}
void NotificationsManager::notificationClosed(uint id, uint reason) {
void NotificationsManager::notificationClosed(uint id, uint reason)
{
Q_UNUSED(reason);
notificationIds.remove(id);
}
@@ -113,7 +101,8 @@ void NotificationsManager::notificationClosed(uint id, uint reason) {
*
* Copyright 2010, David Sansome <me@davidsansome.com>
*/
QDBusArgument &operator<<(QDBusArgument &arg, const QImage &image) {
QDBusArgument &operator<<(QDBusArgument &arg, const QImage &image)
{
if (image.isNull()) {
arg.beginStructure();
arg << 0 << 0 << 0 << false << 0 << 0 << QByteArray();
@@ -155,7 +144,8 @@ QDBusArgument &operator<<(QDBusArgument &arg, const QImage &image) {
return arg;
}
const QDBusArgument &operator>>(const QDBusArgument &arg, QImage &) {
const QDBusArgument &operator>>(const QDBusArgument &arg, QImage &)
{
// This is needed to link but shouldn't be called.
Q_ASSERT(0);
return arg;

View File

@@ -5,79 +5,89 @@
using namespace WinToastLib;
class CustomHandler : public IWinToastHandler {
public:
class CustomHandler : public IWinToastHandler
{
public:
CustomHandler(uint id, NotificationsManager *parent)
: notificationID(id), notificationsManager(parent) {}
void toastActivated() {
: notificationID(id)
, notificationsManager(parent)
{
}
void toastActivated()
{
notificationsManager->actionInvoked(notificationID, "");
}
void toastActivated(int) {
void toastActivated(int)
{
notificationsManager->actionInvoked(notificationID, "");
}
void toastFailed() {
void toastFailed()
{
std::wcout << L"Error showing current toast" << std::endl;
}
void toastDismissed(WinToastDismissalReason) {
void toastDismissed(WinToastDismissalReason)
{
notificationsManager->notificationClosed(notificationID, 0);
}
private:
private:
uint notificationID;
NotificationsManager *notificationsManager;
};
namespace {
namespace
{
bool isInitialized = false;
uint count = 0;
void init() {
void init()
{
isInitialized = true;
WinToast::instance()->setAppName(L"Spectral");
WinToast::instance()->setAppUserModelId(
WinToast::configureAUMI(L"Spectral", L"Spectral"));
WinToast::instance()->setAppUserModelId(WinToast::configureAUMI(L"Spectral", L"Spectral"));
if (!WinToast::instance()->initialize())
std::wcout << "Your system in not compatible with toast notifications\n";
}
} // namespace
NotificationsManager::NotificationsManager(QObject *parent) : QObject(parent) {}
NotificationsManager::NotificationsManager(QObject *parent)
: QObject(parent)
{
}
void NotificationsManager::postNotification(
const QString &room_id, const QString &event_id, const QString &room_name,
const QString &sender, const QString &text, const QImage &icon) {
void NotificationsManager::postNotification(const QString &room_id, const QString &event_id, const QString &room_name, const QString &sender, const QString &text, const QImage &icon)
{
Q_UNUSED(room_id)
Q_UNUSED(event_id)
Q_UNUSED(icon)
if (!isInitialized) init();
if (!isInitialized)
init();
auto templ = WinToastTemplate(WinToastTemplate::ImageAndText02);
if (room_name != sender)
templ.setTextField(
QString("%1 - %2").arg(sender).arg(room_name).toStdWString(),
WinToastTemplate::FirstLine);
templ.setTextField(QString("%1 - %2").arg(sender).arg(room_name).toStdWString(), WinToastTemplate::FirstLine);
else
templ.setTextField(QString("%1").arg(sender).toStdWString(),
WinToastTemplate::FirstLine);
templ.setTextField(QString("%1").arg(text).toStdWString(),
WinToastTemplate::SecondLine);
templ.setTextField(QString("%1").arg(sender).toStdWString(), WinToastTemplate::FirstLine);
templ.setTextField(QString("%1").arg(text).toStdWString(), WinToastTemplate::SecondLine);
count++;
CustomHandler *customHandler = new CustomHandler(count, this);
notificationIds[count] = roomEventId{room_id, event_id};
notificationIds[count] = roomEventId {room_id, event_id};
WinToast::instance()->showToast(templ, customHandler);
}
void NotificationsManager::actionInvoked(uint id, QString action) {
void NotificationsManager::actionInvoked(uint id, QString action)
{
if (notificationIds.contains(id)) {
roomEventId idEntry = notificationIds[id];
emit notificationClicked(idEntry.roomId, idEntry.eventId);
}
}
void NotificationsManager::notificationClosed(uint id, uint reason) {
void NotificationsManager::notificationClosed(uint id, uint reason)
{
notificationIds.remove(id);
}

View File

@@ -1,14 +1,19 @@
#include "wintoastlib.h"
#include <memory>
#include <assert.h>
#include <memory>
#pragma comment(lib,"shlwapi")
#pragma comment(lib,"user32")
#pragma comment(lib, "shlwapi")
#pragma comment(lib, "user32")
#ifdef NDEBUG
#define DEBUG_MSG(str) do { } while ( false )
#else
#define DEBUG_MSG(str) do { std::wcout << str << std::endl; } while( false )
#define DEBUG_MSG(str) \
do { \
} while (false)
#else
#define DEBUG_MSG(str) \
do { \
std::wcout << str << std::endl; \
} while (false)
#endif
// Thanks: https://stackoverflow.com/a/36545162/4297146
@@ -17,21 +22,22 @@ typedef LONG NTSTATUS, *PNTSTATUS;
#define STATUS_SUCCESS (0x00000000)
typedef NTSTATUS(WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);
typedef NTSTATUS(WINAPI *RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);
RTL_OSVERSIONINFOW GetRealOSVersion() {
RTL_OSVERSIONINFOW GetRealOSVersion()
{
HMODULE hMod = ::GetModuleHandleW(L"ntdll.dll");
if (hMod) {
RtlGetVersionPtr fxPtr = (RtlGetVersionPtr)::GetProcAddress(hMod, "RtlGetVersion");
if (fxPtr != nullptr) {
RTL_OSVERSIONINFOW rovi = { 0 };
RTL_OSVERSIONINFOW rovi = {0};
rovi.dwOSVersionInfoSize = sizeof(rovi);
if (STATUS_SUCCESS == fxPtr(&rovi)) {
return rovi;
}
}
}
RTL_OSVERSIONINFOW rovi = { 0 };
RTL_OSVERSIONINFOW rovi = {0};
return rovi;
}
@@ -39,44 +45,44 @@ RTL_OSVERSIONINFOW GetRealOSVersion() {
// https://blogs.msdn.microsoft.com/tiles_and_toasts/2015/10/16/quickstart-handling-toast-activations-from-win32-apps-in-windows-10/
using namespace WinToastLib;
namespace DllImporter {
// Function load a function from library
template <typename Function>
HRESULT loadFunctionFromLibrary(HINSTANCE library, LPCSTR name, Function &func) {
namespace DllImporter
{
// Function load a function from library
template<typename Function> HRESULT loadFunctionFromLibrary(HINSTANCE library, LPCSTR name, Function &func)
{
if (!library) {
return E_INVALIDARG;
}
func = reinterpret_cast<Function>(GetProcAddress(library, name));
return (func != nullptr) ? S_OK : E_FAIL;
}
}
typedef HRESULT(FAR STDAPICALLTYPE *f_SetCurrentProcessExplicitAppUserModelID)(__in PCWSTR AppID);
typedef HRESULT(FAR STDAPICALLTYPE *f_PropVariantToString)(_In_ REFPROPVARIANT propvar, _Out_writes_(cch) PWSTR psz, _In_ UINT cch);
typedef HRESULT(FAR STDAPICALLTYPE *f_RoGetActivationFactory)(_In_ HSTRING activatableClassId, _In_ REFIID iid, _COM_Outptr_ void ** factory);
typedef HRESULT(FAR STDAPICALLTYPE *f_WindowsCreateStringReference)(_In_reads_opt_(length + 1) PCWSTR sourceString, UINT32 length, _Out_ HSTRING_HEADER * hstringHeader, _Outptr_result_maybenull_ _Result_nullonfailure_ HSTRING * string);
typedef PCWSTR(FAR STDAPICALLTYPE *f_WindowsGetStringRawBuffer)(_In_ HSTRING string, _Out_ UINT32 *length);
typedef HRESULT(FAR STDAPICALLTYPE *f_WindowsDeleteString)(_In_opt_ HSTRING string);
typedef HRESULT(FAR STDAPICALLTYPE *f_SetCurrentProcessExplicitAppUserModelID)(__in PCWSTR AppID);
typedef HRESULT(FAR STDAPICALLTYPE *f_PropVariantToString)(_In_ REFPROPVARIANT propvar, _Out_writes_(cch) PWSTR psz, _In_ UINT cch);
typedef HRESULT(FAR STDAPICALLTYPE *f_RoGetActivationFactory)(_In_ HSTRING activatableClassId, _In_ REFIID iid, _COM_Outptr_ void **factory);
typedef HRESULT(FAR STDAPICALLTYPE *f_WindowsCreateStringReference)(_In_reads_opt_(length + 1) PCWSTR sourceString, UINT32 length, _Out_ HSTRING_HEADER *hstringHeader, _Outptr_result_maybenull_ _Result_nullonfailure_ HSTRING *string);
typedef PCWSTR(FAR STDAPICALLTYPE *f_WindowsGetStringRawBuffer)(_In_ HSTRING string, _Out_ UINT32 *length);
typedef HRESULT(FAR STDAPICALLTYPE *f_WindowsDeleteString)(_In_opt_ HSTRING string);
static f_SetCurrentProcessExplicitAppUserModelID SetCurrentProcessExplicitAppUserModelID;
static f_PropVariantToString PropVariantToString;
static f_RoGetActivationFactory RoGetActivationFactory;
static f_WindowsCreateStringReference WindowsCreateStringReference;
static f_WindowsGetStringRawBuffer WindowsGetStringRawBuffer;
static f_WindowsDeleteString WindowsDeleteString;
static f_SetCurrentProcessExplicitAppUserModelID SetCurrentProcessExplicitAppUserModelID;
static f_PropVariantToString PropVariantToString;
static f_RoGetActivationFactory RoGetActivationFactory;
static f_WindowsCreateStringReference WindowsCreateStringReference;
static f_WindowsGetStringRawBuffer WindowsGetStringRawBuffer;
static f_WindowsDeleteString WindowsDeleteString;
template<class T>
_Check_return_ __inline HRESULT _1_GetActivationFactory(_In_ HSTRING activatableClassId, _COM_Outptr_ T** factory) {
template<class T> _Check_return_ __inline HRESULT _1_GetActivationFactory(_In_ HSTRING activatableClassId, _COM_Outptr_ T **factory)
{
return RoGetActivationFactory(activatableClassId, IID_INS_ARGS(factory));
}
}
template<typename T>
inline HRESULT Wrap_GetActivationFactory(_In_ HSTRING activatableClassId, _Inout_ Details::ComPtrRef<T> factory) throw() {
template<typename T> inline HRESULT Wrap_GetActivationFactory(_In_ HSTRING activatableClassId, _Inout_ Details::ComPtrRef<T> factory) throw()
{
return _1_GetActivationFactory(activatableClassId, factory.ReleaseAndGetAddressOf());
}
}
inline HRESULT initialize() {
inline HRESULT initialize()
{
HINSTANCE LibShell32 = LoadLibraryW(L"SHELL32.DLL");
HRESULT hr = loadFunctionFromLibrary(LibShell32, "SetCurrentProcessExplicitAppUserModelID", SetCurrentProcessExplicitAppUserModelID);
if (SUCCEEDED(hr)) {
@@ -84,39 +90,45 @@ namespace DllImporter {
hr = loadFunctionFromLibrary(LibPropSys, "PropVariantToString", PropVariantToString);
if (SUCCEEDED(hr)) {
HINSTANCE LibComBase = LoadLibraryW(L"COMBASE.DLL");
const bool succeded = SUCCEEDED(loadFunctionFromLibrary(LibComBase, "RoGetActivationFactory", RoGetActivationFactory))
&& SUCCEEDED(loadFunctionFromLibrary(LibComBase, "WindowsCreateStringReference", WindowsCreateStringReference))
&& SUCCEEDED(loadFunctionFromLibrary(LibComBase, "WindowsGetStringRawBuffer", WindowsGetStringRawBuffer))
&& SUCCEEDED(loadFunctionFromLibrary(LibComBase, "WindowsDeleteString", WindowsDeleteString));
const bool succeded = SUCCEEDED(loadFunctionFromLibrary(LibComBase, "RoGetActivationFactory", RoGetActivationFactory)) &&
SUCCEEDED(loadFunctionFromLibrary(LibComBase, "WindowsCreateStringReference", WindowsCreateStringReference)) && SUCCEEDED(loadFunctionFromLibrary(LibComBase, "WindowsGetStringRawBuffer", WindowsGetStringRawBuffer)) &&
SUCCEEDED(loadFunctionFromLibrary(LibComBase, "WindowsDeleteString", WindowsDeleteString));
return succeded ? S_OK : E_FAIL;
}
}
return hr;
}
}
}
class WinToastStringWrapper {
class WinToastStringWrapper
{
public:
WinToastStringWrapper(_In_reads_(length) PCWSTR stringRef, _In_ UINT32 length) throw() {
WinToastStringWrapper(_In_reads_(length) PCWSTR stringRef, _In_ UINT32 length) throw()
{
HRESULT hr = DllImporter::WindowsCreateStringReference(stringRef, length, &_header, &_hstring);
if (!SUCCEEDED(hr)) {
RaiseException(static_cast<DWORD>(STATUS_INVALID_PARAMETER), EXCEPTION_NONCONTINUABLE, 0, nullptr);
}
}
WinToastStringWrapper(_In_ const std::wstring &stringRef) throw() {
WinToastStringWrapper(_In_ const std::wstring &stringRef) throw()
{
HRESULT hr = DllImporter::WindowsCreateStringReference(stringRef.c_str(), static_cast<UINT32>(stringRef.length()), &_header, &_hstring);
if (FAILED(hr)) {
RaiseException(static_cast<DWORD>(STATUS_INVALID_PARAMETER), EXCEPTION_NONCONTINUABLE, 0, nullptr);
}
}
~WinToastStringWrapper() {
~WinToastStringWrapper()
{
DllImporter::WindowsDeleteString(_hstring);
}
inline HSTRING Get() const throw() { return _hstring; }
inline HSTRING Get() const throw()
{
return _hstring;
}
private:
HSTRING _hstring;
HSTRING_HEADER _header;
};
class MyDateTime : public IReference<DateTime>
@@ -125,68 +137,83 @@ protected:
DateTime _dateTime;
public:
static INT64 Now() {
static INT64 Now()
{
FILETIME now;
GetSystemTimeAsFileTime(&now);
return ((((INT64)now.dwHighDateTime) << 32) | now.dwLowDateTime);
}
MyDateTime(DateTime dateTime) : _dateTime(dateTime) {}
MyDateTime(DateTime dateTime)
: _dateTime(dateTime)
{
}
MyDateTime(INT64 millisecondsFromNow) {
MyDateTime(INT64 millisecondsFromNow)
{
_dateTime.UniversalTime = Now() + millisecondsFromNow * 10000;
}
operator INT64() {
operator INT64()
{
return _dateTime.UniversalTime;
}
HRESULT STDMETHODCALLTYPE get_Value(DateTime *dateTime) {
HRESULT STDMETHODCALLTYPE get_Value(DateTime *dateTime)
{
*dateTime = _dateTime;
return S_OK;
}
HRESULT STDMETHODCALLTYPE QueryInterface(const IID& riid, void** ppvObject) {
HRESULT STDMETHODCALLTYPE QueryInterface(const IID &riid, void **ppvObject)
{
if (!ppvObject) {
return E_POINTER;
}
if (riid == __uuidof(IUnknown) || riid == __uuidof(IReference<DateTime>)) {
*ppvObject = static_cast<IUnknown*>(static_cast<IReference<DateTime>*>(this));
*ppvObject = static_cast<IUnknown *>(static_cast<IReference<DateTime> *>(this));
return S_OK;
}
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE Release() {
ULONG STDMETHODCALLTYPE Release()
{
return 1;
}
ULONG STDMETHODCALLTYPE AddRef() {
ULONG STDMETHODCALLTYPE AddRef()
{
return 2;
}
HRESULT STDMETHODCALLTYPE GetIids(ULONG*, IID**) {
HRESULT STDMETHODCALLTYPE GetIids(ULONG *, IID **)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE GetRuntimeClassName(HSTRING*) {
HRESULT STDMETHODCALLTYPE GetRuntimeClassName(HSTRING *)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE GetTrustLevel(TrustLevel*) {
HRESULT STDMETHODCALLTYPE GetTrustLevel(TrustLevel *)
{
return E_NOTIMPL;
}
};
namespace Util {
inline HRESULT defaultExecutablePath(_In_ WCHAR* path, _In_ DWORD nSize = MAX_PATH) {
namespace Util
{
inline HRESULT defaultExecutablePath(_In_ WCHAR *path, _In_ DWORD nSize = MAX_PATH)
{
DWORD written = GetModuleFileNameExW(GetCurrentProcess(), nullptr, path, nSize);
DEBUG_MSG("Default executable path: " << path);
return (written > 0) ? S_OK : E_FAIL;
}
}
inline HRESULT defaultShellLinksDirectory(_In_ WCHAR* path, _In_ DWORD nSize = MAX_PATH) {
inline HRESULT defaultShellLinksDirectory(_In_ WCHAR *path, _In_ DWORD nSize = MAX_PATH)
{
DWORD written = GetEnvironmentVariableW(L"APPDATA", path, nSize);
HRESULT hr = written > 0 ? S_OK : E_INVALIDARG;
if (SUCCEEDED(hr)) {
@@ -195,9 +222,10 @@ namespace Util {
DEBUG_MSG("Default shell link path: " << path);
}
return hr;
}
}
inline HRESULT defaultShellLinkPath(const std::wstring& appname, _In_ WCHAR* path, _In_ DWORD nSize = MAX_PATH) {
inline HRESULT defaultShellLinkPath(const std::wstring &appname, _In_ WCHAR *path, _In_ DWORD nSize = MAX_PATH)
{
HRESULT hr = defaultShellLinksDirectory(path, nSize);
if (SUCCEEDED(hr)) {
const std::wstring appLink(appname + DEFAULT_LINK_FORMAT);
@@ -206,10 +234,10 @@ namespace Util {
DEBUG_MSG("Default shell link file path: " << path);
}
return hr;
}
}
inline PCWSTR AsString(ComPtr<IXmlDocument> &xmlDocument) {
inline PCWSTR AsString(ComPtr<IXmlDocument> &xmlDocument)
{
HSTRING xml;
ComPtr<IXmlNodeSerializer> ser;
HRESULT hr = xmlDocument.As<IXmlNodeSerializer>(&ser);
@@ -217,15 +245,17 @@ namespace Util {
if (SUCCEEDED(hr))
return DllImporter::WindowsGetStringRawBuffer(xml, NULL);
return NULL;
}
}
inline PCWSTR AsString(HSTRING hstring) {
inline PCWSTR AsString(HSTRING hstring)
{
return DllImporter::WindowsGetStringRawBuffer(hstring, NULL);
}
}
inline HRESULT setNodeStringValue(const std::wstring& string, IXmlNode *node, IXmlDocument *xml) {
inline HRESULT setNodeStringValue(const std::wstring &string, IXmlNode *node, IXmlDocument *xml)
{
ComPtr<IXmlText> textNode;
HRESULT hr = xml->CreateTextNode( WinToastStringWrapper(string).Get(), &textNode);
HRESULT hr = xml->CreateTextNode(WinToastStringWrapper(string).Get(), &textNode);
if (SUCCEEDED(hr)) {
ComPtr<IXmlNode> stringNode;
hr = textNode.As(&stringNode);
@@ -235,15 +265,12 @@ namespace Util {
}
}
return hr;
}
}
inline HRESULT setEventHandlers(_In_ IToastNotification* notification, _In_ std::shared_ptr<IWinToastHandler> eventHandler, _In_ INT64 expirationTime) {
inline HRESULT setEventHandlers(_In_ IToastNotification *notification, _In_ std::shared_ptr<IWinToastHandler> eventHandler, _In_ INT64 expirationTime)
{
EventRegistrationToken activatedToken, dismissedToken, failedToken;
HRESULT hr = notification->add_Activated(
Callback < Implements < RuntimeClassFlags<ClassicCom>,
ITypedEventHandler<ToastNotification*, IInspectable* >> >(
[eventHandler](IToastNotification*, IInspectable* inspectable)
{
HRESULT hr = notification->add_Activated(Callback<Implements<RuntimeClassFlags<ClassicCom>, ITypedEventHandler<ToastNotification *, IInspectable *>>>([eventHandler](IToastNotification *, IInspectable *inspectable) {
IToastActivatedEventArgs *activatedEventArgs;
HRESULT hr = inspectable->QueryInterface(&activatedEventArgs);
if (SUCCEEDED(hr)) {
@@ -259,36 +286,34 @@ namespace Util {
}
eventHandler->toastActivated();
return S_OK;
}).Get(), &activatedToken);
}).Get(),
&activatedToken);
if (SUCCEEDED(hr)) {
hr = notification->add_Dismissed(Callback < Implements < RuntimeClassFlags<ClassicCom>,
ITypedEventHandler<ToastNotification*, ToastDismissedEventArgs* >> >(
[eventHandler, expirationTime](IToastNotification*, IToastDismissedEventArgs* e)
{
hr = notification->add_Dismissed(
Callback<Implements<RuntimeClassFlags<ClassicCom>, ITypedEventHandler<ToastNotification *, ToastDismissedEventArgs *>>>([eventHandler, expirationTime](IToastNotification *, IToastDismissedEventArgs *e) {
ToastDismissalReason reason;
if (SUCCEEDED(e->get_Reason(&reason)))
{
if (SUCCEEDED(e->get_Reason(&reason))) {
if (reason == ToastDismissalReason_UserCanceled && expirationTime && MyDateTime::Now() >= expirationTime)
reason = ToastDismissalReason_TimedOut;
eventHandler->toastDismissed(static_cast<IWinToastHandler::WinToastDismissalReason>(reason));
}
return S_OK;
}).Get(), &dismissedToken);
}).Get(),
&dismissedToken);
if (SUCCEEDED(hr)) {
hr = notification->add_Failed(Callback < Implements < RuntimeClassFlags<ClassicCom>,
ITypedEventHandler<ToastNotification*, ToastFailedEventArgs* >> >(
[eventHandler](IToastNotification*, IToastFailedEventArgs*)
{
hr = notification->add_Failed(Callback<Implements<RuntimeClassFlags<ClassicCom>, ITypedEventHandler<ToastNotification *, ToastFailedEventArgs *>>>([eventHandler](IToastNotification *, IToastFailedEventArgs *) {
eventHandler->toastFailed();
return S_OK;
}).Get(), &failedToken);
}).Get(),
&failedToken);
}
}
return hr;
}
}
inline HRESULT addAttribute(_In_ IXmlDocument *xml, const std::wstring &name, IXmlNamedNodeMap *attributeMap) {
inline HRESULT addAttribute(_In_ IXmlDocument *xml, const std::wstring &name, IXmlNamedNodeMap *attributeMap)
{
ComPtr<ABI::Windows::Data::Xml::Dom::IXmlAttribute> srcAttribute;
HRESULT hr = xml->CreateAttribute(WinToastStringWrapper(name).Get(), &srcAttribute);
if (SUCCEEDED(hr)) {
@@ -300,9 +325,10 @@ namespace Util {
}
}
return hr;
}
}
inline HRESULT createElement(_In_ IXmlDocument *xml, _In_ const std::wstring& root_node, _In_ const std::wstring& element_name, _In_ const std::vector<std::wstring>& attribute_names) {
inline HRESULT createElement(_In_ IXmlDocument *xml, _In_ const std::wstring &root_node, _In_ const std::wstring &element_name, _In_ const std::vector<std::wstring> &attribute_names)
{
ComPtr<IXmlNodeList> rootList;
HRESULT hr = xml->GetElementsByTagName(WinToastStringWrapper(root_node).Get(), &rootList);
if (SUCCEEDED(hr)) {
@@ -331,57 +357,55 @@ namespace Util {
}
}
return hr;
}
}
}
WinToast* WinToast::instance() {
WinToast *WinToast::instance()
{
static WinToast instance;
return &instance;
}
WinToast::WinToast() :
_isInitialized(false),
_hasCoInitialized(false)
WinToast::WinToast()
: _isInitialized(false)
, _hasCoInitialized(false)
{
if (!isCompatible()) {
DEBUG_MSG(L"Warning: Your system is not compatible with this library ");
}
}
WinToast::~WinToast() {
WinToast::~WinToast()
{
if (_hasCoInitialized) {
CoUninitialize();
}
}
void WinToast::setAppName(_In_ const std::wstring& appName) {
void WinToast::setAppName(_In_ const std::wstring &appName)
{
_appName = appName;
}
void WinToast::setAppUserModelId(_In_ const std::wstring& aumi) {
void WinToast::setAppUserModelId(_In_ const std::wstring &aumi)
{
_aumi = aumi;
DEBUG_MSG(L"Default App User Model Id: " << _aumi.c_str());
}
bool WinToast::isCompatible() {
bool WinToast::isCompatible()
{
DllImporter::initialize();
return !((DllImporter::SetCurrentProcessExplicitAppUserModelID == nullptr)
|| (DllImporter::PropVariantToString == nullptr)
|| (DllImporter::RoGetActivationFactory == nullptr)
|| (DllImporter::WindowsCreateStringReference == nullptr)
|| (DllImporter::WindowsDeleteString == nullptr));
return !((DllImporter::SetCurrentProcessExplicitAppUserModelID == nullptr) || (DllImporter::PropVariantToString == nullptr) || (DllImporter::RoGetActivationFactory == nullptr) || (DllImporter::WindowsCreateStringReference == nullptr) ||
(DllImporter::WindowsDeleteString == nullptr));
}
bool WinToastLib::WinToast::isSupportingModernFeatures() {
bool WinToastLib::WinToast::isSupportingModernFeatures()
{
RTL_OSVERSIONINFOW tmp = GetRealOSVersion();
return tmp.dwMajorVersion > 6;
}
std::wstring WinToast::configureAUMI(_In_ const std::wstring &companyName,
_In_ const std::wstring &productName,
_In_ const std::wstring &subProduct,
_In_ const std::wstring &versionInformation)
std::wstring WinToast::configureAUMI(_In_ const std::wstring &companyName, _In_ const std::wstring &productName, _In_ const std::wstring &subProduct, _In_ const std::wstring &versionInformation)
{
std::wstring aumi = companyName;
aumi += L"." + productName;
@@ -398,8 +422,8 @@ std::wstring WinToast::configureAUMI(_In_ const std::wstring &companyName,
return aumi;
}
enum WinToast::ShortcutResult WinToast::createShortcut() {
enum WinToast::ShortcutResult WinToast::createShortcut()
{
if (_aumi.empty() || _appName.empty()) {
DEBUG_MSG(L"Error: App User Model Id or Appname is empty!");
return SHORTCUT_MISSING_PARAMETERS;
@@ -416,8 +440,7 @@ enum WinToast::ShortcutResult WinToast::createShortcut() {
if (FAILED(initHr) && initHr != S_FALSE) {
DEBUG_MSG(L"Error on COM library initialization!");
return SHORTCUT_COM_INIT_FAILURE;
}
else {
} else {
_hasCoInitialized = true;
}
}
@@ -432,7 +455,8 @@ enum WinToast::ShortcutResult WinToast::createShortcut() {
return SUCCEEDED(hr) ? SHORTCUT_WAS_CREATED : SHORTCUT_CREATE_FAILED;
}
bool WinToast::initialize(_Out_ WinToastError* error) {
bool WinToast::initialize(_Out_ WinToastError *error)
{
_isInitialized = false;
setError(error, WinToastError::NoError);
@@ -442,7 +466,6 @@ bool WinToast::initialize(_Out_ WinToastError* error) {
return false;
}
if (_aumi.empty() || _appName.empty()) {
setError(error, WinToastError::InvalidParameters);
DEBUG_MSG(L"Error while initializing, did you set up a valid AUMI and App name?");
@@ -465,21 +488,24 @@ bool WinToast::initialize(_Out_ WinToastError* error) {
return _isInitialized;
}
bool WinToast::isInitialized() const {
bool WinToast::isInitialized() const
{
return _isInitialized;
}
const std::wstring& WinToast::appName() const {
const std::wstring &WinToast::appName() const
{
return _appName;
}
const std::wstring& WinToast::appUserModelId() const {
const std::wstring &WinToast::appUserModelId() const
{
return _aumi;
}
HRESULT WinToast::validateShellLinkHelper(_Out_ bool& wasChanged) {
WCHAR path[MAX_PATH] = { L'\0' };
HRESULT WinToast::validateShellLinkHelper(_Out_ bool &wasChanged)
{
WCHAR path[MAX_PATH] = {L'\0'};
Util::defaultShellLinkPath(_appName, path);
// Check if the file exist
DWORD attr = GetFileAttributesW(path);
@@ -535,11 +561,10 @@ HRESULT WinToast::validateShellLinkHelper(_Out_ bool& wasChanged) {
return hr;
}
HRESULT WinToast::createShellLinkHelper() {
WCHAR exePath[MAX_PATH]{L'\0'};
WCHAR slPath[MAX_PATH]{L'\0'};
HRESULT WinToast::createShellLinkHelper()
{
WCHAR exePath[MAX_PATH] {L'\0'};
WCHAR slPath[MAX_PATH] {L'\0'};
Util::defaultShellLinkPath(_appName, slPath);
Util::defaultExecutablePath(exePath);
ComPtr<IShellLinkW> shellLink;
@@ -578,7 +603,8 @@ HRESULT WinToast::createShellLinkHelper() {
return hr;
}
INT64 WinToast::showToast(_In_ const WinToastTemplate& toast, _In_ IWinToastHandler* handler, _Out_ WinToastError* error) {
INT64 WinToast::showToast(_In_ const WinToastTemplate &toast, _In_ IWinToastHandler *handler, _Out_ WinToastError *error)
{
setError(error, WinToastError::NoError);
INT64 id = -1;
if (!isInitialized()) {
@@ -611,11 +637,9 @@ INT64 WinToast::showToast(_In_ const WinToastTemplate& toast, _In_ IWinToastHan
// Modern feature are supported Windows > Windows 10
if (SUCCEEDED(hr) && isSupportingModernFeatures()) {
// Note that we do this *after* using toast.textFieldsCount() to
// iterate/fill the template's text fields, since we're adding yet another text field.
if (SUCCEEDED(hr)
&& !toast.attributionText().empty()) {
if (SUCCEEDED(hr) && !toast.attributionText().empty()) {
hr = setAttributionTextFieldHelper(xmlDocument.Get(), toast.attributionText());
}
@@ -627,13 +651,11 @@ INT64 WinToast::showToast(_In_ const WinToastTemplate& toast, _In_ IWinToastHan
}
if (SUCCEEDED(hr)) {
hr = (toast.audioPath().empty() && toast.audioOption() == WinToastTemplate::AudioOption::Default)
? hr : setAudioFieldHelper(xmlDocument.Get(), toast.audioPath(), toast.audioOption());
hr = (toast.audioPath().empty() && toast.audioOption() == WinToastTemplate::AudioOption::Default) ? hr : setAudioFieldHelper(xmlDocument.Get(), toast.audioPath(), toast.audioOption());
}
if (SUCCEEDED(hr) && toast.duration() != WinToastTemplate::Duration::System) {
hr = addDurationHelper(xmlDocument.Get(),
(toast.duration() == WinToastTemplate::Duration::Short) ? L"short" : L"long");
hr = addDurationHelper(xmlDocument.Get(), (toast.duration() == WinToastTemplate::Duration::Short) ? L"short" : L"long");
}
} else {
@@ -683,7 +705,8 @@ INT64 WinToast::showToast(_In_ const WinToastTemplate& toast, _In_ IWinToastHan
return FAILED(hr) ? -1 : id;
}
ComPtr<IToastNotifier> WinToast::notifier(_In_ bool* succeded) const {
ComPtr<IToastNotifier> WinToast::notifier(_In_ bool *succeded) const
{
ComPtr<IToastNotificationManagerStatics> notificationManager;
ComPtr<IToastNotifier> notifier;
HRESULT hr = DllImporter::Wrap_GetActivationFactory(WinToastStringWrapper(RuntimeClass_Windows_UI_Notifications_ToastNotificationManager).Get(), &notificationManager);
@@ -694,7 +717,8 @@ ComPtr<IToastNotifier> WinToast::notifier(_In_ bool* succeded) const {
return notifier;
}
bool WinToast::hideToast(_In_ INT64 id) {
bool WinToast::hideToast(_In_ INT64 id)
{
if (!isInitialized()) {
DEBUG_MSG("Error when hiding the toast. WinToast is not initialized.");
return false;
@@ -711,7 +735,8 @@ bool WinToast::hideToast(_In_ INT64 id) {
return find;
}
void WinToast::clear() {
void WinToast::clear()
{
bool succeded = false;
ComPtr<IToastNotifier> notify = notifier(&succeded);
if (succeded) {
@@ -730,8 +755,9 @@ void WinToast::clear() {
// NOTE: This will add a new text field, so be aware when iterating over
// the toast's text fields or getting a count of them.
//
HRESULT WinToast::setAttributionTextFieldHelper(_In_ IXmlDocument *xml, _In_ const std::wstring& text) {
Util::createElement(xml, L"binding", L"text", { L"placement" });
HRESULT WinToast::setAttributionTextFieldHelper(_In_ IXmlDocument *xml, _In_ const std::wstring &text)
{
Util::createElement(xml, L"binding", L"text", {L"placement"});
ComPtr<IXmlNodeList> nodeList;
HRESULT hr = xml->GetElementsByTagName(WinToastStringWrapper(L"text").Get(), &nodeList);
if (SUCCEEDED(hr)) {
@@ -764,7 +790,8 @@ HRESULT WinToast::setAttributionTextFieldHelper(_In_ IXmlDocument *xml, _In_ con
return hr;
}
HRESULT WinToast::addDurationHelper(_In_ IXmlDocument *xml, _In_ const std::wstring& duration) {
HRESULT WinToast::addDurationHelper(_In_ IXmlDocument *xml, _In_ const std::wstring &duration)
{
ComPtr<IXmlNodeList> nodeList;
HRESULT hr = xml->GetElementsByTagName(WinToastStringWrapper(L"toast").Get(), &nodeList);
if (SUCCEEDED(hr)) {
@@ -777,8 +804,7 @@ HRESULT WinToast::addDurationHelper(_In_ IXmlDocument *xml, _In_ const std::wstr
ComPtr<IXmlElement> toastElement;
hr = toastNode.As(&toastElement);
if (SUCCEEDED(hr)) {
hr = toastElement->SetAttribute(WinToastStringWrapper(L"duration").Get(),
WinToastStringWrapper(duration).Get());
hr = toastElement->SetAttribute(WinToastStringWrapper(L"duration").Get(), WinToastStringWrapper(duration).Get());
}
}
}
@@ -786,7 +812,8 @@ HRESULT WinToast::addDurationHelper(_In_ IXmlDocument *xml, _In_ const std::wstr
return hr;
}
HRESULT WinToast::setTextFieldHelper(_In_ IXmlDocument *xml, _In_ const std::wstring& text, _In_ int pos) {
HRESULT WinToast::setTextFieldHelper(_In_ IXmlDocument *xml, _In_ const std::wstring &text, _In_ int pos)
{
ComPtr<IXmlNodeList> nodeList;
HRESULT hr = xml->GetElementsByTagName(WinToastStringWrapper(L"text").Get(), &nodeList);
if (SUCCEEDED(hr)) {
@@ -799,8 +826,8 @@ HRESULT WinToast::setTextFieldHelper(_In_ IXmlDocument *xml, _In_ const std::wst
return hr;
}
HRESULT WinToast::setImageFieldHelper(_In_ IXmlDocument *xml, _In_ const std::wstring& path) {
HRESULT WinToast::setImageFieldHelper(_In_ IXmlDocument *xml, _In_ const std::wstring &path)
{
wchar_t imagePath[MAX_PATH] = L"file:///";
HRESULT hr = StringCchCatW(imagePath, MAX_PATH, path.c_str());
if (SUCCEEDED(hr)) {
@@ -825,11 +852,15 @@ HRESULT WinToast::setImageFieldHelper(_In_ IXmlDocument *xml, _In_ const std::ws
return hr;
}
HRESULT WinToast::setAudioFieldHelper(_In_ IXmlDocument *xml, _In_ const std::wstring& path, _In_opt_ WinToastTemplate::AudioOption option) {
HRESULT WinToast::setAudioFieldHelper(_In_ IXmlDocument *xml, _In_ const std::wstring &path, _In_opt_ WinToastTemplate::AudioOption option)
{
std::vector<std::wstring> attrs;
if (!path.empty()) attrs.push_back(L"src");
if (option == WinToastTemplate::AudioOption::Loop) attrs.push_back(L"loop");
if (option == WinToastTemplate::AudioOption::Silent) attrs.push_back(L"silent");
if (!path.empty())
attrs.push_back(L"src");
if (option == WinToastTemplate::AudioOption::Loop)
attrs.push_back(L"loop");
if (option == WinToastTemplate::AudioOption::Silent)
attrs.push_back(L"silent");
Util::createElement(xml, L"toast", L"audio", attrs);
ComPtr<IXmlNodeList> nodeList;
@@ -874,7 +905,8 @@ HRESULT WinToast::setAudioFieldHelper(_In_ IXmlDocument *xml, _In_ const std::ws
return hr;
}
HRESULT WinToast::addActionHelper(_In_ IXmlDocument *xml, _In_ const std::wstring& content, _In_ const std::wstring& arguments) {
HRESULT WinToast::addActionHelper(_In_ IXmlDocument *xml, _In_ const std::wstring &content, _In_ const std::wstring &arguments)
{
ComPtr<IXmlNodeList> nodeList;
HRESULT hr = xml->GetElementsByTagName(WinToastStringWrapper(L"actions").Get(), &nodeList);
if (SUCCEEDED(hr)) {
@@ -934,102 +966,126 @@ HRESULT WinToast::addActionHelper(_In_ IXmlDocument *xml, _In_ const std::wstrin
return hr;
}
void WinToast::setError(_Out_ WinToastError* error, _In_ WinToastError value) {
void WinToast::setError(_Out_ WinToastError *error, _In_ WinToastError value)
{
if (error) {
*error = value;
}
}
WinToastTemplate::WinToastTemplate(_In_ WinToastTemplateType type) : _type(type) {
static const std::size_t TextFieldsCount[] = { 1, 2, 2, 3, 1, 2, 2, 3};
WinToastTemplate::WinToastTemplate(_In_ WinToastTemplateType type)
: _type(type)
{
static const std::size_t TextFieldsCount[] = {1, 2, 2, 3, 1, 2, 2, 3};
_textFields = std::vector<std::wstring>(TextFieldsCount[type], L"");
}
WinToastTemplate::~WinToastTemplate() {
WinToastTemplate::~WinToastTemplate()
{
_textFields.clear();
}
void WinToastTemplate::setTextField(_In_ const std::wstring& txt, _In_ WinToastTemplate::TextField pos) {
void WinToastTemplate::setTextField(_In_ const std::wstring &txt, _In_ WinToastTemplate::TextField pos)
{
_textFields[pos] = txt;
}
void WinToastTemplate::setImagePath(_In_ const std::wstring& imgPath) {
void WinToastTemplate::setImagePath(_In_ const std::wstring &imgPath)
{
_imagePath = imgPath;
}
void WinToastTemplate::setAudioPath(_In_ const std::wstring& audioPath) {
void WinToastTemplate::setAudioPath(_In_ const std::wstring &audioPath)
{
_audioPath = audioPath;
}
void WinToastTemplate::setAudioOption(_In_ WinToastTemplate::AudioOption audioOption) {
void WinToastTemplate::setAudioOption(_In_ WinToastTemplate::AudioOption audioOption)
{
_audioOption = audioOption;
}
void WinToastTemplate::setDuration(_In_ Duration duration) {
void WinToastTemplate::setDuration(_In_ Duration duration)
{
_duration = duration;
}
void WinToastTemplate::setExpiration(_In_ INT64 millisecondsFromNow) {
void WinToastTemplate::setExpiration(_In_ INT64 millisecondsFromNow)
{
_expiration = millisecondsFromNow;
}
void WinToastTemplate::setAttributionText(_In_ const std::wstring& attributionText) {
void WinToastTemplate::setAttributionText(_In_ const std::wstring &attributionText)
{
_attributionText = attributionText;
}
void WinToastTemplate::addAction(_In_ const std::wstring & label)
void WinToastTemplate::addAction(_In_ const std::wstring &label)
{
_actions.push_back(label);
}
std::size_t WinToastTemplate::textFieldsCount() const {
std::size_t WinToastTemplate::textFieldsCount() const
{
return _textFields.size();
}
std::size_t WinToastTemplate::actionsCount() const {
std::size_t WinToastTemplate::actionsCount() const
{
return _actions.size();
}
bool WinToastTemplate::hasImage() const {
bool WinToastTemplate::hasImage() const
{
return _type < WinToastTemplateType::Text01;
}
const std::vector<std::wstring>& WinToastTemplate::textFields() const {
const std::vector<std::wstring> &WinToastTemplate::textFields() const
{
return _textFields;
}
const std::wstring& WinToastTemplate::textField(_In_ TextField pos) const {
const std::wstring &WinToastTemplate::textField(_In_ TextField pos) const
{
return _textFields[pos];
}
const std::wstring& WinToastTemplate::actionLabel(_In_ int pos) const {
const std::wstring &WinToastTemplate::actionLabel(_In_ int pos) const
{
return _actions[pos];
}
const std::wstring& WinToastTemplate::imagePath() const {
const std::wstring &WinToastTemplate::imagePath() const
{
return _imagePath;
}
const std::wstring& WinToastTemplate::audioPath() const {
const std::wstring &WinToastTemplate::audioPath() const
{
return _audioPath;
}
const std::wstring& WinToastTemplate::attributionText() const {
const std::wstring &WinToastTemplate::attributionText() const
{
return _attributionText;
}
INT64 WinToastTemplate::expiration() const {
INT64 WinToastTemplate::expiration() const
{
return _expiration;
}
WinToastTemplate::WinToastTemplateType WinToastTemplate::type() const {
WinToastTemplate::WinToastTemplateType WinToastTemplate::type() const
{
return _type;
}
WinToastTemplate::AudioOption WinToastTemplate::audioOption() const {
WinToastTemplate::AudioOption WinToastTemplate::audioOption() const
{
return _audioOption;
}
WinToastTemplate::Duration WinToastTemplate::duration() const {
WinToastTemplate::Duration WinToastTemplate::duration() const
{
return _duration;
}

View File

@@ -1,23 +1,23 @@
#ifndef WINTOASTLIB_H
#define WINTOASTLIB_H
#include <Windows.h>
#include <sdkddkver.h>
#include <WinUser.h>
#include <ShObjIdl.h>
#include <wrl/implements.h>
#include <wrl/event.h>
#include <windows.ui.notifications.h>
#include <strsafe.h>
#include <Psapi.h>
#include <ShObjIdl.h>
#include <ShlObj.h>
#include <roapi.h>
#include <propvarutil.h>
#include <WinUser.h>
#include <Windows.h>
#include <functiondiscoverykeys.h>
#include <iostream>
#include <winstring.h>
#include <string.h>
#include <vector>
#include <map>
#include <propvarutil.h>
#include <roapi.h>
#include <sdkddkver.h>
#include <string.h>
#include <strsafe.h>
#include <vector>
#include <windows.ui.notifications.h>
#include <winstring.h>
#include <wrl/event.h>
#include <wrl/implements.h>
using namespace Microsoft::WRL;
using namespace ABI::Windows::Data::Xml::Dom;
using namespace ABI::Windows::Foundation;
@@ -26,24 +26,28 @@ using namespace Windows::Foundation;
#define DEFAULT_SHELL_LINKS_PATH L"\\Microsoft\\Windows\\Start Menu\\Programs\\"
#define DEFAULT_LINK_FORMAT L".lnk"
namespace WinToastLib {
class IWinToastHandler {
public:
namespace WinToastLib
{
class IWinToastHandler
{
public:
enum WinToastDismissalReason {
UserCanceled = ToastDismissalReason::ToastDismissalReason_UserCanceled,
ApplicationHidden = ToastDismissalReason::ToastDismissalReason_ApplicationHidden,
TimedOut = ToastDismissalReason::ToastDismissalReason_TimedOut
};
virtual ~IWinToastHandler() {}
virtual ~IWinToastHandler()
{
}
virtual void toastActivated() = 0;
virtual void toastActivated(int actionIndex) = 0;
virtual void toastDismissed(WinToastDismissalReason state) = 0;
virtual void toastFailed() = 0;
};
};
class WinToastTemplate {
public:
class WinToastTemplate
{
public:
enum Duration { System, Short, Long };
enum AudioOption { Default = 0, Silent = 1, Loop = 2 };
enum TextField { FirstLine = 0, SecondLine, ThirdLine };
@@ -62,28 +66,29 @@ namespace WinToastLib {
WinToastTemplate(_In_ WinToastTemplateType type = WinToastTemplateType::ImageAndText02);
~WinToastTemplate();
void setTextField(_In_ const std::wstring& txt, _In_ TextField pos);
void setImagePath(_In_ const std::wstring& imgPath);
void setAudioPath(_In_ const std::wstring& audioPath);
void setAttributionText(_In_ const std::wstring & attributionText);
void addAction(_In_ const std::wstring& label);
void setTextField(_In_ const std::wstring &txt, _In_ TextField pos);
void setImagePath(_In_ const std::wstring &imgPath);
void setAudioPath(_In_ const std::wstring &audioPath);
void setAttributionText(_In_ const std::wstring &attributionText);
void addAction(_In_ const std::wstring &label);
void setAudioOption(_In_ WinToastTemplate::AudioOption audioOption);
void setDuration(_In_ Duration duration);
void setExpiration(_In_ INT64 millisecondsFromNow);
std::size_t textFieldsCount() const;
std::size_t actionsCount() const;
bool hasImage() const;
const std::vector<std::wstring>& textFields() const;
const std::wstring& textField(_In_ TextField pos) const;
const std::wstring& actionLabel(_In_ int pos) const;
const std::wstring& imagePath() const;
const std::wstring& audioPath() const;
const std::wstring& attributionText() const;
const std::vector<std::wstring> &textFields() const;
const std::wstring &textField(_In_ TextField pos) const;
const std::wstring &actionLabel(_In_ int pos) const;
const std::wstring &imagePath() const;
const std::wstring &audioPath() const;
const std::wstring &attributionText() const;
INT64 expiration() const;
WinToastTemplateType type() const;
WinToastTemplate::AudioOption audioOption() const;
Duration duration() const;
private:
private:
std::vector<std::wstring> _textFields;
std::vector<std::wstring> _actions;
std::wstring _imagePath = L"";
@@ -93,21 +98,12 @@ namespace WinToastLib {
AudioOption _audioOption = WinToastTemplate::AudioOption::Default;
WinToastTemplateType _type = WinToastTemplateType::Text01;
Duration _duration = Duration::System;
};
};
class WinToast {
public:
enum WinToastError {
NoError = 0,
NotInitialized,
SystemNotSupported,
ShellLinkNotCreated,
InvalidAppUserModelID,
InvalidParameters,
InvalidHandler,
NotDisplayed,
UnknownError
};
class WinToast
{
public:
enum WinToastError { NoError = 0, NotInitialized, SystemNotSupported, ShellLinkNotCreated, InvalidAppUserModelID, InvalidParameters, InvalidHandler, NotDisplayed, UnknownError };
enum ShortcutResult {
SHORTCUT_UNCHANGED = 0,
@@ -122,43 +118,39 @@ namespace WinToastLib {
WinToast(void);
virtual ~WinToast();
static WinToast* instance();
static WinToast *instance();
static bool isCompatible();
static bool isSupportingModernFeatures();
static std::wstring configureAUMI(_In_ const std::wstring& companyName,
_In_ const std::wstring& productName,
_In_ const std::wstring& subProduct = std::wstring(),
_In_ const std::wstring& versionInformation = std::wstring()
);
virtual bool initialize(_Out_ WinToastError* error = nullptr);
static std::wstring configureAUMI(_In_ const std::wstring &companyName, _In_ const std::wstring &productName, _In_ const std::wstring &subProduct = std::wstring(), _In_ const std::wstring &versionInformation = std::wstring());
virtual bool initialize(_Out_ WinToastError *error = nullptr);
virtual bool isInitialized() const;
virtual bool hideToast(_In_ INT64 id);
virtual INT64 showToast(_In_ const WinToastTemplate& toast, _In_ IWinToastHandler* handler, _Out_ WinToastError* error = nullptr);
virtual INT64 showToast(_In_ const WinToastTemplate &toast, _In_ IWinToastHandler *handler, _Out_ WinToastError *error = nullptr);
virtual void clear();
virtual enum ShortcutResult createShortcut();
const std::wstring& appName() const;
const std::wstring& appUserModelId() const;
void setAppUserModelId(_In_ const std::wstring& appName);
void setAppName(_In_ const std::wstring& appName);
const std::wstring &appName() const;
const std::wstring &appUserModelId() const;
void setAppUserModelId(_In_ const std::wstring &appName);
void setAppName(_In_ const std::wstring &appName);
protected:
protected:
bool _isInitialized;
bool _hasCoInitialized;
std::wstring _appName;
std::wstring _aumi;
std::map<INT64, ComPtr<IToastNotification>> _buffer;
HRESULT validateShellLinkHelper(_Out_ bool& wasChanged);
HRESULT validateShellLinkHelper(_Out_ bool &wasChanged);
HRESULT createShellLinkHelper();
HRESULT setImageFieldHelper(_In_ IXmlDocument *xml, _In_ const std::wstring& path);
HRESULT setAudioFieldHelper(_In_ IXmlDocument *xml, _In_ const std::wstring& path, _In_opt_ WinToastTemplate::AudioOption option = WinToastTemplate::AudioOption::Default);
HRESULT setTextFieldHelper(_In_ IXmlDocument *xml, _In_ const std::wstring& text, _In_ int pos);
HRESULT setAttributionTextFieldHelper(_In_ IXmlDocument *xml, _In_ const std::wstring& text);
HRESULT addActionHelper(_In_ IXmlDocument *xml, _In_ const std::wstring& action, _In_ const std::wstring& arguments);
HRESULT addDurationHelper(_In_ IXmlDocument *xml, _In_ const std::wstring& duration);
ComPtr<IToastNotifier> notifier(_In_ bool* succeded) const;
void setError(_Out_ WinToastError* error, _In_ WinToastError value);
};
HRESULT setImageFieldHelper(_In_ IXmlDocument *xml, _In_ const std::wstring &path);
HRESULT setAudioFieldHelper(_In_ IXmlDocument *xml, _In_ const std::wstring &path, _In_opt_ WinToastTemplate::AudioOption option = WinToastTemplate::AudioOption::Default);
HRESULT setTextFieldHelper(_In_ IXmlDocument *xml, _In_ const std::wstring &text, _In_ int pos);
HRESULT setAttributionTextFieldHelper(_In_ IXmlDocument *xml, _In_ const std::wstring &text);
HRESULT addActionHelper(_In_ IXmlDocument *xml, _In_ const std::wstring &action, _In_ const std::wstring &arguments);
HRESULT addDurationHelper(_In_ IXmlDocument *xml, _In_ const std::wstring &duration);
ComPtr<IToastNotifier> notifier(_In_ bool *succeded) const;
void setError(_Out_ WinToastError *error, _In_ WinToastError value);
};
}
#endif // WINTOASTLIB_H

View File

@@ -1,9 +1,12 @@
#include "publicroomlistmodel.h"
PublicRoomListModel::PublicRoomListModel(QObject* parent)
: QAbstractListModel(parent) {}
PublicRoomListModel::PublicRoomListModel(QObject *parent)
: QAbstractListModel(parent)
{
}
void PublicRoomListModel::setConnection(Connection* conn) {
void PublicRoomListModel::setConnection(Connection *conn)
{
if (m_connection == conn)
return;
@@ -36,7 +39,8 @@ void PublicRoomListModel::setConnection(Connection* conn) {
emit hasMoreChanged();
}
void PublicRoomListModel::setServer(const QString& value) {
void PublicRoomListModel::setServer(const QString &value)
{
if (m_server == value)
return;
@@ -63,7 +67,8 @@ void PublicRoomListModel::setServer(const QString& value) {
emit hasMoreChanged();
}
void PublicRoomListModel::setKeyword(const QString& value) {
void PublicRoomListModel::setKeyword(const QString &value)
{
if (m_keyword == value)
return;
@@ -90,7 +95,8 @@ void PublicRoomListModel::setKeyword(const QString& value) {
emit hasMoreChanged();
}
void PublicRoomListModel::next(int count) {
void PublicRoomListModel::next(int count)
{
if (count < 1)
return;
@@ -103,8 +109,7 @@ void PublicRoomListModel::next(int count) {
if (!hasMore())
return;
job = m_connection->callApi<QueryPublicRoomsJob>(
m_server, count, nextBatch, QueryPublicRoomsJob::Filter{m_keyword});
job = m_connection->callApi<QueryPublicRoomsJob>(m_server, count, nextBatch, QueryPublicRoomsJob::Filter {m_keyword});
connect(job, &BaseJob::finished, this, [=] {
attempted = true;
@@ -112,8 +117,7 @@ void PublicRoomListModel::next(int count) {
if (job->status() == BaseJob::Success) {
nextBatch = job->nextBatch();
this->beginInsertRows({}, rooms.count(),
rooms.count() + job->chunk().count() - 1);
this->beginInsertRows({}, rooms.count(), rooms.count() + job->chunk().count() - 1);
rooms.append(job->chunk());
this->endInsertRows();
@@ -126,7 +130,8 @@ void PublicRoomListModel::next(int count) {
});
}
QVariant PublicRoomListModel::data(const QModelIndex& index, int role) const {
QVariant PublicRoomListModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
@@ -191,7 +196,8 @@ QVariant PublicRoomListModel::data(const QModelIndex& index, int role) const {
return {};
}
QHash<int, QByteArray> PublicRoomListModel::roleNames() const {
QHash<int, QByteArray> PublicRoomListModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[NameRole] = "name";
@@ -206,13 +212,15 @@ QHash<int, QByteArray> PublicRoomListModel::roleNames() const {
return roles;
}
int PublicRoomListModel::rowCount(const QModelIndex& parent) const {
int PublicRoomListModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return rooms.count();
}
bool PublicRoomListModel::hasMore() const {
bool PublicRoomListModel::hasMore() const
{
return !(attempted && nextBatch.isEmpty());
}

View File

@@ -10,16 +10,15 @@
using namespace Quotient;
class PublicRoomListModel : public QAbstractListModel {
class PublicRoomListModel : public QAbstractListModel
{
Q_OBJECT
Q_PROPERTY(Connection* connection READ connection WRITE setConnection NOTIFY
connectionChanged)
Q_PROPERTY(Connection *connection READ connection WRITE setConnection NOTIFY connectionChanged)
Q_PROPERTY(QString server READ server WRITE setServer NOTIFY serverChanged)
Q_PROPERTY(
QString keyword READ keyword WRITE setKeyword NOTIFY keywordChanged)
Q_PROPERTY(QString keyword READ keyword WRITE setKeyword NOTIFY keywordChanged)
Q_PROPERTY(bool hasMore READ hasMore NOTIFY hasMoreChanged)
public:
public:
enum EventRoles {
NameRole = Qt::DisplayRole + 1,
AvatarRole,
@@ -31,28 +30,37 @@ class PublicRoomListModel : public QAbstractListModel {
IsJoinedRole,
};
PublicRoomListModel(QObject* parent = nullptr);
PublicRoomListModel(QObject *parent = nullptr);
QVariant data(const QModelIndex& index, int role = NameRole) const override;
int rowCount(const QModelIndex& parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = NameRole) const override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QHash<int, QByteArray> roleNames() const override;
Connection* connection() const { return m_connection; }
void setConnection(Connection* value);
Connection *connection() const
{
return m_connection;
}
void setConnection(Connection *value);
QString server() const { return m_server; }
void setServer(const QString& value);
QString server() const
{
return m_server;
}
void setServer(const QString &value);
QString keyword() const { return m_keyword; }
void setKeyword(const QString& value);
QString keyword() const
{
return m_keyword;
}
void setKeyword(const QString &value);
bool hasMore() const;
Q_INVOKABLE void next(int count = 50);
private:
Connection* m_connection = nullptr;
private:
Connection *m_connection = nullptr;
QString m_server;
QString m_keyword;
@@ -61,9 +69,9 @@ class PublicRoomListModel : public QAbstractListModel {
QVector<PublicRoomsChunk> rooms;
QueryPublicRoomsJob* job = nullptr;
QueryPublicRoomsJob *job = nullptr;
signals:
signals:
void connectionChanged();
void serverChanged();
void keywordChanged();

View File

@@ -11,11 +11,17 @@
#include <QtGui/QColor>
#include <QtQuick>
RoomListModel::RoomListModel(QObject* parent) : QAbstractListModel(parent) {}
RoomListModel::RoomListModel(QObject *parent)
: QAbstractListModel(parent)
{
}
RoomListModel::~RoomListModel() {}
RoomListModel::~RoomListModel()
{
}
void RoomListModel::setConnection(Connection* connection) {
void RoomListModel::setConnection(Connection *connection)
{
if (connection == m_connection)
return;
if (m_connection)
@@ -31,32 +37,27 @@ void RoomListModel::setConnection(Connection* connection) {
m_connection = connection;
for (SpectralRoom* room : m_rooms)
for (SpectralRoom *room : m_rooms)
room->disconnect(this);
connect(connection, &Connection::connected, this,
&RoomListModel::doResetModel);
connect(connection, &Connection::invitedRoom, this,
&RoomListModel::updateRoom);
connect(connection, &Connection::joinedRoom, this,
&RoomListModel::updateRoom);
connect(connection, &Connection::connected, this, &RoomListModel::doResetModel);
connect(connection, &Connection::invitedRoom, this, &RoomListModel::updateRoom);
connect(connection, &Connection::joinedRoom, this, &RoomListModel::updateRoom);
connect(connection, &Connection::leftRoom, this, &RoomListModel::updateRoom);
connect(connection, &Connection::aboutToDeleteRoom, this,
&RoomListModel::deleteRoom);
connect(connection, &Connection::directChatsListChanged, this,
[=](Quotient::DirectChatsMap additions,
Quotient::DirectChatsMap removals) {
connect(connection, &Connection::aboutToDeleteRoom, this, &RoomListModel::deleteRoom);
connect(connection, &Connection::directChatsListChanged, this, [=](Quotient::DirectChatsMap additions, Quotient::DirectChatsMap removals) {
for (QString roomID : additions.values() + removals.values()) {
auto room = connection->room(roomID);
if (room)
refresh(static_cast<SpectralRoom*>(room));
refresh(static_cast<SpectralRoom *>(room));
}
});
doResetModel();
}
void RoomListModel::doResetModel() {
void RoomListModel::doResetModel()
{
beginResetModel();
m_rooms.clear();
for (auto r : m_connection->allRooms()) {
@@ -66,12 +67,14 @@ void RoomListModel::doResetModel() {
refreshNotificationCount();
}
SpectralRoom* RoomListModel::roomAt(int row) const {
SpectralRoom *RoomListModel::roomAt(int row) const
{
return m_rooms.at(row);
}
void RoomListModel::doAddRoom(Room* r) {
if (auto room = static_cast<SpectralRoom*>(r)) {
void RoomListModel::doAddRoom(Room *r)
{
if (auto room = static_cast<SpectralRoom *>(r)) {
m_rooms.append(room);
connectRoomSignals(room);
emit roomAdded(room);
@@ -81,51 +84,60 @@ void RoomListModel::doAddRoom(Room* r) {
}
}
void RoomListModel::connectRoomSignals(SpectralRoom* room) {
connect(room, &Room::displaynameChanged, this, [=] { refresh(room); });
connect(room, &Room::unreadMessagesChanged, this, [=] { refresh(room); });
connect(room, &Room::notificationCountChanged, this, [=] { refresh(room); });
connect(room, &Room::avatarChanged, this,
[this, room] { refresh(room, {AvatarRole}); });
connect(room, &Room::tagsChanged, this, [=] { refresh(room); });
connect(room, &Room::joinStateChanged, this, [=] { refresh(room); });
connect(room, &Room::addedMessages, this,
[=] { refresh(room, {LastEventRole}); });
void RoomListModel::connectRoomSignals(SpectralRoom *room)
{
connect(room, &Room::displaynameChanged, this, [=] {
refresh(room);
});
connect(room, &Room::unreadMessagesChanged, this, [=] {
refresh(room);
});
connect(room, &Room::notificationCountChanged, this, [=] {
refresh(room);
});
connect(room, &Room::avatarChanged, this, [this, room] {
refresh(room, {AvatarRole});
});
connect(room, &Room::tagsChanged, this, [=] {
refresh(room);
});
connect(room, &Room::joinStateChanged, this, [=] {
refresh(room);
});
connect(room, &Room::addedMessages, this, [=] {
refresh(room, {LastEventRole});
});
connect(room, &Room::notificationCountChanged, this, [=] {
if (room->notificationCount() == 0)
return;
if (room->timelineSize() == 0)
return;
const RoomEvent* lastEvent = room->messageEvents().rbegin()->get();
const RoomEvent *lastEvent = room->messageEvents().rbegin()->get();
if (lastEvent->isStateEvent())
return;
User* sender = room->user(lastEvent->senderId());
User *sender = room->user(lastEvent->senderId());
if (sender == room->localUser())
return;
emit newMessage(room->id(), lastEvent->id(), room->displayName(),
sender->displayname(), room->eventToString(*lastEvent),
room->avatar(128));
emit newMessage(room->id(), lastEvent->id(), room->displayName(), sender->displayname(), room->eventToString(*lastEvent), room->avatar(128));
});
connect(room, &Room::highlightCountChanged, this, [=] {
if (room->highlightCount() == 0)
return;
if (room->timelineSize() == 0)
return;
const RoomEvent* lastEvent = room->messageEvents().rbegin()->get();
const RoomEvent *lastEvent = room->messageEvents().rbegin()->get();
if (lastEvent->isStateEvent())
return;
User* sender = room->user(lastEvent->senderId());
User *sender = room->user(lastEvent->senderId());
if (sender == room->localUser())
return;
emit newHighlight(room->id(), lastEvent->id(), room->displayName(),
sender->displayname(), room->eventToString(*lastEvent),
room->avatar(128));
emit newHighlight(room->id(), lastEvent->id(), room->displayName(), sender->displayname(), room->eventToString(*lastEvent), room->avatar(128));
});
connect(room, &Room::notificationCountChanged, this,
&RoomListModel::refreshNotificationCount);
connect(room, &Room::notificationCountChanged, this, &RoomListModel::refreshNotificationCount);
}
void RoomListModel::refreshNotificationCount() {
void RoomListModel::refreshNotificationCount()
{
int count = 0;
for (auto room : m_rooms) {
count += room->notificationCount();
@@ -134,26 +146,26 @@ void RoomListModel::refreshNotificationCount() {
emit notificationCountChanged();
}
void RoomListModel::updateRoom(Room* room, Room* prev) {
void RoomListModel::updateRoom(Room *room, Room *prev)
{
// There are two cases when this method is called:
// 1. (prev == nullptr) adding a new room to the room list
// 2. (prev != nullptr) accepting/rejecting an invitation or inviting to
// the previously left room (in both cases prev has the previous state).
if (prev == room) {
qCritical() << "RoomListModel::updateRoom: room tried to replace itself";
refresh(static_cast<SpectralRoom*>(room));
refresh(static_cast<SpectralRoom *>(room));
return;
}
if (prev && room->id() != prev->id()) {
qCritical() << "RoomListModel::updateRoom: attempt to update room"
<< room->id() << "to" << prev->id();
qCritical() << "RoomListModel::updateRoom: attempt to update room" << room->id() << "to" << prev->id();
// That doesn't look right but technically we still can do it.
}
// Ok, we're through with pre-checks, now for the real thing.
auto newRoom = static_cast<SpectralRoom*>(room);
const auto it = std::find_if(
m_rooms.begin(), m_rooms.end(),
[=](const SpectralRoom* r) { return r == prev || r == newRoom; });
auto newRoom = static_cast<SpectralRoom *>(room);
const auto it = std::find_if(m_rooms.begin(), m_rooms.end(), [=](const SpectralRoom *r) {
return r == prev || r == newRoom;
});
if (it != m_rooms.end()) {
const int row = it - m_rooms.begin();
// There's no guarantee that prev != newRoom
@@ -170,7 +182,8 @@ void RoomListModel::updateRoom(Room* room, Room* prev) {
}
}
void RoomListModel::deleteRoom(Room* room) {
void RoomListModel::deleteRoom(Room *room)
{
qDebug() << "Deleting room" << room->id();
const auto it = std::find(m_rooms.begin(), m_rooms.end(), room);
if (it == m_rooms.end())
@@ -182,13 +195,15 @@ void RoomListModel::deleteRoom(Room* room) {
endRemoveRows();
}
int RoomListModel::rowCount(const QModelIndex& parent) const {
int RoomListModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return m_rooms.count();
}
QVariant RoomListModel::data(const QModelIndex& index, int role) const {
QVariant RoomListModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
@@ -196,7 +211,7 @@ QVariant RoomListModel::data(const QModelIndex& index, int role) const {
qDebug() << "UserListModel: something wrong here...";
return QVariant();
}
SpectralRoom* room = m_rooms.at(index.row());
SpectralRoom *room = m_rooms.at(index.row());
if (role == NameRole)
return room->displayName();
if (role == AvatarRole)
@@ -234,7 +249,8 @@ QVariant RoomListModel::data(const QModelIndex& index, int role) const {
return QVariant();
}
void RoomListModel::refresh(SpectralRoom* room, const QVector<int>& roles) {
void RoomListModel::refresh(SpectralRoom *room, const QVector<int> &roles)
{
const auto it = std::find(m_rooms.begin(), m_rooms.end(), room);
if (it == m_rooms.end()) {
qCritical() << "Room" << room->id() << "not found in the room list";
@@ -244,7 +260,8 @@ void RoomListModel::refresh(SpectralRoom* room, const QVector<int>& roles) {
emit dataChanged(idx, idx, roles);
}
QHash<int, QByteArray> RoomListModel::roleNames() const {
QHash<int, QByteArray> RoomListModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[NameRole] = "name";
roles[AvatarRole] = "avatar";

View File

@@ -10,10 +10,11 @@
using namespace Quotient;
class RoomType : public QObject {
class RoomType : public QObject
{
Q_OBJECT
public:
public:
enum Types {
Invited = 1,
Favorite,
@@ -24,13 +25,13 @@ class RoomType : public QObject {
Q_ENUMS(Types)
};
class RoomListModel : public QAbstractListModel {
class RoomListModel : public QAbstractListModel
{
Q_OBJECT
Q_PROPERTY(Connection* connection READ connection WRITE setConnection)
Q_PROPERTY(int notificationCount READ notificationCount NOTIFY
notificationCountChanged)
Q_PROPERTY(Connection *connection READ connection WRITE setConnection)
Q_PROPERTY(int notificationCount READ notificationCount NOTIFY notificationCountChanged)
public:
public:
enum EventRoles {
NameRole = Qt::UserRole + 1,
AvatarRole,
@@ -46,56 +47,50 @@ class RoomListModel : public QAbstractListModel {
};
Q_ENUM(EventRoles)
RoomListModel(QObject* parent = nullptr);
RoomListModel(QObject *parent = nullptr);
virtual ~RoomListModel() override;
Connection* connection() const { return m_connection; }
void setConnection(Connection* connection);
Connection *connection() const
{
return m_connection;
}
void setConnection(Connection *connection);
void doResetModel();
Q_INVOKABLE SpectralRoom* roomAt(int row) const;
Q_INVOKABLE SpectralRoom *roomAt(int row) const;
QVariant data(const QModelIndex& index,
int role = Qt::DisplayRole) const override;
Q_INVOKABLE int rowCount(
const QModelIndex& parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
Q_INVOKABLE int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QHash<int, QByteArray> roleNames() const override;
int notificationCount() const { return m_notificationCount; }
int notificationCount() const
{
return m_notificationCount;
}
private slots:
void doAddRoom(Room* room);
void updateRoom(Room* room, Room* prev);
void deleteRoom(Room* room);
void refresh(SpectralRoom* room, const QVector<int>& roles = {});
private slots:
void doAddRoom(Room *room);
void updateRoom(Room *room, Room *prev);
void deleteRoom(Room *room);
void refresh(SpectralRoom *room, const QVector<int> &roles = {});
void refreshNotificationCount();
private:
Connection* m_connection = nullptr;
QList<SpectralRoom*> m_rooms;
private:
Connection *m_connection = nullptr;
QList<SpectralRoom *> m_rooms;
int m_notificationCount = 0;
void connectRoomSignals(SpectralRoom* room);
void connectRoomSignals(SpectralRoom *room);
signals:
signals:
void connectionChanged();
void notificationCountChanged();
void roomAdded(SpectralRoom* room);
void newMessage(const QString& roomId,
const QString& eventId,
const QString& roomName,
const QString& senderName,
const QString& text,
const QImage& icon);
void newHighlight(const QString& roomId,
const QString& eventId,
const QString& roomName,
const QString& senderName,
const QString& text,
const QImage& icon);
void roomAdded(SpectralRoom *room);
void newMessage(const QString &roomId, const QString &eventId, const QString &roomName, const QString &senderName, const QString &text, const QImage &icon);
void newHighlight(const QString &roomId, const QString &eventId, const QString &roomName, const QString &senderName, const QString &text, const QImage &icon);
};
#endif // ROOMLISTMODEL_H

View File

@@ -19,36 +19,33 @@
#include "csapi/typing.h"
#include "events/accountdataevents.h"
#include "events/reactionevent.h"
#include "events/roommessageevent.h"
#include "events/typingevent.h"
#include "events/roompowerlevelsevent.h"
#include "events/roomcanonicalaliasevent.h"
#include "events/roommessageevent.h"
#include "events/roompowerlevelsevent.h"
#include "events/typingevent.h"
#include "jobs/downloadfilejob.h"
#include "user.h"
#include "utils.h"
SpectralRoom::SpectralRoom(Connection* connection,
QString roomId,
JoinState joinState)
: Room(connection, std::move(roomId), joinState) {
connect(this, &SpectralRoom::notificationCountChanged, this,
&SpectralRoom::countChanged);
connect(this, &SpectralRoom::highlightCountChanged, this,
&SpectralRoom::countChanged);
SpectralRoom::SpectralRoom(Connection *connection, QString roomId, JoinState joinState)
: Room(connection, std::move(roomId), joinState)
{
connect(this, &SpectralRoom::notificationCountChanged, this, &SpectralRoom::countChanged);
connect(this, &SpectralRoom::highlightCountChanged, this, &SpectralRoom::countChanged);
connect(this, &Room::fileTransferCompleted, this, [=] {
setFileUploadingProgress(0);
setHasFileUploading(false);
});
}
void SpectralRoom::uploadFile(const QUrl& url, const QString& body) {
void SpectralRoom::uploadFile(const QUrl &url, const QString &body)
{
if (url.isEmpty())
return;
QString txnId = postFile(body.isEmpty() ? url.fileName() : body, url, false);
setHasFileUploading(true);
connect(this, &Room::fileTransferCompleted,
[=](QString id, QUrl /*localFile*/, QUrl /*mxcUrl*/) {
connect(this, &Room::fileTransferCompleted, [=](QString id, QUrl /*localFile*/, QUrl /*mxcUrl*/) {
if (id == txnId) {
setFileUploadingProgress(0);
setHasFileUploading(false);
@@ -60,9 +57,7 @@ void SpectralRoom::uploadFile(const QUrl& url, const QString& body) {
setHasFileUploading(false);
}
});
connect(
this, &Room::fileTransferProgress,
[=](QString id, qint64 progress, qint64 total) {
connect(this, &Room::fileTransferProgress, [=](QString id, qint64 progress, qint64 total) {
if (id == txnId) {
qDebug() << "Progress:" << progress << total;
setFileUploadingProgress(int(float(progress) / float(total) * 100));
@@ -70,40 +65,43 @@ void SpectralRoom::uploadFile(const QUrl& url, const QString& body) {
});
}
void SpectralRoom::acceptInvitation() {
void SpectralRoom::acceptInvitation()
{
connection()->joinRoom(id());
}
void SpectralRoom::forget() {
void SpectralRoom::forget()
{
connection()->forgetRoom(id());
}
QVariantList SpectralRoom::getUsersTyping() const {
QVariantList SpectralRoom::getUsersTyping() const
{
auto users = usersTyping();
users.removeAll(localUser());
QVariantList userVariants;
for (User* user : users) {
for (User *user : users) {
userVariants.append(QVariant::fromValue(user));
}
return userVariants;
}
void SpectralRoom::sendTypingNotification(bool isTyping) {
connection()->callApi<SetTypingJob>(BackgroundRequest, localUser()->id(),
id(), isTyping, 10000);
void SpectralRoom::sendTypingNotification(bool isTyping)
{
connection()->callApi<SetTypingJob>(BackgroundRequest, localUser()->id(), id(), isTyping, 10000);
}
QString SpectralRoom::lastEvent() const {
QString SpectralRoom::lastEvent() const
{
for (auto i = messageEvents().rbegin(); i < messageEvents().rend(); i++) {
const RoomEvent* evt = i->get();
const RoomEvent *evt = i->get();
if (is<RedactionEvent>(*evt) || is<ReactionEvent>(*evt))
continue;
if (evt->isRedacted())
continue;
if (evt->isStateEvent() &&
static_cast<const StateEventBase&>(*evt).repeatsState())
if (evt->isStateEvent() && static_cast<const StateEventBase &>(*evt).repeatsState())
continue;
if (auto e = eventCast<const RoomMessageEvent>(evt)) {
@@ -115,77 +113,79 @@ QString SpectralRoom::lastEvent() const {
if (connection()->isIgnored(user(evt->senderId())))
continue;
return user(evt->senderId())->displayname() +
(evt->isStateEvent() ? " " : ": ") + eventToString(*evt);
return user(evt->senderId())->displayname() + (evt->isStateEvent() ? " " : ": ") + eventToString(*evt);
}
return "";
}
bool SpectralRoom::isEventHighlighted(const RoomEvent* e) const {
bool SpectralRoom::isEventHighlighted(const RoomEvent *e) const
{
return highlights.contains(e);
}
void SpectralRoom::checkForHighlights(const Quotient::TimelineItem& ti) {
void SpectralRoom::checkForHighlights(const Quotient::TimelineItem &ti)
{
auto localUserId = localUser()->id();
if (ti->senderId() == localUserId)
return;
if (auto* e = ti.viewAs<RoomMessageEvent>()) {
const auto& text = e->plainBody();
if (text.contains(localUserId) ||
text.contains(roomMembername(localUserId)))
if (auto *e = ti.viewAs<RoomMessageEvent>()) {
const auto &text = e->plainBody();
if (text.contains(localUserId) || text.contains(roomMembername(localUserId)))
highlights.insert(e);
}
}
void SpectralRoom::onAddNewTimelineEvents(timeline_iter_t from) {
std::for_each(from, messageEvents().cend(),
[this](const TimelineItem& ti) { checkForHighlights(ti); });
void SpectralRoom::onAddNewTimelineEvents(timeline_iter_t from)
{
std::for_each(from, messageEvents().cend(), [this](const TimelineItem &ti) {
checkForHighlights(ti);
});
}
void SpectralRoom::onAddHistoricalTimelineEvents(rev_iter_t from) {
std::for_each(from, messageEvents().crend(),
[this](const TimelineItem& ti) { checkForHighlights(ti); });
void SpectralRoom::onAddHistoricalTimelineEvents(rev_iter_t from)
{
std::for_each(from, messageEvents().crend(), [this](const TimelineItem &ti) {
checkForHighlights(ti);
});
}
void SpectralRoom::onRedaction(const RoomEvent& prevEvent,
const RoomEvent& /*after*/) {
if (const auto& e = eventCast<const ReactionEvent>(&prevEvent)) {
if (auto relatedEventId = e->relation().eventId;
!relatedEventId.isEmpty()) {
void SpectralRoom::onRedaction(const RoomEvent &prevEvent, const RoomEvent & /*after*/)
{
if (const auto &e = eventCast<const ReactionEvent>(&prevEvent)) {
if (auto relatedEventId = e->relation().eventId; !relatedEventId.isEmpty()) {
emit updatedEvent(relatedEventId);
}
}
}
void SpectralRoom::countChanged() {
void SpectralRoom::countChanged()
{
if (displayed() && !hasUnreadMessages()) {
resetNotificationCount();
resetHighlightCount();
}
}
QDateTime SpectralRoom::lastActiveTime() const {
QDateTime SpectralRoom::lastActiveTime() const
{
if (timelineSize() == 0)
return QDateTime();
return messageEvents().rbegin()->get()->originTimestamp();
}
int SpectralRoom::savedTopVisibleIndex() const {
return firstDisplayedMarker() == timelineEdge()
? 0
: int(firstDisplayedMarker() - messageEvents().rbegin());
int SpectralRoom::savedTopVisibleIndex() const
{
return firstDisplayedMarker() == timelineEdge() ? 0 : int(firstDisplayedMarker() - messageEvents().rbegin());
}
int SpectralRoom::savedBottomVisibleIndex() const {
return lastDisplayedMarker() == timelineEdge()
? 0
: int(lastDisplayedMarker() - messageEvents().rbegin());
int SpectralRoom::savedBottomVisibleIndex() const
{
return lastDisplayedMarker() == timelineEdge() ? 0 : int(lastDisplayedMarker() - messageEvents().rbegin());
}
void SpectralRoom::saveViewport(int topIndex, int bottomIndex) {
if (topIndex == -1 || bottomIndex == -1 ||
(bottomIndex == savedBottomVisibleIndex() &&
(bottomIndex == 0 || topIndex == savedTopVisibleIndex())))
void SpectralRoom::saveViewport(int topIndex, int bottomIndex)
{
if (topIndex == -1 || bottomIndex == -1 || (bottomIndex == savedBottomVisibleIndex() && (bottomIndex == 0 || topIndex == savedTopVisibleIndex())))
return;
if (bottomIndex == 0) {
setFirstDisplayedEventId({});
@@ -196,7 +196,8 @@ void SpectralRoom::saveViewport(int topIndex, int bottomIndex) {
setLastDisplayedEvent(maxTimelineIndex() - bottomIndex);
}
QVariantList SpectralRoom::getUsers(const QString& keyword) const {
QVariantList SpectralRoom::getUsers(const QString &keyword) const
{
const auto userList = users();
QVariantList matchedList;
for (const auto u : userList)
@@ -207,11 +208,13 @@ QVariantList SpectralRoom::getUsers(const QString& keyword) const {
return matchedList;
}
QUrl SpectralRoom::urlToMxcUrl(QUrl mxcUrl) {
QUrl SpectralRoom::urlToMxcUrl(QUrl mxcUrl)
{
return DownloadFileJob::makeRequestUrl(connection()->homeserver(), mxcUrl);
}
QString SpectralRoom::avatarMediaId() const {
QString SpectralRoom::avatarMediaId() const
{
if (const auto avatar = Room::avatarMediaId(); !avatar.isEmpty()) {
return avatar;
}
@@ -227,21 +230,19 @@ QString SpectralRoom::avatarMediaId() const {
return {};
}
QString SpectralRoom::eventToString(const RoomEvent& evt,
Qt::TextFormat format,
bool removeReply) const {
QString SpectralRoom::eventToString(const RoomEvent &evt, Qt::TextFormat format, bool removeReply) const
{
const bool prettyPrint = (format == Qt::RichText);
using namespace Quotient;
return visit(
evt,
[prettyPrint, removeReply](const RoomMessageEvent& e) {
[prettyPrint, removeReply](const RoomMessageEvent &e) {
using namespace MessageEventContent;
// 1. prettyPrint/HTML
if (prettyPrint && e.hasTextContent() &&
e.mimeType().name() != "text/plain") {
auto htmlBody = static_cast<const TextContent*>(e.content())->body;
if (prettyPrint && e.hasTextContent() && e.mimeType().name() != "text/plain") {
auto htmlBody = static_cast<const TextContent *>(e.content())->body;
if (removeReply) {
htmlBody.remove(utils::removeRichReplyRegex);
}
@@ -252,11 +253,9 @@ QString SpectralRoom::eventToString(const RoomEvent& evt,
}
if (e.hasFileContent()) {
auto fileCaption =
e.content()->fileInfo()->originalName.toHtmlEscaped();
auto fileCaption = e.content()->fileInfo()->originalName.toHtmlEscaped();
if (fileCaption.isEmpty()) {
fileCaption = prettyPrint ? Quotient::prettyPrint(e.plainBody())
: e.plainBody();
fileCaption = prettyPrint ? Quotient::prettyPrint(e.plainBody()) : e.plainBody();
} else if (e.content()->fileInfo()->originalName != e.plainBody()) {
fileCaption = e.plainBody() + " | " + fileCaption;
}
@@ -266,7 +265,7 @@ QString SpectralRoom::eventToString(const RoomEvent& evt,
// 2. prettyPrint/text 3. plainText/HTML 4. plainText/text
QString plainBody;
if (e.hasTextContent() && e.content() && e.mimeType().name() == "text/plain") { // 2/4
plainBody = static_cast<const TextContent*>(e.content())->body;
plainBody = static_cast<const TextContent *>(e.content())->body;
} else { // 3
plainBody = e.plainBody();
}
@@ -282,7 +281,7 @@ QString SpectralRoom::eventToString(const RoomEvent& evt,
}
return plainBody;
},
[this](const RoomMemberEvent& e) {
[this](const RoomMemberEvent &e) {
// FIXME: Rewind to the name that was at the time of this event
auto subjectName = this->user(e.userId())->displayname();
// The below code assumes senderName output in AuthorRole
@@ -293,19 +292,15 @@ QString SpectralRoom::eventToString(const RoomEvent& evt,
case MembershipType::Join: {
if (e.repeatsState())
return tr("joined the room (repeated)");
if (!e.prevContent() ||
e.membership() != e.prevContent()->membership) {
return e.membership() == MembershipType::Invite
? tr("invited %1 to the room").arg(subjectName)
: tr("joined the room");
if (!e.prevContent() || e.membership() != e.prevContent()->membership) {
return e.membership() == MembershipType::Invite ? tr("invited %1 to the room").arg(subjectName) : tr("joined the room");
}
QString text{};
QString text {};
if (e.isRename()) {
if (e.displayName().isEmpty())
text = tr("cleared their display name");
else
text = tr("changed their display name to %1")
.arg(e.displayName().toHtmlEscaped());
text = tr("changed their display name to %1").arg(e.displayName().toHtmlEscaped());
}
if (e.isAvatarUpdate()) {
if (!text.isEmpty())
@@ -320,90 +315,61 @@ QString SpectralRoom::eventToString(const RoomEvent& evt,
return text;
}
case MembershipType::Leave:
if (e.prevContent() &&
e.prevContent()->membership == MembershipType::Invite) {
return (e.senderId() != e.userId())
? tr("withdrew %1's invitation").arg(subjectName)
: tr("rejected the invitation");
if (e.prevContent() && e.prevContent()->membership == MembershipType::Invite) {
return (e.senderId() != e.userId()) ? tr("withdrew %1's invitation").arg(subjectName) : tr("rejected the invitation");
}
if (e.prevContent() &&
e.prevContent()->membership == MembershipType::Ban) {
return (e.senderId() != e.userId())
? tr("unbanned %1").arg(subjectName)
: tr("self-unbanned");
if (e.prevContent() && e.prevContent()->membership == MembershipType::Ban) {
return (e.senderId() != e.userId()) ? tr("unbanned %1").arg(subjectName) : tr("self-unbanned");
}
return (e.senderId() != e.userId())
? tr("has put %1 out of the room: %2")
.arg(subjectName, e.contentJson()["reason"_ls]
.toString()
.toHtmlEscaped())
: tr("left the room");
return (e.senderId() != e.userId()) ? tr("has put %1 out of the room: %2").arg(subjectName, e.contentJson()["reason"_ls].toString().toHtmlEscaped()) : tr("left the room");
case MembershipType::Ban:
return (e.senderId() != e.userId())
? tr("banned %1 from the room: %2")
.arg(subjectName, e.contentJson()["reason"_ls]
.toString()
.toHtmlEscaped())
: tr("self-banned from the room");
return (e.senderId() != e.userId()) ? tr("banned %1 from the room: %2").arg(subjectName, e.contentJson()["reason"_ls].toString().toHtmlEscaped()) : tr("self-banned from the room");
case MembershipType::Knock:
return tr("knocked");
default:;
}
return tr("made something unknown");
},
[](const RoomCanonicalAliasEvent& e) {
return (e.alias().isEmpty())
? tr("cleared the room main alias")
: tr("set the room main alias to: %1").arg(e.alias());
[](const RoomCanonicalAliasEvent &e) {
return (e.alias().isEmpty()) ? tr("cleared the room main alias") : tr("set the room main alias to: %1").arg(e.alias());
},
[](const RoomNameEvent& e) {
return (e.name().isEmpty()) ? tr("cleared the room name")
: tr("set the room name to: %1")
.arg(e.name().toHtmlEscaped());
[](const RoomNameEvent &e) {
return (e.name().isEmpty()) ? tr("cleared the room name") : tr("set the room name to: %1").arg(e.name().toHtmlEscaped());
},
[prettyPrint](const RoomTopicEvent& e) {
return (e.topic().isEmpty())
? tr("cleared the topic")
: tr("set the topic to: %1")
.arg(prettyPrint ? Quotient::prettyPrint(e.topic())
: e.topic());
[prettyPrint](const RoomTopicEvent &e) {
return (e.topic().isEmpty()) ? tr("cleared the topic") : tr("set the topic to: %1").arg(prettyPrint ? Quotient::prettyPrint(e.topic()) : e.topic());
},
[](const RoomAvatarEvent&) { return tr("changed the room avatar"); },
[](const EncryptionEvent&) {
[](const RoomAvatarEvent &) {
return tr("changed the room avatar");
},
[](const EncryptionEvent &) {
return tr("activated End-to-End Encryption");
},
[](const RoomCreateEvent& e) {
return (e.isUpgrade() ? tr("upgraded the room to version %1")
: tr("created the room, version %1"))
.arg(e.version().isEmpty() ? "1" : e.version().toHtmlEscaped());
[](const RoomCreateEvent &e) {
return (e.isUpgrade() ? tr("upgraded the room to version %1") : tr("created the room, version %1")).arg(e.version().isEmpty() ? "1" : e.version().toHtmlEscaped());
},
[](const StateEventBase& e) {
[](const StateEventBase &e) {
// A small hack for state events from TWIM bot
return e.stateKey() == "twim"
? tr("updated the database", "TWIM bot updated the database")
: e.stateKey().isEmpty()
? tr("updated %1 state", "%1 - Matrix event type")
.arg(e.matrixType())
: tr("updated %1 state for %2",
"%1 - Matrix event type, %2 - state key")
.arg(e.matrixType(),
e.stateKey().toHtmlEscaped());
: e.stateKey().isEmpty() ? tr("updated %1 state", "%1 - Matrix event type").arg(e.matrixType()) : tr("updated %1 state for %2", "%1 - Matrix event type, %2 - state key").arg(e.matrixType(), e.stateKey().toHtmlEscaped());
},
tr("Unknown event"));
}
void SpectralRoom::changeAvatar(QUrl localFile) {
void SpectralRoom::changeAvatar(QUrl localFile)
{
const auto job = connection()->uploadFile(localFile.toLocalFile());
if (isJobRunning(job)) {
connect(job, &BaseJob::success, this, [this, job] {
connection()->callApi<SetRoomStateWithKeyJob>(
id(), "m.room.avatar", localUser()->id(), QJsonObject{{"url", job->contentUri()}});
connection()->callApi<SetRoomStateWithKeyJob>(id(), "m.room.avatar", localUser()->id(), QJsonObject {{"url", job->contentUri()}});
});
}
}
void SpectralRoom::addLocalAlias(const QString& alias) {
void SpectralRoom::addLocalAlias(const QString &alias)
{
auto a = aliases();
if (a.contains(alias))
return;
@@ -413,7 +379,8 @@ void SpectralRoom::addLocalAlias(const QString& alias) {
setLocalAliases(a);
}
void SpectralRoom::removeLocalAlias(const QString& alias) {
void SpectralRoom::removeLocalAlias(const QString &alias)
{
auto a = aliases();
if (!a.contains(alias))
return;
@@ -423,10 +390,10 @@ void SpectralRoom::removeLocalAlias(const QString& alias) {
setLocalAliases(a);
}
QString SpectralRoom::markdownToHTML(const QString& markdown) {
QString SpectralRoom::markdownToHTML(const QString &markdown)
{
const auto str = markdown.toUtf8();
char* tmp_buf =
cmark_markdown_to_html(str.constData(), str.size(), CMARK_OPT_DEFAULT);
char *tmp_buf = cmark_markdown_to_html(str.constData(), str.size(), CMARK_OPT_DEFAULT);
const std::string html(tmp_buf);
@@ -440,9 +407,8 @@ QString SpectralRoom::markdownToHTML(const QString& markdown) {
return result;
}
void SpectralRoom::postArbitaryMessage(const QString& text,
MessageEventType type,
const QString& replyEventId) {
void SpectralRoom::postArbitaryMessage(const QString &text, MessageEventType type, const QString &replyEventId)
{
const auto parsedHTML = markdownToHTML(text);
const bool isRichText = Qt::mightBeRichText(parsedHTML);
@@ -453,7 +419,8 @@ void SpectralRoom::postArbitaryMessage(const QString& text,
}
}
QString msgTypeToString(MessageEventType msgType) {
QString msgTypeToString(MessageEventType msgType)
{
switch (msgType) {
case MessageEventType::Text:
return "m.text";
@@ -476,16 +443,15 @@ QString msgTypeToString(MessageEventType msgType) {
}
}
void SpectralRoom::postPlainMessage(const QString& text,
MessageEventType type,
const QString& replyEventId) {
void SpectralRoom::postPlainMessage(const QString &text, MessageEventType type, const QString &replyEventId)
{
bool isReply = !replyEventId.isEmpty();
const auto replyIt = findInTimeline(replyEventId);
if (replyIt == timelineEdge())
isReply = false;
if (isReply) {
const auto& replyEvt = **replyIt;
const auto &replyEvt = **replyIt;
// clang-format off
QJsonObject json{
@@ -521,17 +487,15 @@ void SpectralRoom::postPlainMessage(const QString& text,
Room::postMessage(text, type);
}
void SpectralRoom::postHtmlMessage(const QString& text,
const QString& html,
MessageEventType type,
const QString& replyEventId) {
void SpectralRoom::postHtmlMessage(const QString &text, const QString &html, MessageEventType type, const QString &replyEventId)
{
bool isReply = !replyEventId.isEmpty();
const auto replyIt = findInTimeline(replyEventId);
if (replyIt == timelineEdge())
isReply = false;
if (isReply) {
const auto& replyEvt = **replyIt;
const auto &replyEvt = **replyIt;
// clang-format off
QJsonObject json{
@@ -567,8 +531,8 @@ void SpectralRoom::postHtmlMessage(const QString& text,
Room::postHtmlMessage(text, html, type);
}
void SpectralRoom::toggleReaction(const QString& eventId,
const QString& reaction) {
void SpectralRoom::toggleReaction(const QString &eventId, const QString &reaction)
{
if (eventId.isEmpty() || reaction.isEmpty())
return;
@@ -576,13 +540,13 @@ void SpectralRoom::toggleReaction(const QString& eventId,
if (eventIt == timelineEdge())
return;
const auto& evt = **eventIt;
const auto &evt = **eventIt;
QStringList redactEventIds; // What if there are multiple reaction events?
const auto& annotations = relatedEvents(evt, EventRelation::Annotation());
const auto &annotations = relatedEvents(evt, EventRelation::Annotation());
if (!annotations.isEmpty()) {
for (const auto& a : annotations) {
for (const auto &a : annotations) {
if (auto e = eventCast<const ReactionEvent>(a)) {
if (e->relation().key != reaction)
continue;
@@ -596,7 +560,7 @@ void SpectralRoom::toggleReaction(const QString& eventId,
}
if (!redactEventIds.isEmpty()) {
for (const auto& redactEventId : redactEventIds) {
for (const auto &redactEventId : redactEventIds) {
redactEvent(redactEventId);
}
} else {
@@ -604,7 +568,8 @@ void SpectralRoom::toggleReaction(const QString& eventId,
}
}
bool SpectralRoom::containsUser(QString userID) const {
bool SpectralRoom::containsUser(QString userID) const
{
auto u = Room::user(userID);
if (!u)
@@ -613,7 +578,8 @@ bool SpectralRoom::containsUser(QString userID) const {
return Room::memberJoinState(u) != JoinState::Leave;
}
bool SpectralRoom::canSendEvent(const QString& eventType) const {
bool SpectralRoom::canSendEvent(const QString &eventType) const
{
auto plEvent = getCurrentState<RoomPowerLevelsEvent>();
auto pl = plEvent->powerLevelForEvent(eventType);
auto currentPl = plEvent->powerLevelForUser(localUser()->id());
@@ -621,7 +587,8 @@ bool SpectralRoom::canSendEvent(const QString& eventType) const {
return currentPl >= pl;
}
bool SpectralRoom::canSendState(const QString& eventType) const {
bool SpectralRoom::canSendState(const QString &eventType) const
{
auto plEvent = getCurrentState<RoomPowerLevelsEvent>();
auto pl = plEvent->powerLevelForState(eventType);
auto currentPl = plEvent->powerLevelForUser(localUser()->id());

View File

@@ -18,31 +18,31 @@
using namespace Quotient;
class SpectralRoom : public Room {
class SpectralRoom : public Room
{
Q_OBJECT
Q_PROPERTY(QVariantList usersTyping READ getUsersTyping NOTIFY typingChanged)
Q_PROPERTY(QString cachedInput MEMBER m_cachedInput NOTIFY cachedInputChanged)
Q_PROPERTY(bool hasFileUploading READ hasFileUploading WRITE
setHasFileUploading NOTIFY hasFileUploadingChanged)
Q_PROPERTY(int fileUploadingProgress READ fileUploadingProgress NOTIFY
fileUploadingProgressChanged)
Q_PROPERTY(QString avatarMediaId READ avatarMediaId NOTIFY avatarChanged
STORED false)
Q_PROPERTY(bool hasFileUploading READ hasFileUploading WRITE setHasFileUploading NOTIFY hasFileUploadingChanged)
Q_PROPERTY(int fileUploadingProgress READ fileUploadingProgress NOTIFY fileUploadingProgressChanged)
Q_PROPERTY(QString avatarMediaId READ avatarMediaId NOTIFY avatarChanged STORED false)
public:
explicit SpectralRoom(Connection* connection,
QString roomId,
JoinState joinState = {});
public:
explicit SpectralRoom(Connection *connection, QString roomId, JoinState joinState = {});
QVariantList getUsersTyping() const;
QString lastEvent() const;
bool isEventHighlighted(const Quotient::RoomEvent* e) const;
bool isEventHighlighted(const Quotient::RoomEvent *e) const;
QDateTime lastActiveTime() const;
bool hasFileUploading() const { return m_hasFileUploading; }
void setHasFileUploading(bool value) {
bool hasFileUploading() const
{
return m_hasFileUploading;
}
void setHasFileUploading(bool value)
{
if (value == m_hasFileUploading) {
return;
}
@@ -50,8 +50,12 @@ class SpectralRoom : public Room {
emit hasFileUploadingChanged();
}
int fileUploadingProgress() const { return m_fileUploadingProgress; }
void setFileUploadingProgress(int value) {
int fileUploadingProgress() const
{
return m_fileUploadingProgress;
}
void setFileUploadingProgress(int value)
{
if (m_fileUploadingProgress == value) {
return;
}
@@ -63,65 +67,56 @@ class SpectralRoom : public Room {
Q_INVOKABLE int savedBottomVisibleIndex() const;
Q_INVOKABLE void saveViewport(int topIndex, int bottomIndex);
Q_INVOKABLE QVariantList getUsers(const QString& keyword) const;
Q_INVOKABLE QVariantList getUsers(const QString &keyword) const;
Q_INVOKABLE QUrl urlToMxcUrl(QUrl mxcUrl);
QString avatarMediaId() const;
QString eventToString(const RoomEvent& evt,
Qt::TextFormat format = Qt::PlainText,
bool removeReply = true) const;
QString eventToString(const RoomEvent &evt, Qt::TextFormat format = Qt::PlainText, bool removeReply = true) const;
Q_INVOKABLE bool containsUser(QString userID) const;
Q_INVOKABLE bool canSendEvent(const QString& eventType) const;
Q_INVOKABLE bool canSendState(const QString& eventType) const;
Q_INVOKABLE bool canSendEvent(const QString &eventType) const;
Q_INVOKABLE bool canSendState(const QString &eventType) const;
private:
private:
QString m_cachedInput;
QSet<const Quotient::RoomEvent*> highlights;
QSet<const Quotient::RoomEvent *> highlights;
bool m_hasFileUploading = false;
int m_fileUploadingProgress = 0;
void checkForHighlights(const Quotient::TimelineItem& ti);
void checkForHighlights(const Quotient::TimelineItem &ti);
void onAddNewTimelineEvents(timeline_iter_t from) override;
void onAddHistoricalTimelineEvents(rev_iter_t from) override;
void onRedaction(const RoomEvent& prevEvent, const RoomEvent& after) override;
void onRedaction(const RoomEvent &prevEvent, const RoomEvent &after) override;
static QString markdownToHTML(const QString& plaintext);
static QString markdownToHTML(const QString &plaintext);
private slots:
private slots:
void countChanged();
signals:
signals:
void cachedInputChanged();
void busyChanged();
void hasFileUploadingChanged();
void fileUploadingProgressChanged();
void backgroundChanged();
public slots:
void uploadFile(const QUrl& url, const QString& body = "");
public slots:
void uploadFile(const QUrl &url, const QString &body = "");
void acceptInvitation();
void forget();
void sendTypingNotification(bool isTyping);
void postArbitaryMessage(const QString& text,
MessageEventType type = MessageEventType::Text,
const QString& replyEventId = "");
void postPlainMessage(const QString& text,
MessageEventType type = MessageEventType::Text,
const QString& replyEventId = "");
void postHtmlMessage(const QString& text,
const QString& html,
MessageEventType type = MessageEventType::Text,
const QString& replyEventId = "");
void postArbitaryMessage(const QString &text, MessageEventType type = MessageEventType::Text, const QString &replyEventId = "");
void postPlainMessage(const QString &text, MessageEventType type = MessageEventType::Text, const QString &replyEventId = "");
void postHtmlMessage(const QString &text, const QString &html, MessageEventType type = MessageEventType::Text, const QString &replyEventId = "");
void changeAvatar(QUrl localFile);
void addLocalAlias(const QString& alias);
void removeLocalAlias(const QString& alias);
void toggleReaction(const QString& eventId, const QString& reaction);
void addLocalAlias(const QString &alias);
void removeLocalAlias(const QString &alias);
void toggleReaction(const QString &eventId, const QString &reaction);
};
#endif // SpectralRoom_H

View File

@@ -1,5 +1,6 @@
#include "spectraluser.h"
QColor SpectralUser::color() {
QColor SpectralUser::color()
{
return QColor::fromHslF(hueF(), 0.7, 0.5, 1);
}

View File

@@ -8,12 +8,15 @@
using namespace Quotient;
class SpectralUser : public User {
class SpectralUser : public User
{
Q_OBJECT
Q_PROPERTY(QColor color READ color CONSTANT)
public:
SpectralUser(QString userId, Connection* connection)
: User(userId, connection) {}
public:
SpectralUser(QString userId, Connection *connection)
: User(userId, connection)
{
}
QColor color();
};

View File

@@ -12,15 +12,14 @@
#include <QtMacExtras>
#endif
MsgCountComposedIcon::MsgCountComposedIcon(const QString& filename)
: QIconEngine() {
MsgCountComposedIcon::MsgCountComposedIcon(const QString &filename)
: QIconEngine()
{
icon_ = QIcon(filename);
}
void MsgCountComposedIcon::paint(QPainter* painter,
const QRect& rect,
QIcon::Mode mode,
QIcon::State state) {
void MsgCountComposedIcon::paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state)
{
painter->setRenderHint(QPainter::TextAntialiasing);
painter->setRenderHint(QPainter::SmoothPixmapTransform);
painter->setRenderHint(QPainter::Antialiasing);
@@ -41,8 +40,7 @@ void MsgCountComposedIcon::paint(QPainter* painter,
painter->setPen(Qt::NoPen);
painter->setFont(QFont("Open Sans", 8, QFont::Black));
QRectF bubble(rect.width() - BubbleDiameter, rect.height() - BubbleDiameter,
BubbleDiameter, BubbleDiameter);
QRectF bubble(rect.width() - BubbleDiameter, rect.height() - BubbleDiameter, BubbleDiameter, BubbleDiameter);
painter->drawEllipse(bubble);
painter->setPen(QPen(textColor));
painter->setBrush(Qt::NoBrush);
@@ -55,12 +53,13 @@ void MsgCountComposedIcon::paint(QPainter* painter,
}
}
QIconEngine* MsgCountComposedIcon::clone() const {
QIconEngine *MsgCountComposedIcon::clone() const
{
return new MsgCountComposedIcon(*this);
}
QList<QSize> MsgCountComposedIcon::availableSizes(QIcon::Mode mode,
QIcon::State state) const {
QList<QSize> MsgCountComposedIcon::availableSizes(QIcon::Mode mode, QIcon::State state) const
{
Q_UNUSED(mode)
Q_UNUSED(state)
QList<QSize> sizes;
@@ -73,9 +72,8 @@ QList<QSize> MsgCountComposedIcon::availableSizes(QIcon::Mode mode,
return sizes;
}
QPixmap MsgCountComposedIcon::pixmap(const QSize& size,
QIcon::Mode mode,
QIcon::State state) {
QPixmap MsgCountComposedIcon::pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state)
{
QImage img(size, QImage::Format_ARGB32);
img.fill(qRgba(0, 0, 0, 0));
QPixmap result = QPixmap::fromImage(img, Qt::NoFormatConversion);
@@ -86,8 +84,10 @@ QPixmap MsgCountComposedIcon::pixmap(const QSize& size,
return result;
}
TrayIcon::TrayIcon(QObject* parent) : QSystemTrayIcon(parent) {
QMenu* menu = new QMenu();
TrayIcon::TrayIcon(QObject *parent)
: QSystemTrayIcon(parent)
{
QMenu *menu = new QMenu();
viewAction_ = new QAction(tr("Show"), parent);
quitAction_ = new QAction(tr("Quit"), parent);
@@ -100,7 +100,8 @@ TrayIcon::TrayIcon(QObject* parent) : QSystemTrayIcon(parent) {
setContextMenu(menu);
}
void TrayIcon::setNotificationCount(int count) {
void TrayIcon::setNotificationCount(int count)
{
m_notificationCount = count;
// Use the native badge counter in MacOS.
#if defined(Q_OS_MAC)
@@ -117,8 +118,7 @@ void TrayIcon::setNotificationCount(int count) {
return;
// Custom drawing on Linux.
MsgCountComposedIcon* tmp =
static_cast<MsgCountComposedIcon*>(icon_->clone());
MsgCountComposedIcon *tmp = static_cast<MsgCountComposedIcon *>(icon_->clone());
tmp->msgCount = count;
setIcon(QIcon(tmp));
@@ -128,12 +128,12 @@ void TrayIcon::setNotificationCount(int count) {
emit notificationCountChanged();
}
void TrayIcon::setIsOnline(bool online) {
void TrayIcon::setIsOnline(bool online)
{
m_isOnline = online;
#if defined(Q_OS_MAC)
if (online) {
auto labelText =
m_notificationCount == 0 ? "" : QString::number(m_notificationCount);
auto labelText = m_notificationCount == 0 ? "" : QString::number(m_notificationCount);
if (labelText == QtMac::badgeLabelText())
return;
@@ -154,8 +154,7 @@ void TrayIcon::setIsOnline(bool online) {
return;
// Custom drawing on Linux.
MsgCountComposedIcon* tmp =
static_cast<MsgCountComposedIcon*>(icon_->clone());
MsgCountComposedIcon *tmp = static_cast<MsgCountComposedIcon *>(icon_->clone());
tmp->isOnline = online;
setIcon(QIcon(tmp));
@@ -165,7 +164,8 @@ void TrayIcon::setIsOnline(bool online) {
emit isOnlineChanged();
}
void TrayIcon::setIconSource(const QString& source) {
void TrayIcon::setIconSource(const QString &source)
{
m_iconSource = source;
#if defined(Q_OS_MAC) || defined(Q_OS_WIN)
setIcon(QIcon(source));

View File

@@ -10,65 +10,68 @@
#include <QRect>
#include <QSystemTrayIcon>
class MsgCountComposedIcon : public QIconEngine {
public:
MsgCountComposedIcon(const QString& filename);
class MsgCountComposedIcon : public QIconEngine
{
public:
MsgCountComposedIcon(const QString &filename);
virtual void paint(QPainter* p,
const QRect& rect,
QIcon::Mode mode,
QIcon::State state);
virtual QIconEngine* clone() const;
virtual QList<QSize> availableSizes(QIcon::Mode mode,
QIcon::State state) const;
virtual QPixmap pixmap(const QSize& size,
QIcon::Mode mode,
QIcon::State state);
virtual void paint(QPainter *p, const QRect &rect, QIcon::Mode mode, QIcon::State state);
virtual QIconEngine *clone() const;
virtual QList<QSize> availableSizes(QIcon::Mode mode, QIcon::State state) const;
virtual QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state);
int msgCount = 0;
bool isOnline = true; // Default to false?
private:
private:
const int BubbleDiameter = 14;
QIcon icon_;
};
class TrayIcon : public QSystemTrayIcon {
class TrayIcon : public QSystemTrayIcon
{
Q_OBJECT
Q_PROPERTY(QString iconSource READ iconSource WRITE setIconSource NOTIFY
iconSourceChanged)
Q_PROPERTY(int notificationCount READ notificationCount WRITE
setNotificationCount NOTIFY notificationCountChanged)
Q_PROPERTY(QString iconSource READ iconSource WRITE setIconSource NOTIFY iconSourceChanged)
Q_PROPERTY(int notificationCount READ notificationCount WRITE setNotificationCount NOTIFY notificationCountChanged)
Q_PROPERTY(bool isOnline READ isOnline WRITE setIsOnline NOTIFY isOnlineChanged)
public:
TrayIcon(QObject* parent = nullptr);
public:
TrayIcon(QObject *parent = nullptr);
QString iconSource() { return m_iconSource; }
void setIconSource(const QString& source);
QString iconSource()
{
return m_iconSource;
}
void setIconSource(const QString &source);
int notificationCount() { return m_notificationCount; }
int notificationCount()
{
return m_notificationCount;
}
void setNotificationCount(int count);
bool isOnline() { return m_isOnline; }
bool isOnline()
{
return m_isOnline;
}
void setIsOnline(bool online);
signals:
signals:
void notificationCountChanged();
void iconSourceChanged();
void isOnlineChanged();
void showWindow();
private:
private:
QString m_iconSource;
int m_notificationCount = 0;
bool m_isOnline = true;
QAction* viewAction_;
QAction* quitAction_;
QAction *viewAction_;
QAction *quitAction_;
MsgCountComposedIcon* icon_ = nullptr;
MsgCountComposedIcon *icon_ = nullptr;
};
#endif // TRAYICON_H

View File

@@ -1,9 +1,12 @@
#include "userdirectorylistmodel.h"
UserDirectoryListModel::UserDirectoryListModel(QObject* parent)
: QAbstractListModel(parent) {}
UserDirectoryListModel::UserDirectoryListModel(QObject *parent)
: QAbstractListModel(parent)
{
}
void UserDirectoryListModel::setConnection(Connection* conn) {
void UserDirectoryListModel::setConnection(Connection *conn)
{
if (m_connection == conn)
return;
@@ -30,7 +33,8 @@ void UserDirectoryListModel::setConnection(Connection* conn) {
emit limitedChanged();
}
void UserDirectoryListModel::setKeyword(const QString& value) {
void UserDirectoryListModel::setKeyword(const QString &value)
{
if (m_keyword == value)
return;
@@ -48,7 +52,8 @@ void UserDirectoryListModel::setKeyword(const QString& value) {
emit limitedChanged();
}
void UserDirectoryListModel::search(int count) {
void UserDirectoryListModel::search(int count)
{
if (count < 1)
return;
@@ -83,8 +88,8 @@ void UserDirectoryListModel::search(int count) {
});
}
QVariant UserDirectoryListModel::data(const QModelIndex& index,
int role) const {
QVariant UserDirectoryListModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
@@ -137,7 +142,8 @@ QVariant UserDirectoryListModel::data(const QModelIndex& index,
return {};
}
QHash<int, QByteArray> UserDirectoryListModel::roleNames() const {
QHash<int, QByteArray> UserDirectoryListModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[NameRole] = "name";
@@ -148,7 +154,8 @@ QHash<int, QByteArray> UserDirectoryListModel::roleNames() const {
return roles;
}
int UserDirectoryListModel::rowCount(const QModelIndex& parent) const {
int UserDirectoryListModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;

View File

@@ -9,15 +9,14 @@
using namespace Quotient;
class UserDirectoryListModel : public QAbstractListModel {
class UserDirectoryListModel : public QAbstractListModel
{
Q_OBJECT
Q_PROPERTY(Connection* connection READ connection WRITE setConnection NOTIFY
connectionChanged)
Q_PROPERTY(
QString keyword READ keyword WRITE setKeyword NOTIFY keywordChanged)
Q_PROPERTY(Connection *connection READ connection WRITE setConnection NOTIFY connectionChanged)
Q_PROPERTY(QString keyword READ keyword WRITE setKeyword NOTIFY keywordChanged)
Q_PROPERTY(bool limited READ limited NOTIFY limitedChanged)
public:
public:
enum EventRoles {
NameRole = Qt::DisplayRole + 1,
AvatarRole,
@@ -25,25 +24,34 @@ class UserDirectoryListModel : public QAbstractListModel {
DirectChatsRole,
};
UserDirectoryListModel(QObject* parent = nullptr);
UserDirectoryListModel(QObject *parent = nullptr);
QVariant data(const QModelIndex& index, int role = NameRole) const override;
int rowCount(const QModelIndex& parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = NameRole) const override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QHash<int, QByteArray> roleNames() const override;
Connection* connection() const { return m_connection; }
void setConnection(Connection* value);
Connection *connection() const
{
return m_connection;
}
void setConnection(Connection *value);
QString keyword() const { return m_keyword; }
void setKeyword(const QString& value);
QString keyword() const
{
return m_keyword;
}
void setKeyword(const QString &value);
bool limited() const { return m_limited; }
bool limited() const
{
return m_limited;
}
Q_INVOKABLE void search(int count = 50);
private:
Connection* m_connection = nullptr;
private:
Connection *m_connection = nullptr;
QString m_keyword;
bool m_limited = false;
@@ -51,9 +59,9 @@ class UserDirectoryListModel : public QAbstractListModel {
QVector<SearchUserDirectoryJob::User> users;
SearchUserDirectoryJob* job = nullptr;
SearchUserDirectoryJob *job = nullptr;
signals:
signals:
void connectionChanged();
void keywordChanged();
void limitedChanged();

View File

@@ -12,10 +12,14 @@
#include "spectraluser.h"
UserListModel::UserListModel(QObject* parent)
: QAbstractListModel(parent), m_currentRoom(nullptr) {}
UserListModel::UserListModel(QObject *parent)
: QAbstractListModel(parent)
, m_currentRoom(nullptr)
{
}
void UserListModel::setRoom(Quotient::Room* room) {
void UserListModel::setRoom(Quotient::Room *room)
{
if (m_currentRoom == room)
return;
@@ -24,47 +28,48 @@ void UserListModel::setRoom(Quotient::Room* room) {
if (m_currentRoom) {
m_currentRoom->disconnect(this);
// m_currentRoom->connection()->disconnect(this);
for (User* user : m_users)
for (User *user : m_users)
user->disconnect(this);
m_users.clear();
}
m_currentRoom = room;
if (m_currentRoom) {
connect(m_currentRoom, &Room::userAdded, this, &UserListModel::userAdded);
connect(m_currentRoom, &Room::userRemoved, this,
&UserListModel::userRemoved);
connect(m_currentRoom, &Room::memberAboutToRename, this,
&UserListModel::userRemoved);
connect(m_currentRoom, &Room::memberRenamed, this,
&UserListModel::userAdded);
connect(m_currentRoom, &Room::userRemoved, this, &UserListModel::userRemoved);
connect(m_currentRoom, &Room::memberAboutToRename, this, &UserListModel::userRemoved);
connect(m_currentRoom, &Room::memberRenamed, this, &UserListModel::userAdded);
{
m_users = m_currentRoom->users();
std::sort(m_users.begin(), m_users.end(), room->memberSorter());
}
for (User* user : m_users) {
connect(user, &User::defaultAvatarChanged, this, [user, this](){avatarChanged(user);});
for (User *user : m_users) {
connect(user, &User::defaultAvatarChanged, this, [user, this]() {
avatarChanged(user);
});
}
connect(m_currentRoom->connection(), &Connection::loggedOut, this,
[=] { setRoom(nullptr); });
connect(m_currentRoom->connection(), &Connection::loggedOut, this, [=] {
setRoom(nullptr);
});
qDebug() << m_users.count() << "user(s) in the room";
}
endResetModel();
emit roomChanged();
}
Quotient::User* UserListModel::userAt(QModelIndex index) const {
Quotient::User *UserListModel::userAt(QModelIndex index) const
{
if (index.row() < 0 || index.row() >= m_users.size())
return nullptr;
return m_users.at(index.row());
}
QVariant UserListModel::data(const QModelIndex& index, int role) const {
QVariant UserListModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (index.row() >= m_users.count()) {
qDebug()
<< "UserListModel, something's wrong: index.row() >= m_users.count()";
qDebug() << "UserListModel, something's wrong: index.row() >= m_users.count()";
return {};
}
auto user = m_users.at(index.row());
@@ -122,22 +127,27 @@ QVariant UserListModel::data(const QModelIndex& index, int role) const {
return {};
}
int UserListModel::rowCount(const QModelIndex& parent) const {
int UserListModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return m_users.count();
}
void UserListModel::userAdded(Quotient::User* user) {
void UserListModel::userAdded(Quotient::User *user)
{
auto pos = findUserPos(user);
beginInsertRows(QModelIndex(), pos, pos);
m_users.insert(pos, user);
endInsertRows();
connect(user, &Quotient::User::defaultAvatarChanged, this, [user, this](){avatarChanged(user);});
connect(user, &Quotient::User::defaultAvatarChanged, this, [user, this]() {
avatarChanged(user);
});
}
void UserListModel::userRemoved(Quotient::User* user) {
void UserListModel::userRemoved(Quotient::User *user)
{
auto pos = findUserPos(user);
if (pos != m_users.size()) {
beginRemoveRows(QModelIndex(), pos, pos);
@@ -148,7 +158,8 @@ void UserListModel::userRemoved(Quotient::User* user) {
qWarning() << "Trying to remove a room member not in the user list";
}
void UserListModel::refresh(Quotient::User* user, QVector<int> roles) {
void UserListModel::refresh(Quotient::User *user, QVector<int> roles)
{
auto pos = findUserPos(user);
if (pos != m_users.size())
emit dataChanged(index(pos), index(pos), roles);
@@ -156,19 +167,23 @@ void UserListModel::refresh(Quotient::User* user, QVector<int> roles) {
qWarning() << "Trying to access a room member not in the user list";
}
void UserListModel::avatarChanged(Quotient::User* user) {
void UserListModel::avatarChanged(Quotient::User *user)
{
refresh(user, {AvatarRole});
}
int UserListModel::findUserPos(User* user) const {
int UserListModel::findUserPos(User *user) const
{
return findUserPos(m_currentRoom->roomMembername(user));
}
int UserListModel::findUserPos(const QString& username) const {
int UserListModel::findUserPos(const QString &username) const
{
return m_currentRoom->memberSorter().lowerBoundIndex(m_users, username);
}
QHash<int, QByteArray> UserListModel::roleNames() const {
QHash<int, QByteArray> UserListModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[NameRole] = "name";

View File

@@ -6,16 +6,18 @@
#include <QObject>
#include <QtCore/QAbstractListModel>
namespace Quotient {
namespace Quotient
{
class Connection;
class Room;
class User;
} // namespace Quotient
class UserType : public QObject {
class UserType : public QObject
{
Q_OBJECT
public:
public:
enum Types {
Owner = 1,
Admin,
@@ -26,11 +28,11 @@ class UserType : public QObject {
Q_ENUMS(Types)
};
class UserListModel : public QAbstractListModel {
class UserListModel : public QAbstractListModel
{
Q_OBJECT
Q_PROPERTY(
Quotient::Room* room READ room WRITE setRoom NOTIFY roomChanged)
public:
Q_PROPERTY(Quotient::Room *room READ room WRITE setRoom NOTIFY roomChanged)
public:
enum EventRoles {
NameRole = Qt::UserRole + 1,
UserIDRole,
@@ -39,32 +41,35 @@ class UserListModel : public QAbstractListModel {
PermRole,
};
UserListModel(QObject* parent = nullptr);
UserListModel(QObject *parent = nullptr);
Quotient::Room* room() const { return m_currentRoom; }
void setRoom(Quotient::Room* room);
Quotient::User* userAt(QModelIndex index) const;
Quotient::Room *room() const
{
return m_currentRoom;
}
void setRoom(Quotient::Room *room);
Quotient::User *userAt(QModelIndex index) const;
QVariant data(const QModelIndex& index, int role = NameRole) const override;
int rowCount(const QModelIndex& parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = NameRole) const override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QHash<int, QByteArray> roleNames() const override;
signals:
signals:
void roomChanged();
private slots:
void userAdded(Quotient::User* user);
void userRemoved(Quotient::User* user);
void refresh(Quotient::User* user, QVector<int> roles = {});
void avatarChanged(Quotient::User* user);
private slots:
void userAdded(Quotient::User *user);
void userRemoved(Quotient::User *user);
void refresh(Quotient::User *user, QVector<int> roles = {});
void avatarChanged(Quotient::User *user);
private:
Quotient::Room* m_currentRoom;
QList<Quotient::User*> m_users;
private:
Quotient::Room *m_currentRoom;
QList<Quotient::User *> m_users;
int findUserPos(Quotient::User* user) const;
int findUserPos(const QString& username) const;
int findUserPos(Quotient::User *user) const;
int findUserPos(const QString &username) const;
};
#endif // USERLISTMODEL_H

View File

@@ -13,18 +13,13 @@
#include <events/roommemberevent.h>
#include <events/simplestateevents.h>
namespace utils {
static const QRegularExpression removeReplyRegex{
"> <.*?>.*?\\n\\n", QRegularExpression::DotMatchesEverythingOption};
static const QRegularExpression removeRichReplyRegex{
"<mx-reply>.*?</mx-reply>", QRegularExpression::DotMatchesEverythingOption};
static const QRegularExpression codePillRegExp{
"<pre><code[^>]*>(.*?)</code></pre>", QRegularExpression::DotMatchesEverythingOption};
static const QRegularExpression userPillRegExp{
"<a href=\"https://matrix.to/#/@.*?:.*?\">(.*?)</a>",
QRegularExpression::DotMatchesEverythingOption};
static const QRegularExpression strikethroughRegExp{
"<del>(.*?)</del>", QRegularExpression::DotMatchesEverythingOption};
namespace utils
{
static const QRegularExpression removeReplyRegex {"> <.*?>.*?\\n\\n", QRegularExpression::DotMatchesEverythingOption};
static const QRegularExpression removeRichReplyRegex {"<mx-reply>.*?</mx-reply>", QRegularExpression::DotMatchesEverythingOption};
static const QRegularExpression codePillRegExp {"<pre><code[^>]*>(.*?)</code></pre>", QRegularExpression::DotMatchesEverythingOption};
static const QRegularExpression userPillRegExp {"<a href=\"https://matrix.to/#/@.*?:.*?\">(.*?)</a>", QRegularExpression::DotMatchesEverythingOption};
static const QRegularExpression strikethroughRegExp {"<del>(.*?)</del>", QRegularExpression::DotMatchesEverythingOption};
} // namespace utils
#endif