Apply Clang Format
This commit is contained in:
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1,3 +1,3 @@
|
||||
build
|
||||
|
||||
.DS_Store
|
||||
.clang-format
|
||||
.DS_Store
|
||||
|
||||
@@ -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})
|
||||
|
||||
@@ -7,86 +7,88 @@
|
||||
|
||||
#include "room.h"
|
||||
|
||||
AccountListModel::AccountListModel(QObject* parent)
|
||||
: QAbstractListModel(parent) {}
|
||||
|
||||
void AccountListModel::setController(Controller* value) {
|
||||
if (m_controller == value) {
|
||||
return;
|
||||
}
|
||||
|
||||
beginResetModel();
|
||||
|
||||
m_connections.clear();
|
||||
m_controller = value;
|
||||
m_connections += m_controller->connections();
|
||||
|
||||
connect(m_controller, &Controller::connectionAdded, this,
|
||||
[=](Connection* conn) {
|
||||
if (!conn) {
|
||||
return;
|
||||
}
|
||||
beginInsertRows(QModelIndex(), m_connections.count(),
|
||||
m_connections.count());
|
||||
m_connections.append(conn);
|
||||
endInsertRows();
|
||||
});
|
||||
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);
|
||||
if (it == m_connections.end())
|
||||
return; // Already deleted, nothing to do
|
||||
const int row = it - m_connections.begin();
|
||||
beginRemoveRows(QModelIndex(), row, row);
|
||||
m_connections.erase(it);
|
||||
endRemoveRows();
|
||||
});
|
||||
emit controllerChanged();
|
||||
AccountListModel::AccountListModel(QObject *parent)
|
||||
: QAbstractListModel(parent)
|
||||
{
|
||||
}
|
||||
|
||||
QVariant AccountListModel::data(const QModelIndex& index, int role) const {
|
||||
if (!index.isValid()) {
|
||||
void AccountListModel::setController(Controller *value)
|
||||
{
|
||||
if (m_controller == value) {
|
||||
return;
|
||||
}
|
||||
|
||||
beginResetModel();
|
||||
|
||||
m_connections.clear();
|
||||
m_controller = value;
|
||||
m_connections += m_controller->connections();
|
||||
|
||||
connect(m_controller, &Controller::connectionAdded, this, [=](Connection *conn) {
|
||||
if (!conn) {
|
||||
return;
|
||||
}
|
||||
beginInsertRows(QModelIndex(), m_connections.count(), m_connections.count());
|
||||
m_connections.append(conn);
|
||||
endInsertRows();
|
||||
});
|
||||
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);
|
||||
if (it == m_connections.end())
|
||||
return; // Already deleted, nothing to do
|
||||
const int row = it - m_connections.begin();
|
||||
beginRemoveRows(QModelIndex(), row, row);
|
||||
m_connections.erase(it);
|
||||
endRemoveRows();
|
||||
});
|
||||
emit controllerChanged();
|
||||
}
|
||||
|
||||
QVariant AccountListModel::data(const QModelIndex &index, int role) const
|
||||
{
|
||||
if (!index.isValid()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
if (index.row() >= m_connections.count()) {
|
||||
qDebug() << "AccountListModel, something's wrong: index.row() >= "
|
||||
"m_users.count()";
|
||||
return {};
|
||||
}
|
||||
|
||||
auto m_connection = m_connections.at(index.row());
|
||||
|
||||
if (role == UserRole) {
|
||||
return QVariant::fromValue(m_connection->user());
|
||||
}
|
||||
if (role == ConnectionRole) {
|
||||
return QVariant::fromValue(m_connection);
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
if (index.row() >= m_connections.count()) {
|
||||
qDebug() << "AccountListModel, something's wrong: index.row() >= "
|
||||
"m_users.count()";
|
||||
return {};
|
||||
}
|
||||
|
||||
auto m_connection = m_connections.at(index.row());
|
||||
|
||||
if (role == UserRole) {
|
||||
return QVariant::fromValue(m_connection->user());
|
||||
}
|
||||
if (role == ConnectionRole) {
|
||||
return QVariant::fromValue(m_connection);
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
int AccountListModel::rowCount(const QModelIndex& parent) const {
|
||||
if (parent.isValid()) {
|
||||
return 0;
|
||||
}
|
||||
int AccountListModel::rowCount(const QModelIndex &parent) const
|
||||
{
|
||||
if (parent.isValid()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return m_connections.count();
|
||||
return m_connections.count();
|
||||
}
|
||||
|
||||
QHash<int, QByteArray> AccountListModel::roleNames() const {
|
||||
QHash<int, QByteArray> roles;
|
||||
QHash<int, QByteArray> AccountListModel::roleNames() const
|
||||
{
|
||||
QHash<int, QByteArray> roles;
|
||||
|
||||
roles[UserRole] = "user";
|
||||
roles[ConnectionRole] = "connection";
|
||||
roles[UserRole] = "user";
|
||||
roles[ConnectionRole] = "connection";
|
||||
|
||||
return roles;
|
||||
return roles;
|
||||
}
|
||||
|
||||
@@ -11,29 +11,32 @@
|
||||
#include <QAbstractListModel>
|
||||
#include <QObject>
|
||||
|
||||
class AccountListModel : public QAbstractListModel {
|
||||
Q_OBJECT
|
||||
Q_PROPERTY(Controller* controller READ controller WRITE setController NOTIFY
|
||||
controllerChanged)
|
||||
public:
|
||||
enum EventRoles { UserRole = Qt::UserRole + 1, ConnectionRole };
|
||||
class AccountListModel : public QAbstractListModel
|
||||
{
|
||||
Q_OBJECT
|
||||
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;
|
||||
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:
|
||||
void controllerChanged();
|
||||
signals:
|
||||
void controllerChanged();
|
||||
};
|
||||
|
||||
#endif // ACCOUNTLISTMODEL_H
|
||||
#endif // ACCOUNTLISTMODEL_H
|
||||
|
||||
@@ -37,362 +37,355 @@
|
||||
#include "spectraluser.h"
|
||||
#include "utils.h"
|
||||
|
||||
Controller::Controller(QObject* parent) : QObject(parent) {
|
||||
QApplication::setQuitOnLastWindowClosed(false);
|
||||
Controller::Controller(QObject *parent)
|
||||
: QObject(parent)
|
||||
{
|
||||
QApplication::setQuitOnLastWindowClosed(false);
|
||||
|
||||
Connection::setRoomType<SpectralRoom>();
|
||||
Connection::setUserType<SpectralUser>();
|
||||
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(); });
|
||||
}
|
||||
|
||||
Controller::~Controller() {
|
||||
for (auto c : m_connections) {
|
||||
c->stopSync();
|
||||
c->saveState();
|
||||
}
|
||||
}
|
||||
|
||||
inline QString accessTokenFileName(const AccountSettings& account) {
|
||||
QString fileName = account.userId();
|
||||
fileName.replace(':', '_');
|
||||
return QStandardPaths::writableLocation(
|
||||
QStandardPaths::AppLocalDataLocation) +
|
||||
'/' + fileName;
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
QUrl serverUrl(serverAddr);
|
||||
|
||||
auto conn = new Connection(this);
|
||||
if (serverUrl.isValid()) {
|
||||
conn->setHomeserver(serverUrl);
|
||||
}
|
||||
conn->connectToServer(user, pass, deviceName, "");
|
||||
|
||||
connect(conn, &Connection::connected, [=] {
|
||||
AccountSettings account(conn->userId());
|
||||
account.setKeepLoggedIn(true);
|
||||
account.clearAccessToken(); // Drop the legacy - just in case
|
||||
account.setHomeserver(conn->homeserver());
|
||||
account.setDeviceId(conn->deviceId());
|
||||
account.setDeviceName(deviceName);
|
||||
if (!saveAccessTokenToKeyChain(account, conn->accessToken()))
|
||||
qWarning() << "Couldn't save access token";
|
||||
account.sync();
|
||||
addConnection(conn);
|
||||
setConnection(conn);
|
||||
});
|
||||
connect(conn, &Connection::networkError,
|
||||
[=](QString error, QString, int, int) {
|
||||
emit errorOccured("Network Error", error);
|
||||
});
|
||||
connect(conn, &Connection::loginError, [=](QString error, QString) {
|
||||
emit errorOccured("Login Failed", error);
|
||||
});
|
||||
}
|
||||
|
||||
void Controller::loginWithAccessToken(QString serverAddr,
|
||||
QString user,
|
||||
QString token,
|
||||
QString deviceName) {
|
||||
if (user.isEmpty() || token.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
QUrl serverUrl(serverAddr);
|
||||
|
||||
auto conn = new Connection(this);
|
||||
if (serverUrl.isValid()) {
|
||||
conn->setHomeserver(serverUrl);
|
||||
}
|
||||
|
||||
connect(conn, &Connection::connected, [=] {
|
||||
AccountSettings account(conn->userId());
|
||||
account.setKeepLoggedIn(true);
|
||||
account.clearAccessToken(); // Drop the legacy - just in case
|
||||
account.setHomeserver(conn->homeserver());
|
||||
account.setDeviceId(conn->deviceId());
|
||||
account.setDeviceName(deviceName);
|
||||
if (!saveAccessTokenToKeyChain(account, conn->accessToken()))
|
||||
qWarning() << "Couldn't save access token";
|
||||
account.sync();
|
||||
addConnection(conn);
|
||||
setConnection(conn);
|
||||
});
|
||||
connect(conn, &Connection::networkError,
|
||||
[=](QString error, QString, int, int) {
|
||||
emit errorOccured("Network Error", error);
|
||||
});
|
||||
conn->connectWithToken(user, token, deviceName);
|
||||
}
|
||||
|
||||
void Controller::logout(Connection* conn) {
|
||||
if (!conn) {
|
||||
qCritical() << "Attempt to logout null connection";
|
||||
return;
|
||||
}
|
||||
|
||||
SettingsGroup("Accounts").remove(conn->userId());
|
||||
QFile(accessTokenFileName(AccountSettings(conn->userId()))).remove();
|
||||
|
||||
QKeychain::DeletePasswordJob job(qAppName());
|
||||
job.setAutoDelete(true);
|
||||
job.setKey(conn->userId());
|
||||
QEventLoop loop;
|
||||
QKeychain::DeletePasswordJob::connect(&job, &QKeychain::Job::finished, &loop,
|
||||
&QEventLoop::quit);
|
||||
job.start();
|
||||
loop.exec();
|
||||
|
||||
auto logoutJob = conn->callApi<LogoutJob>();
|
||||
connect(logoutJob, &LogoutJob::finished, conn, [=] {
|
||||
conn->stopSync();
|
||||
emit conn->stateChanged();
|
||||
emit conn->loggedOut();
|
||||
if (!m_connections.isEmpty())
|
||||
setConnection(m_connections[0]);
|
||||
});
|
||||
connect(logoutJob, &LogoutJob::failure, this, [=] {
|
||||
emit errorOccured("Server-side Logout Failed", logoutJob->errorString());
|
||||
});
|
||||
}
|
||||
|
||||
void Controller::addConnection(Connection* c) {
|
||||
Q_ASSERT_X(c, __FUNCTION__, "Attempt to add a null connection");
|
||||
|
||||
m_connections += c;
|
||||
|
||||
c->setLazyLoading(true);
|
||||
|
||||
connect(c, &Connection::syncDone, this, [=] {
|
||||
setBusy(false);
|
||||
|
||||
emit syncDone();
|
||||
|
||||
c->sync(30000);
|
||||
c->saveState();
|
||||
});
|
||||
connect(c, &Connection::loggedOut, this, [=] { dropConnection(c); });
|
||||
connect(&m_ncm, &QNetworkConfigurationManager::onlineStateChanged,
|
||||
[=](bool status) {
|
||||
if (!status) {
|
||||
return;
|
||||
}
|
||||
|
||||
c->stopSync();
|
||||
c->sync(30000);
|
||||
});
|
||||
|
||||
using namespace Quotient;
|
||||
|
||||
setBusy(true);
|
||||
|
||||
c->sync();
|
||||
|
||||
emit connectionAdded(c);
|
||||
}
|
||||
|
||||
void Controller::dropConnection(Connection* c) {
|
||||
Q_ASSERT_X(c, __FUNCTION__, "Attempt to drop a null connection");
|
||||
m_connections.removeOne(c);
|
||||
|
||||
emit connectionDropped(c);
|
||||
c->deleteLater();
|
||||
}
|
||||
|
||||
void Controller::invokeLogin() {
|
||||
using namespace Quotient;
|
||||
const auto accounts = SettingsGroup("Accounts").childGroups();
|
||||
for (const auto& accountId : accounts) {
|
||||
AccountSettings account{accountId};
|
||||
if (!account.homeserver().isEmpty()) {
|
||||
auto accessToken = loadAccessTokenFromKeyChain(account);
|
||||
|
||||
auto c = new Connection(account.homeserver(), this);
|
||||
auto deviceName = account.deviceName();
|
||||
connect(c, &Connection::connected, this, [=] {
|
||||
c->loadState();
|
||||
addConnection(c);
|
||||
});
|
||||
connect(c, &Connection::loginError, [=](QString error, QString) {
|
||||
emit errorOccured("Login Failed", error);
|
||||
logout(c);
|
||||
});
|
||||
connect(c, &Connection::networkError,
|
||||
[=](QString error, QString, int, int) {
|
||||
emit errorOccured("Network Error", error);
|
||||
});
|
||||
c->connectWithToken(account.userId(), accessToken, account.deviceId());
|
||||
}
|
||||
}
|
||||
|
||||
if (!m_connections.isEmpty()) {
|
||||
setConnection(m_connections[0]);
|
||||
}
|
||||
|
||||
emit initiated();
|
||||
}
|
||||
|
||||
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() << "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();
|
||||
QKeychain::ReadPasswordJob job(qAppName());
|
||||
job.setAutoDelete(false);
|
||||
job.setKey(account.userId());
|
||||
QEventLoop loop;
|
||||
QKeychain::ReadPasswordJob::connect(&job, &QKeychain::Job::finished, &loop,
|
||||
&QEventLoop::quit);
|
||||
job.start();
|
||||
loop.exec();
|
||||
|
||||
if (job.error() == QKeychain::Error::NoError) {
|
||||
return job.binaryData();
|
||||
}
|
||||
|
||||
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();
|
||||
bool removed = false;
|
||||
bool saved = saveAccessTokenToKeyChain(account, accessToken);
|
||||
if (saved) {
|
||||
QFile accountTokenFile{accessTokenFileName(account)};
|
||||
removed = accountTokenFile.remove();
|
||||
}
|
||||
if (!(saved && removed)) {
|
||||
qDebug() << "Migrating the access token from the file to the keychain "
|
||||
"failed";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return accessToken;
|
||||
}
|
||||
|
||||
bool Controller::saveAccessTokenToFile(const AccountSettings& account,
|
||||
const QByteArray& accessToken) {
|
||||
// (Re-)Make a dedicated file for access_token.
|
||||
QFile accountTokenFile{accessTokenFileName(account)};
|
||||
accountTokenFile.remove(); // Just in case
|
||||
|
||||
auto fileDir = QFileInfo(accountTokenFile).dir();
|
||||
if (!((fileDir.exists() || fileDir.mkpath(".")) &&
|
||||
accountTokenFile.open(QFile::WriteOnly))) {
|
||||
emit errorOccured("I/O Denied", "Cannot save access token.");
|
||||
} else {
|
||||
accountTokenFile.write(accessToken);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
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);
|
||||
job.start();
|
||||
loop.exec();
|
||||
|
||||
if (job.error()) {
|
||||
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) {
|
||||
if (!alias.contains(":"))
|
||||
return;
|
||||
|
||||
auto knownServer = alias.mid(alias.indexOf(":") + 1);
|
||||
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());
|
||||
createRoomJob->connect(createRoomJob, &CreateRoomJob::failure, [=] {
|
||||
emit errorOccured("Create Room Failed", createRoomJob->errorString());
|
||||
});
|
||||
}
|
||||
|
||||
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());
|
||||
});
|
||||
}
|
||||
|
||||
void Controller::playAudio(QUrl localFile) {
|
||||
auto player = new QMediaPlayer;
|
||||
player->setMedia(localFile);
|
||||
player->play();
|
||||
connect(player, &QMediaPlayer::stateChanged, [=] { player->deleteLater(); });
|
||||
}
|
||||
|
||||
void Controller::changeAvatar(Connection* conn, QUrl localFile) {
|
||||
auto job = conn->uploadFile(localFile.toLocalFile());
|
||||
if (isJobRunning(job)) {
|
||||
connect(job, &BaseJob::success, this, [conn, job] {
|
||||
conn->callApi<SetAvatarUrlJob>(conn->userId(), job->contentUri());
|
||||
QTimer::singleShot(0, this, [=] {
|
||||
invokeLogin();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void Controller::markAllMessagesAsRead(Connection* conn) {
|
||||
for (auto room : conn->allRooms()) {
|
||||
room->markAllMessagesAsRead();
|
||||
}
|
||||
Controller::~Controller()
|
||||
{
|
||||
for (auto c : m_connections) {
|
||||
c->stopSync();
|
||||
c->saveState();
|
||||
}
|
||||
}
|
||||
|
||||
inline QString accessTokenFileName(const AccountSettings &account)
|
||||
{
|
||||
QString fileName = account.userId();
|
||||
fileName.replace(':', '_');
|
||||
return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + '/' + fileName;
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
QUrl serverUrl(serverAddr);
|
||||
|
||||
auto conn = new Connection(this);
|
||||
if (serverUrl.isValid()) {
|
||||
conn->setHomeserver(serverUrl);
|
||||
}
|
||||
conn->connectToServer(user, pass, deviceName, "");
|
||||
|
||||
connect(conn, &Connection::connected, [=] {
|
||||
AccountSettings account(conn->userId());
|
||||
account.setKeepLoggedIn(true);
|
||||
account.clearAccessToken(); // Drop the legacy - just in case
|
||||
account.setHomeserver(conn->homeserver());
|
||||
account.setDeviceId(conn->deviceId());
|
||||
account.setDeviceName(deviceName);
|
||||
if (!saveAccessTokenToKeyChain(account, conn->accessToken()))
|
||||
qWarning() << "Couldn't save access token";
|
||||
account.sync();
|
||||
addConnection(conn);
|
||||
setConnection(conn);
|
||||
});
|
||||
connect(conn, &Connection::networkError, [=](QString error, QString, int, int) {
|
||||
emit errorOccured("Network Error", error);
|
||||
});
|
||||
connect(conn, &Connection::loginError, [=](QString error, QString) {
|
||||
emit errorOccured("Login Failed", error);
|
||||
});
|
||||
}
|
||||
|
||||
void Controller::loginWithAccessToken(QString serverAddr, QString user, QString token, QString deviceName)
|
||||
{
|
||||
if (user.isEmpty() || token.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
QUrl serverUrl(serverAddr);
|
||||
|
||||
auto conn = new Connection(this);
|
||||
if (serverUrl.isValid()) {
|
||||
conn->setHomeserver(serverUrl);
|
||||
}
|
||||
|
||||
connect(conn, &Connection::connected, [=] {
|
||||
AccountSettings account(conn->userId());
|
||||
account.setKeepLoggedIn(true);
|
||||
account.clearAccessToken(); // Drop the legacy - just in case
|
||||
account.setHomeserver(conn->homeserver());
|
||||
account.setDeviceId(conn->deviceId());
|
||||
account.setDeviceName(deviceName);
|
||||
if (!saveAccessTokenToKeyChain(account, conn->accessToken()))
|
||||
qWarning() << "Couldn't save access token";
|
||||
account.sync();
|
||||
addConnection(conn);
|
||||
setConnection(conn);
|
||||
});
|
||||
connect(conn, &Connection::networkError, [=](QString error, QString, int, int) {
|
||||
emit errorOccured("Network Error", error);
|
||||
});
|
||||
conn->connectWithToken(user, token, deviceName);
|
||||
}
|
||||
|
||||
void Controller::logout(Connection *conn)
|
||||
{
|
||||
if (!conn) {
|
||||
qCritical() << "Attempt to logout null connection";
|
||||
return;
|
||||
}
|
||||
|
||||
SettingsGroup("Accounts").remove(conn->userId());
|
||||
QFile(accessTokenFileName(AccountSettings(conn->userId()))).remove();
|
||||
|
||||
QKeychain::DeletePasswordJob job(qAppName());
|
||||
job.setAutoDelete(true);
|
||||
job.setKey(conn->userId());
|
||||
QEventLoop loop;
|
||||
QKeychain::DeletePasswordJob::connect(&job, &QKeychain::Job::finished, &loop, &QEventLoop::quit);
|
||||
job.start();
|
||||
loop.exec();
|
||||
|
||||
auto logoutJob = conn->callApi<LogoutJob>();
|
||||
connect(logoutJob, &LogoutJob::finished, conn, [=] {
|
||||
conn->stopSync();
|
||||
emit conn->stateChanged();
|
||||
emit conn->loggedOut();
|
||||
if (!m_connections.isEmpty())
|
||||
setConnection(m_connections[0]);
|
||||
});
|
||||
connect(logoutJob, &LogoutJob::failure, this, [=] {
|
||||
emit errorOccured("Server-side Logout Failed", logoutJob->errorString());
|
||||
});
|
||||
}
|
||||
|
||||
void Controller::addConnection(Connection *c)
|
||||
{
|
||||
Q_ASSERT_X(c, __FUNCTION__, "Attempt to add a null connection");
|
||||
|
||||
m_connections += c;
|
||||
|
||||
c->setLazyLoading(true);
|
||||
|
||||
connect(c, &Connection::syncDone, this, [=] {
|
||||
setBusy(false);
|
||||
|
||||
emit syncDone();
|
||||
|
||||
c->sync(30000);
|
||||
c->saveState();
|
||||
});
|
||||
connect(c, &Connection::loggedOut, this, [=] {
|
||||
dropConnection(c);
|
||||
});
|
||||
connect(&m_ncm, &QNetworkConfigurationManager::onlineStateChanged, [=](bool status) {
|
||||
if (!status) {
|
||||
return;
|
||||
}
|
||||
|
||||
c->stopSync();
|
||||
c->sync(30000);
|
||||
});
|
||||
|
||||
using namespace Quotient;
|
||||
|
||||
setBusy(true);
|
||||
|
||||
c->sync();
|
||||
|
||||
emit connectionAdded(c);
|
||||
}
|
||||
|
||||
void Controller::dropConnection(Connection *c)
|
||||
{
|
||||
Q_ASSERT_X(c, __FUNCTION__, "Attempt to drop a null connection");
|
||||
m_connections.removeOne(c);
|
||||
|
||||
emit connectionDropped(c);
|
||||
c->deleteLater();
|
||||
}
|
||||
|
||||
void Controller::invokeLogin()
|
||||
{
|
||||
using namespace Quotient;
|
||||
const auto accounts = SettingsGroup("Accounts").childGroups();
|
||||
for (const auto &accountId : accounts) {
|
||||
AccountSettings account {accountId};
|
||||
if (!account.homeserver().isEmpty()) {
|
||||
auto accessToken = loadAccessTokenFromKeyChain(account);
|
||||
|
||||
auto c = new Connection(account.homeserver(), this);
|
||||
auto deviceName = account.deviceName();
|
||||
connect(c, &Connection::connected, this, [=] {
|
||||
c->loadState();
|
||||
addConnection(c);
|
||||
});
|
||||
connect(c, &Connection::loginError, [=](QString error, QString) {
|
||||
emit errorOccured("Login Failed", error);
|
||||
logout(c);
|
||||
});
|
||||
connect(c, &Connection::networkError, [=](QString error, QString, int, int) {
|
||||
emit errorOccured("Network Error", error);
|
||||
});
|
||||
c->connectWithToken(account.userId(), accessToken, account.deviceId());
|
||||
}
|
||||
}
|
||||
|
||||
if (!m_connections.isEmpty()) {
|
||||
setConnection(m_connections[0]);
|
||||
}
|
||||
|
||||
emit initiated();
|
||||
}
|
||||
|
||||
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() << "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();
|
||||
QKeychain::ReadPasswordJob job(qAppName());
|
||||
job.setAutoDelete(false);
|
||||
job.setKey(account.userId());
|
||||
QEventLoop loop;
|
||||
QKeychain::ReadPasswordJob::connect(&job, &QKeychain::Job::finished, &loop, &QEventLoop::quit);
|
||||
job.start();
|
||||
loop.exec();
|
||||
|
||||
if (job.error() == QKeychain::Error::NoError) {
|
||||
return job.binaryData();
|
||||
}
|
||||
|
||||
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();
|
||||
bool removed = false;
|
||||
bool saved = saveAccessTokenToKeyChain(account, accessToken);
|
||||
if (saved) {
|
||||
QFile accountTokenFile {accessTokenFileName(account)};
|
||||
removed = accountTokenFile.remove();
|
||||
}
|
||||
if (!(saved && removed)) {
|
||||
qDebug() << "Migrating the access token from the file to the keychain "
|
||||
"failed";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return accessToken;
|
||||
}
|
||||
|
||||
bool Controller::saveAccessTokenToFile(const AccountSettings &account, const QByteArray &accessToken)
|
||||
{
|
||||
// (Re-)Make a dedicated file for access_token.
|
||||
QFile accountTokenFile {accessTokenFileName(account)};
|
||||
accountTokenFile.remove(); // Just in case
|
||||
|
||||
auto fileDir = QFileInfo(accountTokenFile).dir();
|
||||
if (!((fileDir.exists() || fileDir.mkpath(".")) && accountTokenFile.open(QFile::WriteOnly))) {
|
||||
emit errorOccured("I/O Denied", "Cannot save access token.");
|
||||
} else {
|
||||
accountTokenFile.write(accessToken);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
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);
|
||||
job.start();
|
||||
loop.exec();
|
||||
|
||||
if (job.error()) {
|
||||
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)
|
||||
{
|
||||
if (!alias.contains(":"))
|
||||
return;
|
||||
|
||||
auto knownServer = alias.mid(alias.indexOf(":") + 1);
|
||||
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());
|
||||
createRoomJob->connect(createRoomJob, &CreateRoomJob::failure, [=] {
|
||||
emit errorOccured("Create Room Failed", createRoomJob->errorString());
|
||||
});
|
||||
}
|
||||
|
||||
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());
|
||||
});
|
||||
}
|
||||
|
||||
void Controller::playAudio(QUrl localFile)
|
||||
{
|
||||
auto player = new QMediaPlayer;
|
||||
player->setMedia(localFile);
|
||||
player->play();
|
||||
connect(player, &QMediaPlayer::stateChanged, [=] {
|
||||
player->deleteLater();
|
||||
});
|
||||
}
|
||||
|
||||
void Controller::changeAvatar(Connection *conn, QUrl localFile)
|
||||
{
|
||||
auto job = conn->uploadFile(localFile.toLocalFile());
|
||||
if (isJobRunning(job)) {
|
||||
connect(job, &BaseJob::success, this, [conn, job] {
|
||||
conn->callApi<SetAvatarUrlJob>(conn->userId(), job->contentUri());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void Controller::markAllMessagesAsRead(Connection *conn)
|
||||
{
|
||||
for (auto room : conn->allRooms()) {
|
||||
room->markAllMessagesAsRead();
|
||||
}
|
||||
}
|
||||
|
||||
189
src/controller.h
189
src/controller.h
@@ -22,109 +22,122 @@
|
||||
|
||||
using namespace Quotient;
|
||||
|
||||
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(bool isOnline READ isOnline NOTIFY isOnlineChanged)
|
||||
Q_PROPERTY(bool busy READ busy WRITE setBusy NOTIFY busyChanged)
|
||||
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(bool isOnline READ isOnline NOTIFY isOnlineChanged)
|
||||
Q_PROPERTY(bool busy READ busy WRITE setBusy NOTIFY busyChanged)
|
||||
|
||||
public:
|
||||
explicit Controller(QObject* parent = nullptr);
|
||||
~Controller();
|
||||
public:
|
||||
explicit Controller(QObject *parent = nullptr);
|
||||
~Controller();
|
||||
|
||||
Q_INVOKABLE void loginWithCredentials(QString, QString, QString, QString);
|
||||
Q_INVOKABLE void loginWithAccessToken(QString, QString, QString, QString);
|
||||
Q_INVOKABLE void loginWithCredentials(QString, QString, QString, QString);
|
||||
Q_INVOKABLE void loginWithAccessToken(QString, QString, QString, QString);
|
||||
|
||||
QVector<Connection*> connections() const { return m_connections; }
|
||||
|
||||
// All the non-Q_INVOKABLE functions.
|
||||
void addConnection(Connection* c);
|
||||
void dropConnection(Connection* c);
|
||||
|
||||
// All the Q_PROPERTYs.
|
||||
int accountCount() { return m_connections.count(); }
|
||||
|
||||
bool quitOnLastWindowClosed() const {
|
||||
return QApplication::quitOnLastWindowClosed();
|
||||
}
|
||||
void setQuitOnLastWindowClosed(bool value) {
|
||||
if (quitOnLastWindowClosed() != value) {
|
||||
QApplication::setQuitOnLastWindowClosed(value);
|
||||
|
||||
emit quitOnLastWindowClosedChanged();
|
||||
QVector<Connection *> connections() const
|
||||
{
|
||||
return m_connections;
|
||||
}
|
||||
}
|
||||
|
||||
bool isOnline() const { return m_ncm.isOnline(); }
|
||||
// All the non-Q_INVOKABLE functions.
|
||||
void addConnection(Connection *c);
|
||||
void dropConnection(Connection *c);
|
||||
|
||||
bool busy() const { return m_busy; }
|
||||
void setBusy(bool busy) {
|
||||
if (m_busy == busy) {
|
||||
return;
|
||||
// All the Q_PROPERTYs.
|
||||
int accountCount()
|
||||
{
|
||||
return m_connections.count();
|
||||
}
|
||||
m_busy = busy;
|
||||
emit busyChanged();
|
||||
}
|
||||
|
||||
Connection* connection() const {
|
||||
if (m_connection.isNull())
|
||||
return nullptr;
|
||||
bool quitOnLastWindowClosed() const
|
||||
{
|
||||
return QApplication::quitOnLastWindowClosed();
|
||||
}
|
||||
void setQuitOnLastWindowClosed(bool value)
|
||||
{
|
||||
if (quitOnLastWindowClosed() != value) {
|
||||
QApplication::setQuitOnLastWindowClosed(value);
|
||||
|
||||
return m_connection;
|
||||
}
|
||||
emit quitOnLastWindowClosedChanged();
|
||||
}
|
||||
}
|
||||
|
||||
void setConnection(Connection* conn) {
|
||||
if (conn == m_connection)
|
||||
return;
|
||||
m_connection = conn;
|
||||
emit connectionChanged();
|
||||
}
|
||||
bool isOnline() const
|
||||
{
|
||||
return m_ncm.isOnline();
|
||||
}
|
||||
|
||||
private:
|
||||
QVector<Connection*> m_connections;
|
||||
QPointer<Connection> m_connection;
|
||||
QNetworkConfigurationManager m_ncm;
|
||||
bool m_busy = false;
|
||||
bool busy() const
|
||||
{
|
||||
return m_busy;
|
||||
}
|
||||
void setBusy(bool busy)
|
||||
{
|
||||
if (m_busy == busy) {
|
||||
return;
|
||||
}
|
||||
m_busy = busy;
|
||||
emit busyChanged();
|
||||
}
|
||||
|
||||
QByteArray loadAccessTokenFromFile(const AccountSettings& account);
|
||||
QByteArray loadAccessTokenFromKeyChain(const AccountSettings& account);
|
||||
Connection *connection() const
|
||||
{
|
||||
if (m_connection.isNull())
|
||||
return nullptr;
|
||||
|
||||
bool saveAccessTokenToFile(const AccountSettings& account,
|
||||
const QByteArray& accessToken);
|
||||
bool saveAccessTokenToKeyChain(const AccountSettings& account,
|
||||
const QByteArray& accessToken);
|
||||
void loadSettings();
|
||||
void saveSettings() const;
|
||||
return m_connection;
|
||||
}
|
||||
|
||||
private slots:
|
||||
void invokeLogin();
|
||||
void setConnection(Connection *conn)
|
||||
{
|
||||
if (conn == m_connection)
|
||||
return;
|
||||
m_connection = conn;
|
||||
emit connectionChanged();
|
||||
}
|
||||
|
||||
signals:
|
||||
void busyChanged();
|
||||
void errorOccured(QString error, QString detail);
|
||||
void syncDone();
|
||||
void connectionAdded(Connection* conn);
|
||||
void connectionDropped(Connection* conn);
|
||||
void initiated();
|
||||
void notificationClicked(const QString roomId, const QString eventId);
|
||||
void quitOnLastWindowClosedChanged();
|
||||
void unreadCountChanged();
|
||||
void connectionChanged();
|
||||
void isOnlineChanged();
|
||||
private:
|
||||
QVector<Connection *> m_connections;
|
||||
QPointer<Connection> m_connection;
|
||||
QNetworkConfigurationManager m_ncm;
|
||||
bool m_busy = false;
|
||||
|
||||
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);
|
||||
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);
|
||||
void loadSettings();
|
||||
void saveSettings() const;
|
||||
|
||||
private slots:
|
||||
void invokeLogin();
|
||||
|
||||
signals:
|
||||
void busyChanged();
|
||||
void errorOccured(QString error, QString detail);
|
||||
void syncDone();
|
||||
void connectionAdded(Connection *conn);
|
||||
void connectionDropped(Connection *conn);
|
||||
void initiated();
|
||||
void notificationClicked(const QString roomId, const QString eventId);
|
||||
void quitOnLastWindowClosedChanged();
|
||||
void unreadCountChanged();
|
||||
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);
|
||||
void playAudio(QUrl localFile);
|
||||
void changeAvatar(Connection *conn, QUrl localFile);
|
||||
void markAllMessagesAsRead(Connection *conn);
|
||||
};
|
||||
|
||||
#endif // CONTROLLER_H
|
||||
#endif // CONTROLLER_H
|
||||
|
||||
4076
src/emojimodel.cpp
4076
src/emojimodel.cpp
File diff suppressed because it is too large
Load Diff
108
src/emojimodel.h
108
src/emojimodel.h
@@ -12,69 +12,81 @@
|
||||
#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) {
|
||||
arch << object.unicode;
|
||||
arch << object.shortname;
|
||||
return arch;
|
||||
}
|
||||
friend QDataStream &operator<<(QDataStream &arch, const Emoji &object)
|
||||
{
|
||||
arch << object.unicode;
|
||||
arch << object.shortname;
|
||||
return arch;
|
||||
}
|
||||
|
||||
friend QDataStream& operator>>(QDataStream& arch, Emoji& object) {
|
||||
arch >> object.unicode;
|
||||
arch >> object.shortname;
|
||||
return arch;
|
||||
}
|
||||
friend QDataStream &operator>>(QDataStream &arch, Emoji &object)
|
||||
{
|
||||
arch >> object.unicode;
|
||||
arch >> object.shortname;
|
||||
return arch;
|
||||
}
|
||||
|
||||
QString unicode;
|
||||
QString shortname;
|
||||
QString unicode;
|
||||
QString shortname;
|
||||
|
||||
Q_GADGET
|
||||
Q_PROPERTY(QString unicode MEMBER unicode)
|
||||
Q_PROPERTY(QString shortname MEMBER shortname)
|
||||
Q_GADGET
|
||||
Q_PROPERTY(QString unicode MEMBER unicode)
|
||||
Q_PROPERTY(QString shortname MEMBER shortname)
|
||||
};
|
||||
|
||||
Q_DECLARE_METATYPE(Emoji)
|
||||
|
||||
class EmojiModel : public QObject {
|
||||
Q_OBJECT
|
||||
class EmojiModel : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
Q_PROPERTY(QVariantList history READ history NOTIFY historyChanged)
|
||||
Q_PROPERTY(QVariantList history READ history NOTIFY historyChanged)
|
||||
|
||||
Q_PROPERTY(QVariantList people MEMBER people CONSTANT)
|
||||
Q_PROPERTY(QVariantList nature MEMBER nature CONSTANT)
|
||||
Q_PROPERTY(QVariantList food MEMBER food CONSTANT)
|
||||
Q_PROPERTY(QVariantList activity MEMBER activity CONSTANT)
|
||||
Q_PROPERTY(QVariantList travel MEMBER travel CONSTANT)
|
||||
Q_PROPERTY(QVariantList objects MEMBER objects CONSTANT)
|
||||
Q_PROPERTY(QVariantList symbols MEMBER symbols CONSTANT)
|
||||
Q_PROPERTY(QVariantList flags MEMBER flags CONSTANT)
|
||||
Q_PROPERTY(QVariantList people MEMBER people CONSTANT)
|
||||
Q_PROPERTY(QVariantList nature MEMBER nature CONSTANT)
|
||||
Q_PROPERTY(QVariantList food MEMBER food CONSTANT)
|
||||
Q_PROPERTY(QVariantList activity MEMBER activity CONSTANT)
|
||||
Q_PROPERTY(QVariantList travel MEMBER travel CONSTANT)
|
||||
Q_PROPERTY(QVariantList objects MEMBER objects CONSTANT)
|
||||
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 history();
|
||||
Q_INVOKABLE QVariantList filterModel(const QString &filter);
|
||||
|
||||
signals:
|
||||
void historyChanged();
|
||||
signals:
|
||||
void historyChanged();
|
||||
|
||||
public slots:
|
||||
void emojiUsed(QVariant modelData);
|
||||
public slots:
|
||||
void emojiUsed(QVariant modelData);
|
||||
|
||||
private:
|
||||
static const QVariantList people;
|
||||
static const QVariantList nature;
|
||||
static const QVariantList food;
|
||||
static const QVariantList activity;
|
||||
static const QVariantList travel;
|
||||
static const QVariantList objects;
|
||||
static const QVariantList symbols;
|
||||
static const QVariantList flags;
|
||||
private:
|
||||
static const QVariantList people;
|
||||
static const QVariantList nature;
|
||||
static const QVariantList food;
|
||||
static const QVariantList activity;
|
||||
static const QVariantList travel;
|
||||
static const QVariantList objects;
|
||||
static const QVariantList symbols;
|
||||
static const QVariantList flags;
|
||||
|
||||
QSettings* m_settings;
|
||||
QSettings *m_settings;
|
||||
};
|
||||
|
||||
#endif // EMOJIMODEL_H
|
||||
#endif // EMOJIMODEL_H
|
||||
|
||||
@@ -11,36 +11,40 @@
|
||||
#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 {
|
||||
return !image().isNull();
|
||||
bool ImageClipboard::hasImage() const
|
||||
{
|
||||
return !image().isNull();
|
||||
}
|
||||
|
||||
QImage ImageClipboard::image() const {
|
||||
return m_clipboard->image();
|
||||
QImage ImageClipboard::image() const
|
||||
{
|
||||
return m_clipboard->image();
|
||||
}
|
||||
|
||||
bool ImageClipboard::saveImage(const QUrl& localPath) {
|
||||
if (!localPath.isLocalFile())
|
||||
return false;
|
||||
bool ImageClipboard::saveImage(const QUrl &localPath)
|
||||
{
|
||||
if (!localPath.isLocalFile())
|
||||
return false;
|
||||
|
||||
auto i = image();
|
||||
auto i = image();
|
||||
|
||||
if (i.isNull())
|
||||
return false;
|
||||
if (i.isNull())
|
||||
return false;
|
||||
|
||||
QString path = QFileInfo(localPath.toLocalFile()).absolutePath();
|
||||
QDir dir;
|
||||
if (!dir.exists(path)) {
|
||||
dir.mkpath(path);
|
||||
}
|
||||
QString path = QFileInfo(localPath.toLocalFile()).absolutePath();
|
||||
QDir dir;
|
||||
if (!dir.exists(path)) {
|
||||
dir.mkpath(path);
|
||||
}
|
||||
|
||||
i.save(localPath.toLocalFile());
|
||||
i.save(localPath.toLocalFile());
|
||||
|
||||
return true;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -10,24 +10,25 @@
|
||||
#include <QImage>
|
||||
#include <QObject>
|
||||
|
||||
class ImageClipboard : public QObject {
|
||||
Q_OBJECT
|
||||
Q_PROPERTY(bool hasImage READ hasImage NOTIFY imageChanged)
|
||||
Q_PROPERTY(QImage image READ image NOTIFY imageChanged)
|
||||
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;
|
||||
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:
|
||||
void imageChanged();
|
||||
signals:
|
||||
void imageChanged();
|
||||
};
|
||||
|
||||
#endif // IMAGECLIPBOARD_H
|
||||
#endif // IMAGECLIPBOARD_H
|
||||
|
||||
87
src/main.cpp
87
src/main.cpp
@@ -30,59 +30,56 @@
|
||||
|
||||
using namespace Quotient;
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
|
||||
|
||||
QNetworkProxyFactory::setUseSystemConfiguration(true);
|
||||
QNetworkProxyFactory::setUseSystemConfiguration(true);
|
||||
|
||||
QApplication app(argc, argv);
|
||||
QApplication app(argc, argv);
|
||||
|
||||
app.setOrganizationName("ENCOM");
|
||||
app.setOrganizationDomain("encom.eu.org");
|
||||
app.setApplicationName("Spectral");
|
||||
app.setWindowIcon(QIcon(":/assets/img/icon.png"));
|
||||
app.setOrganizationName("ENCOM");
|
||||
app.setOrganizationDomain("encom.eu.org");
|
||||
app.setApplicationName("Spectral");
|
||||
app.setWindowIcon(QIcon(":/assets/img/icon.png"));
|
||||
|
||||
qmlRegisterType<Controller>("Spectral", 0, 1, "Controller");
|
||||
qmlRegisterType<AccountListModel>("Spectral", 0, 1, "AccountListModel");
|
||||
qmlRegisterType<RoomListModel>("Spectral", 0, 1, "RoomListModel");
|
||||
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<EmojiModel>("Spectral", 0, 1, "EmojiModel");
|
||||
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<RoomType>("Spectral", 0, 1, "RoomType", "ENUM");
|
||||
qmlRegisterUncreatableType<UserType>("Spectral", 0, 1, "UserType", "ENUM");
|
||||
qmlRegisterType<Controller>("Spectral", 0, 1, "Controller");
|
||||
qmlRegisterType<AccountListModel>("Spectral", 0, 1, "AccountListModel");
|
||||
qmlRegisterType<RoomListModel>("Spectral", 0, 1, "RoomListModel");
|
||||
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<EmojiModel>("Spectral", 0, 1, "EmojiModel");
|
||||
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<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<MessageEventType>("MessageEventType");
|
||||
qRegisterMetaType<SpectralRoom*>("SpectralRoom*");
|
||||
qRegisterMetaType<SpectralUser*>("SpectralUser*");
|
||||
qRegisterMetaType<GetRoomEventsJob*>("GetRoomEventsJob*");
|
||||
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*");
|
||||
|
||||
qRegisterMetaTypeStreamOperators<Emoji>();
|
||||
qRegisterMetaTypeStreamOperators<Emoji>();
|
||||
|
||||
QQmlApplicationEngine engine;
|
||||
QQmlApplicationEngine engine;
|
||||
|
||||
engine.addImportPath("qrc:/imports");
|
||||
MatrixImageProvider* matrixImageProvider = new MatrixImageProvider();
|
||||
engine.rootContext()->setContextProperty("imageProvider",
|
||||
matrixImageProvider);
|
||||
engine.addImageProvider(QLatin1String("mxc"), matrixImageProvider);
|
||||
engine.addImportPath("qrc:/imports");
|
||||
MatrixImageProvider *matrixImageProvider = new MatrixImageProvider();
|
||||
engine.rootContext()->setContextProperty("imageProvider", matrixImageProvider);
|
||||
engine.addImageProvider(QLatin1String("mxc"), matrixImageProvider);
|
||||
|
||||
engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml")));
|
||||
if (engine.rootObjects().isEmpty())
|
||||
return -1;
|
||||
engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml")));
|
||||
if (engine.rootObjects().isEmpty())
|
||||
return -1;
|
||||
|
||||
return app.exec();
|
||||
return app.exec();
|
||||
}
|
||||
|
||||
@@ -14,113 +14,108 @@
|
||||
|
||||
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") {
|
||||
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);
|
||||
emit finished();
|
||||
return;
|
||||
}
|
||||
|
||||
QImage cachedImage;
|
||||
if (cachedImage.load(localFile)) {
|
||||
image = cachedImage;
|
||||
errorStr.clear();
|
||||
emit finished();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!c) {
|
||||
qWarning() << "Current connection is null";
|
||||
return;
|
||||
}
|
||||
|
||||
// Execute a request on the main thread asynchronously
|
||||
moveToThread(c->thread());
|
||||
QMetaObject::invokeMethod(this, &ThumbnailResponse::startRequest,
|
||||
Qt::QueuedConnection);
|
||||
}
|
||||
|
||||
void ThumbnailResponse::startRequest() {
|
||||
// Runs in the main thread, not QML thread
|
||||
Q_ASSERT(QThread::currentThread() == c->thread());
|
||||
job = c->getThumbnail(mediaId, requestedSize);
|
||||
// Connect to any possible outcome including abandonment
|
||||
// to make sure the QML thread is not left stuck forever.
|
||||
connect(job, &BaseJob::finished, this, &ThumbnailResponse::prepareResult);
|
||||
}
|
||||
|
||||
void ThumbnailResponse::prepareResult() {
|
||||
Q_ASSERT(QThread::currentThread() == job->thread());
|
||||
Q_ASSERT(job->error() != BaseJob::Pending);
|
||||
{
|
||||
QWriteLocker _(&lock);
|
||||
if (job->error() == BaseJob::Success) {
|
||||
image = job->thumbnail();
|
||||
|
||||
QString localPath = QFileInfo(localFile).absolutePath();
|
||||
QDir dir;
|
||||
if (!dir.exists(localPath))
|
||||
dir.mkpath(localPath);
|
||||
|
||||
image.save(localFile);
|
||||
|
||||
errorStr.clear();
|
||||
} else if (job->error() == BaseJob::Abandoned) {
|
||||
errorStr = tr("Image request has been cancelled");
|
||||
qDebug() << "ThumbnailResponse: cancelled for" << mediaId;
|
||||
} else {
|
||||
errorStr = job->errorString();
|
||||
qWarning() << "ThumbnailResponse: no valid image for" << mediaId << "-"
|
||||
<< errorStr;
|
||||
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;
|
||||
}
|
||||
job = nullptr;
|
||||
}
|
||||
emit finished();
|
||||
if (mediaId.count('/') != 1) {
|
||||
errorStr = tr("Media id '%1' doesn't follow server/mediaId pattern").arg(mediaId);
|
||||
emit finished();
|
||||
return;
|
||||
}
|
||||
|
||||
QImage cachedImage;
|
||||
if (cachedImage.load(localFile)) {
|
||||
image = cachedImage;
|
||||
errorStr.clear();
|
||||
emit finished();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!c) {
|
||||
qWarning() << "Current connection is null";
|
||||
return;
|
||||
}
|
||||
|
||||
// Execute a request on the main thread asynchronously
|
||||
moveToThread(c->thread());
|
||||
QMetaObject::invokeMethod(this, &ThumbnailResponse::startRequest, Qt::QueuedConnection);
|
||||
}
|
||||
|
||||
void ThumbnailResponse::doCancel() {
|
||||
// Runs in the main thread, not QML thread
|
||||
if (job) {
|
||||
void ThumbnailResponse::startRequest()
|
||||
{
|
||||
// Runs in the main thread, not QML thread
|
||||
Q_ASSERT(QThread::currentThread() == c->thread());
|
||||
job = c->getThumbnail(mediaId, requestedSize);
|
||||
// Connect to any possible outcome including abandonment
|
||||
// to make sure the QML thread is not left stuck forever.
|
||||
connect(job, &BaseJob::finished, this, &ThumbnailResponse::prepareResult);
|
||||
}
|
||||
|
||||
void ThumbnailResponse::prepareResult()
|
||||
{
|
||||
Q_ASSERT(QThread::currentThread() == job->thread());
|
||||
job->abandon();
|
||||
}
|
||||
Q_ASSERT(job->error() != BaseJob::Pending);
|
||||
{
|
||||
QWriteLocker _(&lock);
|
||||
if (job->error() == BaseJob::Success) {
|
||||
image = job->thumbnail();
|
||||
|
||||
QString localPath = QFileInfo(localFile).absolutePath();
|
||||
QDir dir;
|
||||
if (!dir.exists(localPath))
|
||||
dir.mkpath(localPath);
|
||||
|
||||
image.save(localFile);
|
||||
|
||||
errorStr.clear();
|
||||
} else if (job->error() == BaseJob::Abandoned) {
|
||||
errorStr = tr("Image request has been cancelled");
|
||||
qDebug() << "ThumbnailResponse: cancelled for" << mediaId;
|
||||
} else {
|
||||
errorStr = job->errorString();
|
||||
qWarning() << "ThumbnailResponse: no valid image for" << mediaId << "-" << errorStr;
|
||||
}
|
||||
job = nullptr;
|
||||
}
|
||||
emit finished();
|
||||
}
|
||||
|
||||
QQuickTextureFactory* ThumbnailResponse::textureFactory() const {
|
||||
QReadLocker _(&lock);
|
||||
return QQuickTextureFactory::textureFactoryForImage(image);
|
||||
void ThumbnailResponse::doCancel()
|
||||
{
|
||||
// Runs in the main thread, not QML thread
|
||||
if (job) {
|
||||
Q_ASSERT(QThread::currentThread() == job->thread());
|
||||
job->abandon();
|
||||
}
|
||||
}
|
||||
|
||||
QString ThumbnailResponse::errorString() const {
|
||||
QReadLocker _(&lock);
|
||||
return errorStr;
|
||||
QQuickTextureFactory *ThumbnailResponse::textureFactory() const
|
||||
{
|
||||
QReadLocker _(&lock);
|
||||
return QQuickTextureFactory::textureFactoryForImage(image);
|
||||
}
|
||||
|
||||
void ThumbnailResponse::cancel() {
|
||||
QMetaObject::invokeMethod(this, &ThumbnailResponse::doCancel,
|
||||
Qt::QueuedConnection);
|
||||
QString ThumbnailResponse::errorString() const
|
||||
{
|
||||
QReadLocker _(&lock);
|
||||
return errorStr;
|
||||
}
|
||||
|
||||
QQuickImageResponse* MatrixImageProvider::requestImageResponse(
|
||||
const QString& id,
|
||||
const QSize& requestedSize) {
|
||||
return new ThumbnailResponse(m_connection.loadRelaxed(), id, requestedSize);
|
||||
void ThumbnailResponse::cancel()
|
||||
{
|
||||
QMetaObject::invokeMethod(this, &ThumbnailResponse::doCancel, Qt::QueuedConnection);
|
||||
}
|
||||
|
||||
QQuickImageResponse *MatrixImageProvider::requestImageResponse(const QString &id, const QSize &requestedSize)
|
||||
{
|
||||
return new ThumbnailResponse(m_connection.loadRelaxed(), id, requestedSize);
|
||||
}
|
||||
|
||||
@@ -16,61 +16,63 @@
|
||||
#include <QtCore/QAtomicPointer>
|
||||
#include <QtCore/QReadWriteLock>
|
||||
|
||||
namespace Quotient {
|
||||
namespace Quotient
|
||||
{
|
||||
class Connection;
|
||||
}
|
||||
|
||||
class ThumbnailResponse : public QQuickImageResponse {
|
||||
Q_OBJECT
|
||||
public:
|
||||
ThumbnailResponse(Quotient::Connection* c,
|
||||
QString mediaId,
|
||||
const QSize& requestedSize);
|
||||
~ThumbnailResponse() override = default;
|
||||
class ThumbnailResponse : public QQuickImageResponse
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
ThumbnailResponse(Quotient::Connection *c, QString mediaId, const QSize &requestedSize);
|
||||
~ThumbnailResponse() override = default;
|
||||
|
||||
private slots:
|
||||
void startRequest();
|
||||
void prepareResult();
|
||||
void doCancel();
|
||||
private slots:
|
||||
void startRequest();
|
||||
void prepareResult();
|
||||
void doCancel();
|
||||
|
||||
private:
|
||||
Quotient::Connection* c;
|
||||
const QString mediaId;
|
||||
const QSize requestedSize;
|
||||
const QString localFile;
|
||||
Quotient::MediaThumbnailJob* job = nullptr;
|
||||
private:
|
||||
Quotient::Connection *c;
|
||||
const QString mediaId;
|
||||
const QSize requestedSize;
|
||||
const QString localFile;
|
||||
Quotient::MediaThumbnailJob *job = nullptr;
|
||||
|
||||
QImage image;
|
||||
QString errorStr;
|
||||
mutable QReadWriteLock lock; // Guards ONLY these two members above
|
||||
QImage image;
|
||||
QString errorStr;
|
||||
mutable QReadWriteLock lock; // Guards ONLY these two members above
|
||||
|
||||
QQuickTextureFactory* textureFactory() const override;
|
||||
QString errorString() const override;
|
||||
void cancel() override;
|
||||
QQuickTextureFactory *textureFactory() const override;
|
||||
QString errorString() const override;
|
||||
void cancel() override;
|
||||
};
|
||||
|
||||
class MatrixImageProvider : public QObject, public QQuickAsyncImageProvider {
|
||||
Q_OBJECT
|
||||
Q_PROPERTY(Quotient::Connection* connection READ connection WRITE
|
||||
setConnection NOTIFY connectionChanged)
|
||||
public:
|
||||
explicit MatrixImageProvider() = default;
|
||||
class MatrixImageProvider : public QObject, public QQuickAsyncImageProvider
|
||||
{
|
||||
Q_OBJECT
|
||||
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) {
|
||||
m_connection.storeRelaxed(connection);
|
||||
emit connectionChanged();
|
||||
}
|
||||
Quotient::Connection *connection()
|
||||
{
|
||||
return m_connection;
|
||||
}
|
||||
void setConnection(Quotient::Connection *connection)
|
||||
{
|
||||
m_connection.storeRelaxed(connection);
|
||||
emit connectionChanged();
|
||||
}
|
||||
|
||||
signals:
|
||||
void connectionChanged();
|
||||
signals:
|
||||
void connectionChanged();
|
||||
|
||||
private:
|
||||
QAtomicPointer<Quotient::Connection> m_connection;
|
||||
private:
|
||||
QAtomicPointer<Quotient::Connection> m_connection;
|
||||
};
|
||||
|
||||
#endif // MatrixImageProvider_H
|
||||
#endif // MatrixImageProvider_H
|
||||
|
||||
@@ -10,528 +10,482 @@
|
||||
#include <user.h>
|
||||
|
||||
#include <QtCore/QDebug>
|
||||
#include <QtQml> // for qmlRegisterType()
|
||||
#include <QtQml> // for qmlRegisterType()
|
||||
|
||||
#include "utils.h"
|
||||
|
||||
QHash<int, QByteArray> MessageEventModel::roleNames() const {
|
||||
QHash<int, QByteArray> roles = QAbstractItemModel::roleNames();
|
||||
roles[EventTypeRole] = "eventType";
|
||||
roles[MessageRole] = "message";
|
||||
roles[EventIdRole] = "eventId";
|
||||
roles[TimeRole] = "time";
|
||||
roles[SectionRole] = "section";
|
||||
roles[AuthorRole] = "author";
|
||||
roles[ContentRole] = "content";
|
||||
roles[ContentTypeRole] = "contentType";
|
||||
roles[HighlightRole] = "highlight";
|
||||
roles[ReadMarkerRole] = "readMarker";
|
||||
roles[SpecialMarksRole] = "marks";
|
||||
roles[LongOperationRole] = "progressInfo";
|
||||
roles[AnnotationRole] = "annotation";
|
||||
roles[EventResolvedTypeRole] = "eventResolvedType";
|
||||
roles[ReplyRole] = "reply";
|
||||
roles[UserMarkerRole] = "userMarker";
|
||||
roles[ShowAuthorRole] = "showAuthor";
|
||||
roles[ShowSectionRole] = "showSection";
|
||||
roles[ReactionRole] = "reaction";
|
||||
return roles;
|
||||
QHash<int, QByteArray> MessageEventModel::roleNames() const
|
||||
{
|
||||
QHash<int, QByteArray> roles = QAbstractItemModel::roleNames();
|
||||
roles[EventTypeRole] = "eventType";
|
||||
roles[MessageRole] = "message";
|
||||
roles[EventIdRole] = "eventId";
|
||||
roles[TimeRole] = "time";
|
||||
roles[SectionRole] = "section";
|
||||
roles[AuthorRole] = "author";
|
||||
roles[ContentRole] = "content";
|
||||
roles[ContentTypeRole] = "contentType";
|
||||
roles[HighlightRole] = "highlight";
|
||||
roles[ReadMarkerRole] = "readMarker";
|
||||
roles[SpecialMarksRole] = "marks";
|
||||
roles[LongOperationRole] = "progressInfo";
|
||||
roles[AnnotationRole] = "annotation";
|
||||
roles[EventResolvedTypeRole] = "eventResolvedType";
|
||||
roles[ReplyRole] = "reply";
|
||||
roles[UserMarkerRole] = "userMarker";
|
||||
roles[ShowAuthorRole] = "showAuthor";
|
||||
roles[ShowSectionRole] = "showSection";
|
||||
roles[ReactionRole] = "reaction";
|
||||
return roles;
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
MessageEventModel::~MessageEventModel() {}
|
||||
|
||||
void MessageEventModel::setRoom(SpectralRoom* room) {
|
||||
if (room == m_currentRoom)
|
||||
return;
|
||||
|
||||
beginResetModel();
|
||||
if (m_currentRoom) {
|
||||
m_currentRoom->disconnect(this);
|
||||
}
|
||||
|
||||
m_currentRoom = room;
|
||||
if (room) {
|
||||
lastReadEventId = room->readMarkerEventId();
|
||||
|
||||
MessageEventModel::MessageEventModel(QObject *parent)
|
||||
: QAbstractListModel(parent)
|
||||
, m_currentRoom(nullptr)
|
||||
{
|
||||
using namespace Quotient;
|
||||
connect(m_currentRoom, &Room::aboutToAddNewMessages, this,
|
||||
[=](RoomEventsRange events) {
|
||||
beginInsertRows({}, timelineBaseIndex(),
|
||||
timelineBaseIndex() + int(events.size()) - 1);
|
||||
});
|
||||
connect(m_currentRoom, &Room::aboutToAddHistoricalMessages, this,
|
||||
[=](RoomEventsRange events) {
|
||||
if (rowCount() > 0)
|
||||
rowBelowInserted = rowCount() - 1; // See #312
|
||||
beginInsertRows({}, rowCount(),
|
||||
rowCount() + int(events.size()) - 1);
|
||||
});
|
||||
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});
|
||||
}
|
||||
for (auto i = m_currentRoom->maxTimelineIndex() - biggest;
|
||||
i <= m_currentRoom->maxTimelineIndex() - lowest; ++i)
|
||||
qmlRegisterType<FileTransferInfo>();
|
||||
qRegisterMetaType<FileTransferInfo>();
|
||||
qmlRegisterUncreatableType<EventStatus>("Spectral", 0, 1, "EventStatus", "EventStatus is not an creatable type");
|
||||
}
|
||||
|
||||
MessageEventModel::~MessageEventModel()
|
||||
{
|
||||
}
|
||||
|
||||
void MessageEventModel::setRoom(SpectralRoom *room)
|
||||
{
|
||||
if (room == m_currentRoom)
|
||||
return;
|
||||
|
||||
beginResetModel();
|
||||
if (m_currentRoom) {
|
||||
m_currentRoom->disconnect(this);
|
||||
}
|
||||
|
||||
m_currentRoom = room;
|
||||
if (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::aboutToAddHistoricalMessages, this, [=](RoomEventsRange events) {
|
||||
if (rowCount() > 0)
|
||||
rowBelowInserted = rowCount() - 1; // See #312
|
||||
beginInsertRows({}, rowCount(), rowCount() + int(events.size()) - 1);
|
||||
});
|
||||
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});
|
||||
}
|
||||
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::pendingEventAdded, this, &MessageEventModel::endInsertRows);
|
||||
connect(m_currentRoom, &Room::pendingEventAboutToMerge, this,
|
||||
[this](RoomEvent*, int i) {
|
||||
if (i == 0)
|
||||
return; // No need to move anything, just refresh
|
||||
});
|
||||
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) {
|
||||
if (i == 0)
|
||||
return; // No need to move anything, just refresh
|
||||
|
||||
movingEvent = true;
|
||||
// Reverse i because row 0 is bottommost in the model
|
||||
const auto row = timelineBaseIndex() - i - 1;
|
||||
Q_ASSERT(beginMoveRows({}, row, row, {}, timelineBaseIndex()));
|
||||
});
|
||||
connect(m_currentRoom, &Room::pendingEventMerged, this, [this] {
|
||||
if (movingEvent) {
|
||||
endMoveRows();
|
||||
movingEvent = false;
|
||||
}
|
||||
refreshRow(timelineBaseIndex()); // Refresh the looks
|
||||
refreshLastUserEvents(0);
|
||||
if (m_currentRoom->timelineSize() > 1) // Refresh above
|
||||
refreshEventRoles(timelineBaseIndex() + 1, {ReadMarkerRole});
|
||||
if (timelineBaseIndex() > 0) // Refresh below, see #312
|
||||
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::readMarkerMoved, this, [this] {
|
||||
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::updatedEvent, this,
|
||||
[this](const QString& eventId) {
|
||||
if (eventId.isEmpty()) { // How did we get here?
|
||||
movingEvent = true;
|
||||
// Reverse i because row 0 is bottommost in the model
|
||||
const auto row = timelineBaseIndex() - i - 1;
|
||||
Q_ASSERT(beginMoveRows({}, row, row, {}, timelineBaseIndex()));
|
||||
});
|
||||
connect(m_currentRoom, &Room::pendingEventMerged, this, [this] {
|
||||
if (movingEvent) {
|
||||
endMoveRows();
|
||||
movingEvent = false;
|
||||
}
|
||||
refreshRow(timelineBaseIndex()); // Refresh the looks
|
||||
refreshLastUserEvents(0);
|
||||
if (m_currentRoom->timelineSize() > 1) // Refresh above
|
||||
refreshEventRoles(timelineBaseIndex() + 1, {ReadMarkerRole});
|
||||
if (timelineBaseIndex() > 0) // Refresh below, see #312
|
||||
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::readMarkerMoved, this, [this] {
|
||||
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::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) {
|
||||
refreshEventRoles(fromEventId, {UserMarkerRole});
|
||||
refreshEventRoles(toEventId, {UserMarkerRole});
|
||||
});
|
||||
connect(m_currentRoom->connection(), &Connection::ignoredUsersListChanged,
|
||||
this, [=] {
|
||||
beginResetModel();
|
||||
endResetModel();
|
||||
});
|
||||
qDebug() << "Connected to room" << room->id() << "as"
|
||||
<< room->localUser()->id();
|
||||
} else
|
||||
lastReadEventId.clear();
|
||||
endResetModel();
|
||||
}
|
||||
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) {
|
||||
refreshEventRoles(fromEventId, {UserMarkerRole});
|
||||
refreshEventRoles(toEventId, {UserMarkerRole});
|
||||
});
|
||||
connect(m_currentRoom->connection(), &Connection::ignoredUsersListChanged, this, [=] {
|
||||
beginResetModel();
|
||||
endResetModel();
|
||||
});
|
||||
qDebug() << "Connected to room" << room->id() << "as" << room->localUser()->id();
|
||||
} else
|
||||
lastReadEventId.clear();
|
||||
endResetModel();
|
||||
}
|
||||
|
||||
int MessageEventModel::refreshEvent(const QString& eventId) {
|
||||
return refreshEventRoles(eventId);
|
||||
int MessageEventModel::refreshEvent(const QString &eventId)
|
||||
{
|
||||
return refreshEventRoles(eventId);
|
||||
}
|
||||
|
||||
void MessageEventModel::refreshRow(int row) {
|
||||
refreshEventRoles(row);
|
||||
void MessageEventModel::refreshRow(int row)
|
||||
{
|
||||
refreshEventRoles(row);
|
||||
}
|
||||
|
||||
int MessageEventModel::timelineBaseIndex() const {
|
||||
return m_currentRoom ? int(m_currentRoom->pendingEvents().size()) : 0;
|
||||
int MessageEventModel::timelineBaseIndex() const
|
||||
{
|
||||
return m_currentRoom ? int(m_currentRoom->pendingEvents().size()) : 0;
|
||||
}
|
||||
|
||||
void MessageEventModel::refreshEventRoles(int row, const QVector<int>& roles) {
|
||||
const auto idx = index(row);
|
||||
emit dataChanged(idx, idx, 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) {
|
||||
// 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;
|
||||
// First try pendingEvents because it is almost always very short.
|
||||
const auto pendingIt = m_currentRoom->findPendingEvent(id);
|
||||
if (pendingIt != m_currentRoom->pendingEvents().end())
|
||||
row = int(pendingIt - m_currentRoom->pendingEvents().begin());
|
||||
else {
|
||||
const auto timelineIt = m_currentRoom->findInTimeline(id);
|
||||
if (timelineIt == m_currentRoom->timelineEdge()) {
|
||||
qWarning() << "Trying to refresh inexistent event:" << id;
|
||||
return -1;
|
||||
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;
|
||||
// First try pendingEvents because it is almost always very short.
|
||||
const auto pendingIt = m_currentRoom->findPendingEvent(id);
|
||||
if (pendingIt != m_currentRoom->pendingEvents().end())
|
||||
row = int(pendingIt - m_currentRoom->pendingEvents().begin());
|
||||
else {
|
||||
const auto timelineIt = m_currentRoom->findInTimeline(id);
|
||||
if (timelineIt == m_currentRoom->timelineEdge()) {
|
||||
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;
|
||||
refreshEventRoles(row, roles);
|
||||
return row;
|
||||
}
|
||||
|
||||
inline bool hasValidTimestamp(const Quotient::TimelineItem& ti) {
|
||||
return ti->originTimestamp().isValid();
|
||||
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();
|
||||
auto ts = baseIt->event()->originTimestamp();
|
||||
if (ts.isValid())
|
||||
return ts;
|
||||
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;
|
||||
|
||||
// The event is most likely redacted or just invalid.
|
||||
// Look for the nearest date around and slap zero time to it.
|
||||
using Quotient::TimelineItem;
|
||||
auto rit = std::find_if(baseIt, timeline.rend(), hasValidTimestamp);
|
||||
if (rit != timeline.rend())
|
||||
return {rit->event()->originTimestamp().date(), {0, 0}, Qt::LocalTime};
|
||||
auto it = std::find_if(baseIt.base(), timeline.end(), hasValidTimestamp);
|
||||
if (it != timeline.end())
|
||||
return {it->event()->originTimestamp().date(), {0, 0}, Qt::LocalTime};
|
||||
// The event is most likely redacted or just invalid.
|
||||
// Look for the nearest date around and slap zero time to it.
|
||||
using Quotient::TimelineItem;
|
||||
auto rit = std::find_if(baseIt, timeline.rend(), hasValidTimestamp);
|
||||
if (rit != timeline.rend())
|
||||
return {rit->event()->originTimestamp().date(), {0, 0}, Qt::LocalTime};
|
||||
auto it = std::find_if(baseIt.base(), timeline.end(), hasValidTimestamp);
|
||||
if (it != timeline.end())
|
||||
return {it->event()->originTimestamp().date(), {0, 0}, Qt::LocalTime};
|
||||
|
||||
// What kind of room is that?..
|
||||
qCritical() << "No valid timestamps in the room timeline!";
|
||||
return {};
|
||||
}
|
||||
|
||||
QString MessageEventModel::renderDate(QDateTime timestamp) const {
|
||||
auto date = timestamp.toLocalTime().date();
|
||||
if (date == QDate::currentDate())
|
||||
return tr("Today");
|
||||
if (date == QDate::currentDate().addDays(-1))
|
||||
return tr("Yesterday");
|
||||
if (date == QDate::currentDate().addDays(-2))
|
||||
return tr("The day before yesterday");
|
||||
if (date > QDate::currentDate().addDays(-7))
|
||||
return date.toString("dddd");
|
||||
|
||||
return QLocale::system().toString(date, QLocale::ShortFormat);
|
||||
}
|
||||
|
||||
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) {
|
||||
if ((*it)->senderId() == lastSender) {
|
||||
auto idx = index(it - timelineBottom);
|
||||
emit dataChanged(idx, idx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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{
|
||||
{"isLocalUser", user->id() == room->localUser()->id()},
|
||||
{"id", user->id()},
|
||||
{"avatarMediaId", user->avatarMediaId(room)},
|
||||
{"avatarUrl", user->avatarUrl(room)},
|
||||
{"displayName", user->displayname(room)},
|
||||
{"color", user->color()},
|
||||
{"object", QVariant::fromValue(user)},
|
||||
};
|
||||
}
|
||||
|
||||
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())
|
||||
// What kind of room is that?..
|
||||
qCritical() << "No valid timestamps in the room timeline!";
|
||||
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;
|
||||
QString MessageEventModel::renderDate(QDateTime timestamp) const
|
||||
{
|
||||
auto date = timestamp.toLocalTime().date();
|
||||
if (date == QDate::currentDate())
|
||||
return tr("Today");
|
||||
if (date == QDate::currentDate().addDays(-1))
|
||||
return tr("Yesterday");
|
||||
if (date == QDate::currentDate().addDays(-2))
|
||||
return tr("The day before yesterday");
|
||||
if (date > QDate::currentDate().addDays(-7))
|
||||
return date.toString("dddd");
|
||||
|
||||
if (role == Qt::DisplayRole) {
|
||||
return m_currentRoom->eventToString(evt, Qt::RichText);
|
||||
}
|
||||
return QLocale::system().toString(date, QLocale::ShortFormat);
|
||||
}
|
||||
|
||||
if (role == MessageRole) {
|
||||
return m_currentRoom->eventToString(evt);
|
||||
}
|
||||
void MessageEventModel::refreshLastUserEvents(int baseTimelineRow)
|
||||
{
|
||||
if (!m_currentRoom || m_currentRoom->timelineSize() <= baseTimelineRow)
|
||||
return;
|
||||
|
||||
if (role == Qt::ToolTipRole) {
|
||||
return evt.originalJson();
|
||||
}
|
||||
|
||||
if (role == EventTypeRole) {
|
||||
if (auto e = eventCast<const RoomMessageEvent>(&evt)) {
|
||||
switch (e->msgtype()) {
|
||||
case MessageEventType::Emote:
|
||||
return "emote";
|
||||
case MessageEventType::Notice:
|
||||
return "notice";
|
||||
case MessageEventType::Image:
|
||||
return "image";
|
||||
case MessageEventType::Audio:
|
||||
return "audio";
|
||||
case MessageEventType::Video:
|
||||
return "video";
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (e->hasFileContent()) {
|
||||
return "file";
|
||||
}
|
||||
|
||||
return "message";
|
||||
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);
|
||||
}
|
||||
}
|
||||
if (evt.isStateEvent())
|
||||
return "state";
|
||||
}
|
||||
|
||||
return "other";
|
||||
}
|
||||
int MessageEventModel::rowCount(const QModelIndex &parent) const
|
||||
{
|
||||
if (!m_currentRoom || parent.isValid())
|
||||
return 0;
|
||||
return m_currentRoom->timelineSize();
|
||||
}
|
||||
|
||||
if (role == EventResolvedTypeRole)
|
||||
return EventTypeRegistry::getMatrixType(evt.type());
|
||||
|
||||
if (role == AuthorRole) {
|
||||
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;
|
||||
}
|
||||
return QStringLiteral("text/plain");
|
||||
}
|
||||
|
||||
if (role == ContentRole) {
|
||||
if (evt.isRedacted()) {
|
||||
auto reason = 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();
|
||||
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)},
|
||||
{"avatarUrl", user->avatarUrl(room)},
|
||||
{"displayName", user->displayname(room)},
|
||||
{"color", user->color()},
|
||||
{"object", QVariant::fromValue(user)},
|
||||
};
|
||||
}
|
||||
|
||||
if (role == HighlightRole)
|
||||
return m_currentRoom->isEventHighlighted(&evt);
|
||||
|
||||
if (role == ReadMarkerRole)
|
||||
return evt.id() == lastReadEventId && row > timelineBaseIndex();
|
||||
|
||||
if (role == SpecialMarksRole) {
|
||||
if (isPending)
|
||||
return pendingIt->deliveryStatus();
|
||||
|
||||
auto* memberEvent = timelineIt->viewAs<RoomMemberEvent>();
|
||||
if (memberEvent) {
|
||||
if ((memberEvent->isJoin() || memberEvent->isLeave()) &&
|
||||
!Settings().value("UI/show_joinleave", true).toBool())
|
||||
return EventStatus::Hidden;
|
||||
}
|
||||
|
||||
if (is<RedactionEvent>(evt) || is<ReactionEvent>(evt))
|
||||
return EventStatus::Hidden;
|
||||
if (evt.isRedacted())
|
||||
return EventStatus::Hidden;
|
||||
|
||||
if (evt.isStateEvent() &&
|
||||
static_cast<const StateEventBase&>(evt).repeatsState())
|
||||
return EventStatus::Hidden;
|
||||
|
||||
if (auto e = eventCast<const RoomMessageEvent>(&evt)) {
|
||||
if (!e->replacedEvent().isEmpty() && e->replacedEvent() != e->id()) {
|
||||
return EventStatus::Hidden;
|
||||
}
|
||||
}
|
||||
|
||||
if (m_currentRoom->connection()->isIgnored(
|
||||
m_currentRoom->user(evt.senderId())))
|
||||
return EventStatus::Hidden;
|
||||
|
||||
return EventStatus::Normal;
|
||||
}
|
||||
|
||||
if (role == EventIdRole)
|
||||
return !evt.id().isEmpty() ? evt.id() : evt.transactionId();
|
||||
|
||||
if (role == LongOperationRole) {
|
||||
if (auto e = eventCast<const RoomMessageEvent>(&evt))
|
||||
if (e->hasFileContent())
|
||||
return QVariant::fromValue(m_currentRoom->fileTransferInfo(e->id()));
|
||||
}
|
||||
|
||||
if (role == AnnotationRole)
|
||||
if (isPending)
|
||||
return pendingIt->annotation();
|
||||
|
||||
if (role == TimeRole || role == SectionRole) {
|
||||
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())) {
|
||||
if (user == m_currentRoom->localUser())
|
||||
continue;
|
||||
variantList.append(QVariant::fromValue(user));
|
||||
}
|
||||
return variantList;
|
||||
}
|
||||
|
||||
if (role == ReplyRole) {
|
||||
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;
|
||||
|
||||
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 true;
|
||||
}
|
||||
|
||||
if (role == ShowSectionRole) {
|
||||
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 true;
|
||||
}
|
||||
|
||||
if (role == ReactionRole) {
|
||||
const auto& annotations =
|
||||
m_currentRoom->relatedEvents(evt, EventRelation::Annotation());
|
||||
if (annotations.isEmpty())
|
||||
return {};
|
||||
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())));
|
||||
}
|
||||
|
||||
if (reactions.isEmpty()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
QVariantList res = {};
|
||||
auto i = reactions.constBegin();
|
||||
while (i != reactions.constEnd()) {
|
||||
QVariantList authors;
|
||||
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}});
|
||||
++i;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
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;
|
||||
return -1;
|
||||
}
|
||||
return it - m_currentRoom->messageEvents().rbegin() + timelineBaseIndex();
|
||||
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())
|
||||
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;
|
||||
|
||||
if (role == Qt::DisplayRole) {
|
||||
return m_currentRoom->eventToString(evt, Qt::RichText);
|
||||
}
|
||||
|
||||
if (role == MessageRole) {
|
||||
return m_currentRoom->eventToString(evt);
|
||||
}
|
||||
|
||||
if (role == Qt::ToolTipRole) {
|
||||
return evt.originalJson();
|
||||
}
|
||||
|
||||
if (role == EventTypeRole) {
|
||||
if (auto e = eventCast<const RoomMessageEvent>(&evt)) {
|
||||
switch (e->msgtype()) {
|
||||
case MessageEventType::Emote:
|
||||
return "emote";
|
||||
case MessageEventType::Notice:
|
||||
return "notice";
|
||||
case MessageEventType::Image:
|
||||
return "image";
|
||||
case MessageEventType::Audio:
|
||||
return "audio";
|
||||
case MessageEventType::Video:
|
||||
return "video";
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (e->hasFileContent()) {
|
||||
return "file";
|
||||
}
|
||||
|
||||
return "message";
|
||||
}
|
||||
if (evt.isStateEvent())
|
||||
return "state";
|
||||
|
||||
return "other";
|
||||
}
|
||||
|
||||
if (role == EventResolvedTypeRole)
|
||||
return EventTypeRegistry::getMatrixType(evt.type());
|
||||
|
||||
if (role == AuthorRole) {
|
||||
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;
|
||||
}
|
||||
return QStringLiteral("text/plain");
|
||||
}
|
||||
|
||||
if (role == ContentRole) {
|
||||
if (evt.isRedacted()) {
|
||||
auto reason = 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();
|
||||
};
|
||||
}
|
||||
|
||||
if (role == HighlightRole)
|
||||
return m_currentRoom->isEventHighlighted(&evt);
|
||||
|
||||
if (role == ReadMarkerRole)
|
||||
return evt.id() == lastReadEventId && row > timelineBaseIndex();
|
||||
|
||||
if (role == SpecialMarksRole) {
|
||||
if (isPending)
|
||||
return pendingIt->deliveryStatus();
|
||||
|
||||
auto *memberEvent = timelineIt->viewAs<RoomMemberEvent>();
|
||||
if (memberEvent) {
|
||||
if ((memberEvent->isJoin() || memberEvent->isLeave()) && !Settings().value("UI/show_joinleave", true).toBool())
|
||||
return EventStatus::Hidden;
|
||||
}
|
||||
|
||||
if (is<RedactionEvent>(evt) || is<ReactionEvent>(evt))
|
||||
return EventStatus::Hidden;
|
||||
if (evt.isRedacted())
|
||||
return EventStatus::Hidden;
|
||||
|
||||
if (evt.isStateEvent() && static_cast<const StateEventBase &>(evt).repeatsState())
|
||||
return EventStatus::Hidden;
|
||||
|
||||
if (auto e = eventCast<const RoomMessageEvent>(&evt)) {
|
||||
if (!e->replacedEvent().isEmpty() && e->replacedEvent() != e->id()) {
|
||||
return EventStatus::Hidden;
|
||||
}
|
||||
}
|
||||
|
||||
if (m_currentRoom->connection()->isIgnored(m_currentRoom->user(evt.senderId())))
|
||||
return EventStatus::Hidden;
|
||||
|
||||
return EventStatus::Normal;
|
||||
}
|
||||
|
||||
if (role == EventIdRole)
|
||||
return !evt.id().isEmpty() ? evt.id() : evt.transactionId();
|
||||
|
||||
if (role == LongOperationRole) {
|
||||
if (auto e = eventCast<const RoomMessageEvent>(&evt))
|
||||
if (e->hasFileContent())
|
||||
return QVariant::fromValue(m_currentRoom->fileTransferInfo(e->id()));
|
||||
}
|
||||
|
||||
if (role == AnnotationRole)
|
||||
if (isPending)
|
||||
return pendingIt->annotation();
|
||||
|
||||
if (role == TimeRole || role == SectionRole) {
|
||||
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())) {
|
||||
if (user == m_currentRoom->localUser())
|
||||
continue;
|
||||
variantList.append(QVariant::fromValue(user));
|
||||
}
|
||||
return variantList;
|
||||
}
|
||||
|
||||
if (role == ReplyRole) {
|
||||
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;
|
||||
|
||||
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 true;
|
||||
}
|
||||
|
||||
if (role == ShowSectionRole) {
|
||||
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 true;
|
||||
}
|
||||
|
||||
if (role == ReactionRole) {
|
||||
const auto &annotations = m_currentRoom->relatedEvents(evt, EventRelation::Annotation());
|
||||
if (annotations.isEmpty())
|
||||
return {};
|
||||
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())));
|
||||
}
|
||||
|
||||
if (reactions.isEmpty()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
QVariantList res = {};
|
||||
auto i = reactions.constBegin();
|
||||
while (i != reactions.constEnd()) {
|
||||
QVariantList authors;
|
||||
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}});
|
||||
++i;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
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;
|
||||
return -1;
|
||||
}
|
||||
return it - m_currentRoom->messageEvents().rbegin() + timelineBaseIndex();
|
||||
}
|
||||
|
||||
@@ -6,80 +6,82 @@
|
||||
#include "room.h"
|
||||
#include "spectralroom.h"
|
||||
|
||||
class MessageEventModel : public QAbstractListModel {
|
||||
Q_OBJECT
|
||||
Q_PROPERTY(SpectralRoom* room READ room WRITE setRoom NOTIFY roomChanged)
|
||||
class MessageEventModel : public QAbstractListModel
|
||||
{
|
||||
Q_OBJECT
|
||||
Q_PROPERTY(SpectralRoom *room READ room WRITE setRoom NOTIFY roomChanged)
|
||||
|
||||
public:
|
||||
enum EventRoles {
|
||||
EventTypeRole = Qt::UserRole + 1,
|
||||
MessageRole,
|
||||
EventIdRole,
|
||||
TimeRole,
|
||||
SectionRole,
|
||||
AuthorRole,
|
||||
ContentRole,
|
||||
ContentTypeRole,
|
||||
HighlightRole,
|
||||
ReadMarkerRole,
|
||||
SpecialMarksRole,
|
||||
LongOperationRole,
|
||||
AnnotationRole,
|
||||
UserMarkerRole,
|
||||
public:
|
||||
enum EventRoles {
|
||||
EventTypeRole = Qt::UserRole + 1,
|
||||
MessageRole,
|
||||
EventIdRole,
|
||||
TimeRole,
|
||||
SectionRole,
|
||||
AuthorRole,
|
||||
ContentRole,
|
||||
ContentTypeRole,
|
||||
HighlightRole,
|
||||
ReadMarkerRole,
|
||||
SpecialMarksRole,
|
||||
LongOperationRole,
|
||||
AnnotationRole,
|
||||
UserMarkerRole,
|
||||
|
||||
ReplyRole,
|
||||
ReplyRole,
|
||||
|
||||
ShowAuthorRole,
|
||||
ShowSectionRole,
|
||||
ShowAuthorRole,
|
||||
ShowSectionRole,
|
||||
|
||||
ReactionRole,
|
||||
ReactionRole,
|
||||
|
||||
// For debugging
|
||||
EventResolvedTypeRole,
|
||||
};
|
||||
Q_ENUM(EventRoles)
|
||||
// For debugging
|
||||
EventResolvedTypeRole,
|
||||
};
|
||||
Q_ENUM(EventRoles)
|
||||
|
||||
enum BubbleShapes {
|
||||
NoShape = 0,
|
||||
BeginShape,
|
||||
MiddleShape,
|
||||
EndShape,
|
||||
};
|
||||
enum BubbleShapes {
|
||||
NoShape = 0,
|
||||
BeginShape,
|
||||
MiddleShape,
|
||||
EndShape,
|
||||
};
|
||||
|
||||
explicit MessageEventModel(QObject* parent = nullptr);
|
||||
~MessageEventModel() override;
|
||||
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;
|
||||
QHash<int, QByteArray> roleNames() 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);
|
||||
void refreshRow(int row);
|
||||
private slots:
|
||||
int refreshEvent(const QString &eventId);
|
||||
void refreshRow(int row);
|
||||
|
||||
private:
|
||||
SpectralRoom* m_currentRoom = nullptr;
|
||||
QString lastReadEventId;
|
||||
int rowBelowInserted = -1;
|
||||
bool movingEvent = 0;
|
||||
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;
|
||||
QString renderDate(QDateTime timestamp) const;
|
||||
int timelineBaseIndex() 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 refreshLastUserEvents(int baseRow);
|
||||
void refreshEventRoles(int row, const QVector<int> &roles = {});
|
||||
int refreshEventRoles(const QString &eventId, const QVector<int> &roles = {});
|
||||
|
||||
signals:
|
||||
void roomChanged();
|
||||
signals:
|
||||
void roomChanged();
|
||||
};
|
||||
|
||||
#endif // MESSAGEEVENTMODEL_H
|
||||
#endif // MESSAGEEVENTMODEL_H
|
||||
|
||||
@@ -12,45 +12,39 @@
|
||||
#endif
|
||||
|
||||
struct roomEventId {
|
||||
QString roomId;
|
||||
QString eventId;
|
||||
QString roomId;
|
||||
QString eventId;
|
||||
};
|
||||
|
||||
class NotificationsManager : public QObject {
|
||||
Q_OBJECT
|
||||
public:
|
||||
NotificationsManager(QObject* parent = nullptr);
|
||||
class NotificationsManager : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
NotificationsManager(QObject *parent = nullptr);
|
||||
|
||||
signals:
|
||||
void notificationClicked(const QString roomId, const QString eventId);
|
||||
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);
|
||||
QDBusInterface dbus;
|
||||
bool serverSupportsHtml = false;
|
||||
uint showNotification(const QString summary, const QString text, const QImage image);
|
||||
#endif
|
||||
|
||||
// notification ID to (room ID, event ID)
|
||||
QMap<uint, roomEventId> notificationIds;
|
||||
// notification ID to (room ID, event ID)
|
||||
QMap<uint, roomEventId> notificationIds;
|
||||
|
||||
// these slots are platform specific (D-Bus only)
|
||||
// but Qt slot declarations can not be inside an ifdef!
|
||||
public slots:
|
||||
void actionInvoked(uint id, QString action);
|
||||
void notificationClosed(uint id, uint reason);
|
||||
// these slots are platform specific (D-Bus only)
|
||||
// but Qt slot declarations can not be inside an ifdef!
|
||||
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
|
||||
|
||||
@@ -8,36 +8,28 @@
|
||||
#include <QtDBus/QDBusReply>
|
||||
|
||||
NotificationsManager::NotificationsManager(QObject *parent)
|
||||
: QObject(parent),
|
||||
dbus("org.freedesktop.Notifications", "/org/freedesktop/Notifications",
|
||||
"org.freedesktop.Notifications", QDBusConnection::sessionBus(),
|
||||
this) {
|
||||
qDBusRegisterMetaType<QImage>();
|
||||
: QObject(parent)
|
||||
, dbus("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications", QDBusConnection::sessionBus(), this)
|
||||
{
|
||||
qDBusRegisterMetaType<QImage>();
|
||||
|
||||
const QDBusReply<QStringList> capabilitiesReply = dbus.call("GetCapabilities");
|
||||
const QDBusReply<QStringList> capabilitiesReply = dbus.call("GetCapabilities");
|
||||
|
||||
if (capabilitiesReply.isValid()) {
|
||||
const QStringList capabilities = capabilitiesReply.value();
|
||||
serverSupportsHtml = capabilities.contains("body-markup");
|
||||
} else {
|
||||
qWarning() << "Could not get notification server capabilities" << capabilitiesReply.error();
|
||||
}
|
||||
if (capabilitiesReply.isValid()) {
|
||||
const QStringList capabilities = capabilitiesReply.value();
|
||||
serverSupportsHtml = capabilities.contains("body-markup");
|
||||
} else {
|
||||
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) {
|
||||
uint id = showNotification(sender + " (" + roomname + ")", text, icon);
|
||||
notificationIds[id] = roomEventId{roomid, eventid};
|
||||
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};
|
||||
}
|
||||
/**
|
||||
* This function is based on code from
|
||||
@@ -45,63 +37,59 @@ 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) {
|
||||
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());
|
||||
croppedImage = image.copy(crop);
|
||||
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());
|
||||
croppedImage = image.copy(crop);
|
||||
} else {
|
||||
QRect crop(0, (rect.height() - rect.width()) / 2, rect.width(), rect.width());
|
||||
croppedImage = image.copy(crop);
|
||||
}
|
||||
} else {
|
||||
QRect crop(0, (rect.height() - rect.width()) / 2, rect.width(),
|
||||
rect.width());
|
||||
croppedImage = image.copy(crop);
|
||||
croppedImage = image;
|
||||
}
|
||||
} else {
|
||||
croppedImage = image;
|
||||
}
|
||||
|
||||
const QString body = serverSupportsHtml ? text.toHtmlEscaped() : text;
|
||||
const QString body = serverSupportsHtml ? text.toHtmlEscaped() : text;
|
||||
|
||||
QVariantMap hints;
|
||||
hints["image-data"] = croppedImage;
|
||||
hints["desktop-entry"] = "org.eu.encom.spectral";
|
||||
QList<QVariant> argumentList;
|
||||
argumentList << "Spectral"; // app_name
|
||||
argumentList << uint(0); // replace_id
|
||||
argumentList << ""; // app_icon
|
||||
argumentList << summary; // summary
|
||||
argumentList << body; // body
|
||||
argumentList << (QStringList("default") << "reply"); // actions
|
||||
argumentList << hints; // hints
|
||||
argumentList << int(-1); // timeout in ms
|
||||
QVariantMap hints;
|
||||
hints["image-data"] = croppedImage;
|
||||
hints["desktop-entry"] = "org.eu.encom.spectral";
|
||||
QList<QVariant> argumentList;
|
||||
argumentList << "Spectral"; // app_name
|
||||
argumentList << uint(0); // replace_id
|
||||
argumentList << ""; // app_icon
|
||||
argumentList << summary; // summary
|
||||
argumentList << body; // body
|
||||
argumentList << (QStringList("default") << "reply"); // actions
|
||||
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);
|
||||
if (reply.type() == QDBusMessage::ErrorMessage) {
|
||||
qDebug() << "D-Bus Error:" << reply.errorMessage();
|
||||
return 0;
|
||||
} else {
|
||||
return reply.arguments().first().toUInt();
|
||||
}
|
||||
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;
|
||||
} else {
|
||||
return reply.arguments().first().toUInt();
|
||||
}
|
||||
}
|
||||
|
||||
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::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) {
|
||||
Q_UNUSED(reason);
|
||||
notificationIds.remove(id);
|
||||
void NotificationsManager::notificationClosed(uint id, uint reason)
|
||||
{
|
||||
Q_UNUSED(reason);
|
||||
notificationIds.remove(id);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -113,50 +101,52 @@ void NotificationsManager::notificationClosed(uint id, uint reason) {
|
||||
*
|
||||
* Copyright 2010, David Sansome <me@davidsansome.com>
|
||||
*/
|
||||
QDBusArgument &operator<<(QDBusArgument &arg, const QImage &image) {
|
||||
if (image.isNull()) {
|
||||
arg.beginStructure();
|
||||
arg << 0 << 0 << 0 << false << 0 << 0 << QByteArray();
|
||||
arg.endStructure();
|
||||
return arg;
|
||||
}
|
||||
QDBusArgument &operator<<(QDBusArgument &arg, const QImage &image)
|
||||
{
|
||||
if (image.isNull()) {
|
||||
arg.beginStructure();
|
||||
arg << 0 << 0 << 0 << false << 0 << 0 << QByteArray();
|
||||
arg.endStructure();
|
||||
return arg;
|
||||
}
|
||||
|
||||
QImage scaled = image.scaledToHeight(100, Qt::SmoothTransformation);
|
||||
scaled = scaled.convertToFormat(QImage::Format_ARGB32);
|
||||
QImage scaled = image.scaledToHeight(100, Qt::SmoothTransformation);
|
||||
scaled = scaled.convertToFormat(QImage::Format_ARGB32);
|
||||
|
||||
#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
|
||||
// ABGR -> ARGB
|
||||
QImage i = scaled.rgbSwapped();
|
||||
// ABGR -> ARGB
|
||||
QImage i = scaled.rgbSwapped();
|
||||
#else
|
||||
// ABGR -> GBAR
|
||||
QImage i(scaled.size(), scaled.format());
|
||||
for (int y = 0; y < i.height(); ++y) {
|
||||
QRgb *p = (QRgb *)scaled.scanLine(y);
|
||||
QRgb *q = (QRgb *)i.scanLine(y);
|
||||
QRgb *end = p + scaled.width();
|
||||
while (p < end) {
|
||||
*q = qRgba(qGreen(*p), qBlue(*p), qAlpha(*p), qRed(*p));
|
||||
p++;
|
||||
q++;
|
||||
// ABGR -> GBAR
|
||||
QImage i(scaled.size(), scaled.format());
|
||||
for (int y = 0; y < i.height(); ++y) {
|
||||
QRgb *p = (QRgb *)scaled.scanLine(y);
|
||||
QRgb *q = (QRgb *)i.scanLine(y);
|
||||
QRgb *end = p + scaled.width();
|
||||
while (p < end) {
|
||||
*q = qRgba(qGreen(*p), qBlue(*p), qAlpha(*p), qRed(*p));
|
||||
p++;
|
||||
q++;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
arg.beginStructure();
|
||||
arg << i.width();
|
||||
arg << i.height();
|
||||
arg << i.bytesPerLine();
|
||||
arg << i.hasAlphaChannel();
|
||||
int channels = i.isGrayscale() ? 1 : (i.hasAlphaChannel() ? 4 : 3);
|
||||
arg << i.depth() / channels;
|
||||
arg << channels;
|
||||
arg << QByteArray(reinterpret_cast<const char *>(i.bits()), i.sizeInBytes());
|
||||
arg.endStructure();
|
||||
return arg;
|
||||
arg.beginStructure();
|
||||
arg << i.width();
|
||||
arg << i.height();
|
||||
arg << i.bytesPerLine();
|
||||
arg << i.hasAlphaChannel();
|
||||
int channels = i.isGrayscale() ? 1 : (i.hasAlphaChannel() ? 4 : 3);
|
||||
arg << i.depth() / channels;
|
||||
arg << channels;
|
||||
arg << QByteArray(reinterpret_cast<const char *>(i.bits()), i.sizeInBytes());
|
||||
arg.endStructure();
|
||||
return arg;
|
||||
}
|
||||
|
||||
const QDBusArgument &operator>>(const QDBusArgument &arg, QImage &) {
|
||||
// This is needed to link but shouldn't be called.
|
||||
Q_ASSERT(0);
|
||||
return arg;
|
||||
const QDBusArgument &operator>>(const QDBusArgument &arg, QImage &)
|
||||
{
|
||||
// This is needed to link but shouldn't be called.
|
||||
Q_ASSERT(0);
|
||||
return arg;
|
||||
}
|
||||
|
||||
@@ -5,79 +5,89 @@
|
||||
|
||||
using namespace WinToastLib;
|
||||
|
||||
class CustomHandler : public IWinToastHandler {
|
||||
public:
|
||||
CustomHandler(uint id, NotificationsManager *parent)
|
||||
: notificationID(id), notificationsManager(parent) {}
|
||||
void toastActivated() {
|
||||
notificationsManager->actionInvoked(notificationID, "");
|
||||
}
|
||||
void toastActivated(int) {
|
||||
notificationsManager->actionInvoked(notificationID, "");
|
||||
}
|
||||
void toastFailed() {
|
||||
std::wcout << L"Error showing current toast" << std::endl;
|
||||
}
|
||||
void toastDismissed(WinToastDismissalReason) {
|
||||
notificationsManager->notificationClosed(notificationID, 0);
|
||||
}
|
||||
class CustomHandler : public IWinToastHandler
|
||||
{
|
||||
public:
|
||||
CustomHandler(uint id, NotificationsManager *parent)
|
||||
: notificationID(id)
|
||||
, notificationsManager(parent)
|
||||
{
|
||||
}
|
||||
void toastActivated()
|
||||
{
|
||||
notificationsManager->actionInvoked(notificationID, "");
|
||||
}
|
||||
void toastActivated(int)
|
||||
{
|
||||
notificationsManager->actionInvoked(notificationID, "");
|
||||
}
|
||||
void toastFailed()
|
||||
{
|
||||
std::wcout << L"Error showing current toast" << std::endl;
|
||||
}
|
||||
void toastDismissed(WinToastDismissalReason)
|
||||
{
|
||||
notificationsManager->notificationClosed(notificationID, 0);
|
||||
}
|
||||
|
||||
private:
|
||||
uint notificationID;
|
||||
NotificationsManager *notificationsManager;
|
||||
private:
|
||||
uint notificationID;
|
||||
NotificationsManager *notificationsManager;
|
||||
};
|
||||
|
||||
namespace {
|
||||
namespace
|
||||
{
|
||||
bool isInitialized = false;
|
||||
uint count = 0;
|
||||
|
||||
void init() {
|
||||
isInitialized = true;
|
||||
void init()
|
||||
{
|
||||
isInitialized = true;
|
||||
|
||||
WinToast::instance()->setAppName(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";
|
||||
WinToast::instance()->setAppName(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
|
||||
} // namespace
|
||||
|
||||
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) {
|
||||
Q_UNUSED(room_id)
|
||||
Q_UNUSED(event_id)
|
||||
Q_UNUSED(icon)
|
||||
|
||||
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);
|
||||
else
|
||||
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};
|
||||
|
||||
WinToast::instance()->showToast(templ, customHandler);
|
||||
NotificationsManager::NotificationsManager(QObject *parent)
|
||||
: QObject(parent)
|
||||
{
|
||||
}
|
||||
|
||||
void NotificationsManager::actionInvoked(uint id, QString action) {
|
||||
if (notificationIds.contains(id)) {
|
||||
roomEventId idEntry = notificationIds[id];
|
||||
emit notificationClicked(idEntry.roomId, idEntry.eventId);
|
||||
}
|
||||
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();
|
||||
|
||||
auto templ = WinToastTemplate(WinToastTemplate::ImageAndText02);
|
||||
if (room_name != sender)
|
||||
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);
|
||||
|
||||
count++;
|
||||
CustomHandler *customHandler = new CustomHandler(count, this);
|
||||
notificationIds[count] = roomEventId {room_id, event_id};
|
||||
|
||||
WinToast::instance()->showToast(templ, customHandler);
|
||||
}
|
||||
|
||||
void NotificationsManager::notificationClosed(uint id, uint reason) {
|
||||
notificationIds.remove(id);
|
||||
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)
|
||||
{
|
||||
notificationIds.remove(id);
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,164 +1,156 @@
|
||||
#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;
|
||||
using namespace ABI::Windows::UI::Notifications;
|
||||
using namespace Windows::Foundation;
|
||||
|
||||
#define DEFAULT_SHELL_LINKS_PATH L"\\Microsoft\\Windows\\Start Menu\\Programs\\"
|
||||
#define DEFAULT_LINK_FORMAT L".lnk"
|
||||
namespace WinToastLib {
|
||||
#define DEFAULT_SHELL_LINKS_PATH L"\\Microsoft\\Windows\\Start Menu\\Programs\\"
|
||||
#define DEFAULT_LINK_FORMAT L".lnk"
|
||||
namespace WinToastLib
|
||||
{
|
||||
class IWinToastHandler
|
||||
{
|
||||
public:
|
||||
enum WinToastDismissalReason {
|
||||
UserCanceled = ToastDismissalReason::ToastDismissalReason_UserCanceled,
|
||||
ApplicationHidden = ToastDismissalReason::ToastDismissalReason_ApplicationHidden,
|
||||
TimedOut = ToastDismissalReason::ToastDismissalReason_TimedOut
|
||||
};
|
||||
virtual ~IWinToastHandler()
|
||||
{
|
||||
}
|
||||
virtual void toastActivated() = 0;
|
||||
virtual void toastActivated(int actionIndex) = 0;
|
||||
virtual void toastDismissed(WinToastDismissalReason state) = 0;
|
||||
virtual void toastFailed() = 0;
|
||||
};
|
||||
|
||||
class IWinToastHandler {
|
||||
public:
|
||||
enum WinToastDismissalReason {
|
||||
UserCanceled = ToastDismissalReason::ToastDismissalReason_UserCanceled,
|
||||
ApplicationHidden = ToastDismissalReason::ToastDismissalReason_ApplicationHidden,
|
||||
TimedOut = ToastDismissalReason::ToastDismissalReason_TimedOut
|
||||
};
|
||||
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:
|
||||
enum Duration { System, Short, Long };
|
||||
enum AudioOption { Default = 0, Silent = 1, Loop = 2 };
|
||||
enum TextField { FirstLine = 0, SecondLine, ThirdLine };
|
||||
enum WinToastTemplateType {
|
||||
ImageAndText01 = ToastTemplateType::ToastTemplateType_ToastImageAndText01,
|
||||
ImageAndText02 = ToastTemplateType::ToastTemplateType_ToastImageAndText02,
|
||||
ImageAndText03 = ToastTemplateType::ToastTemplateType_ToastImageAndText03,
|
||||
ImageAndText04 = ToastTemplateType::ToastTemplateType_ToastImageAndText04,
|
||||
Text01 = ToastTemplateType::ToastTemplateType_ToastText01,
|
||||
Text02 = ToastTemplateType::ToastTemplateType_ToastText02,
|
||||
Text03 = ToastTemplateType::ToastTemplateType_ToastText03,
|
||||
Text04 = ToastTemplateType::ToastTemplateType_ToastText04,
|
||||
WinToastTemplateTypeCount
|
||||
};
|
||||
|
||||
class WinToastTemplate {
|
||||
public:
|
||||
enum Duration { System, Short, Long };
|
||||
enum AudioOption { Default = 0, Silent = 1, Loop = 2 };
|
||||
enum TextField { FirstLine = 0, SecondLine, ThirdLine };
|
||||
enum WinToastTemplateType {
|
||||
ImageAndText01 = ToastTemplateType::ToastTemplateType_ToastImageAndText01,
|
||||
ImageAndText02 = ToastTemplateType::ToastTemplateType_ToastImageAndText02,
|
||||
ImageAndText03 = ToastTemplateType::ToastTemplateType_ToastImageAndText03,
|
||||
ImageAndText04 = ToastTemplateType::ToastTemplateType_ToastImageAndText04,
|
||||
Text01 = ToastTemplateType::ToastTemplateType_ToastText01,
|
||||
Text02 = ToastTemplateType::ToastTemplateType_ToastText02,
|
||||
Text03 = ToastTemplateType::ToastTemplateType_ToastText03,
|
||||
Text04 = ToastTemplateType::ToastTemplateType_ToastText04,
|
||||
WinToastTemplateTypeCount
|
||||
};
|
||||
WinToastTemplate(_In_ WinToastTemplateType type = WinToastTemplateType::ImageAndText02);
|
||||
~WinToastTemplate();
|
||||
|
||||
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 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;
|
||||
INT64 expiration() const;
|
||||
WinToastTemplateType type() const;
|
||||
WinToastTemplate::AudioOption audioOption() const;
|
||||
Duration duration() const;
|
||||
|
||||
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;
|
||||
INT64 expiration() const;
|
||||
WinToastTemplateType type() const;
|
||||
WinToastTemplate::AudioOption audioOption() const;
|
||||
Duration duration() const;
|
||||
private:
|
||||
std::vector<std::wstring> _textFields;
|
||||
std::vector<std::wstring> _actions;
|
||||
std::wstring _imagePath = L"";
|
||||
std::wstring _audioPath = L"";
|
||||
std::wstring _attributionText = L"";
|
||||
INT64 _expiration = 0;
|
||||
AudioOption _audioOption = WinToastTemplate::AudioOption::Default;
|
||||
WinToastTemplateType _type = WinToastTemplateType::Text01;
|
||||
Duration _duration = Duration::System;
|
||||
private:
|
||||
std::vector<std::wstring> _textFields;
|
||||
std::vector<std::wstring> _actions;
|
||||
std::wstring _imagePath = L"";
|
||||
std::wstring _audioPath = L"";
|
||||
std::wstring _attributionText = L"";
|
||||
INT64 _expiration = 0;
|
||||
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 };
|
||||
|
||||
enum ShortcutResult {
|
||||
SHORTCUT_UNCHANGED = 0,
|
||||
SHORTCUT_WAS_CHANGED = 1,
|
||||
SHORTCUT_WAS_CREATED = 2,
|
||||
|
||||
SHORTCUT_MISSING_PARAMETERS = -1,
|
||||
SHORTCUT_INCOMPATIBLE_OS = -2,
|
||||
SHORTCUT_COM_INIT_FAILURE = -3,
|
||||
SHORTCUT_CREATE_FAILED = -4
|
||||
};
|
||||
|
||||
class WinToast {
|
||||
public:
|
||||
enum WinToastError {
|
||||
NoError = 0,
|
||||
NotInitialized,
|
||||
SystemNotSupported,
|
||||
ShellLinkNotCreated,
|
||||
InvalidAppUserModelID,
|
||||
InvalidParameters,
|
||||
InvalidHandler,
|
||||
NotDisplayed,
|
||||
UnknownError
|
||||
};
|
||||
WinToast(void);
|
||||
virtual ~WinToast();
|
||||
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);
|
||||
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 void clear();
|
||||
virtual enum ShortcutResult createShortcut();
|
||||
|
||||
enum ShortcutResult {
|
||||
SHORTCUT_UNCHANGED = 0,
|
||||
SHORTCUT_WAS_CHANGED = 1,
|
||||
SHORTCUT_WAS_CREATED = 2,
|
||||
const std::wstring &appName() const;
|
||||
const std::wstring &appUserModelId() const;
|
||||
void setAppUserModelId(_In_ const std::wstring &appName);
|
||||
void setAppName(_In_ const std::wstring &appName);
|
||||
|
||||
SHORTCUT_MISSING_PARAMETERS = -1,
|
||||
SHORTCUT_INCOMPATIBLE_OS = -2,
|
||||
SHORTCUT_COM_INIT_FAILURE = -3,
|
||||
SHORTCUT_CREATE_FAILED = -4
|
||||
};
|
||||
protected:
|
||||
bool _isInitialized;
|
||||
bool _hasCoInitialized;
|
||||
std::wstring _appName;
|
||||
std::wstring _aumi;
|
||||
std::map<INT64, ComPtr<IToastNotification>> _buffer;
|
||||
|
||||
WinToast(void);
|
||||
virtual ~WinToast();
|
||||
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);
|
||||
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 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);
|
||||
|
||||
protected:
|
||||
bool _isInitialized;
|
||||
bool _hasCoInitialized;
|
||||
std::wstring _appName;
|
||||
std::wstring _aumi;
|
||||
std::map<INT64, ComPtr<IToastNotification>> _buffer;
|
||||
|
||||
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 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);
|
||||
};
|
||||
}
|
||||
#endif // WINTOASTLIB_H
|
||||
|
||||
@@ -1,218 +1,226 @@
|
||||
#include "publicroomlistmodel.h"
|
||||
|
||||
PublicRoomListModel::PublicRoomListModel(QObject* parent)
|
||||
: QAbstractListModel(parent) {}
|
||||
|
||||
void PublicRoomListModel::setConnection(Connection* conn) {
|
||||
if (m_connection == conn)
|
||||
return;
|
||||
|
||||
beginResetModel();
|
||||
|
||||
nextBatch = "";
|
||||
attempted = false;
|
||||
rooms.clear();
|
||||
m_server.clear();
|
||||
|
||||
if (m_connection) {
|
||||
m_connection->disconnect(this);
|
||||
}
|
||||
|
||||
endResetModel();
|
||||
|
||||
m_connection = conn;
|
||||
|
||||
if (job) {
|
||||
job->abandon();
|
||||
job = nullptr;
|
||||
}
|
||||
|
||||
if (m_connection) {
|
||||
next();
|
||||
}
|
||||
|
||||
emit connectionChanged();
|
||||
emit serverChanged();
|
||||
emit hasMoreChanged();
|
||||
PublicRoomListModel::PublicRoomListModel(QObject *parent)
|
||||
: QAbstractListModel(parent)
|
||||
{
|
||||
}
|
||||
|
||||
void PublicRoomListModel::setServer(const QString& value) {
|
||||
if (m_server == value)
|
||||
return;
|
||||
void PublicRoomListModel::setConnection(Connection *conn)
|
||||
{
|
||||
if (m_connection == conn)
|
||||
return;
|
||||
|
||||
m_server = value;
|
||||
beginResetModel();
|
||||
|
||||
beginResetModel();
|
||||
nextBatch = "";
|
||||
attempted = false;
|
||||
rooms.clear();
|
||||
m_server.clear();
|
||||
|
||||
nextBatch = "";
|
||||
attempted = false;
|
||||
rooms.clear();
|
||||
|
||||
endResetModel();
|
||||
|
||||
if (job) {
|
||||
job->abandon();
|
||||
job = nullptr;
|
||||
}
|
||||
|
||||
if (m_connection) {
|
||||
next();
|
||||
}
|
||||
|
||||
emit serverChanged();
|
||||
emit hasMoreChanged();
|
||||
}
|
||||
|
||||
void PublicRoomListModel::setKeyword(const QString& value) {
|
||||
if (m_keyword == value)
|
||||
return;
|
||||
|
||||
m_keyword = value;
|
||||
|
||||
beginResetModel();
|
||||
|
||||
nextBatch = "";
|
||||
attempted = false;
|
||||
rooms.clear();
|
||||
|
||||
endResetModel();
|
||||
|
||||
if (job) {
|
||||
job->abandon();
|
||||
job = nullptr;
|
||||
}
|
||||
|
||||
if (m_connection) {
|
||||
next();
|
||||
}
|
||||
|
||||
emit keywordChanged();
|
||||
emit hasMoreChanged();
|
||||
}
|
||||
|
||||
void PublicRoomListModel::next(int count) {
|
||||
if (count < 1)
|
||||
return;
|
||||
|
||||
if (job) {
|
||||
qDebug() << "PublicRoomListModel: Other jobs running, ignore";
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!hasMore())
|
||||
return;
|
||||
|
||||
job = m_connection->callApi<QueryPublicRoomsJob>(
|
||||
m_server, count, nextBatch, QueryPublicRoomsJob::Filter{m_keyword});
|
||||
|
||||
connect(job, &BaseJob::finished, this, [=] {
|
||||
attempted = true;
|
||||
|
||||
if (job->status() == BaseJob::Success) {
|
||||
nextBatch = job->nextBatch();
|
||||
|
||||
this->beginInsertRows({}, rooms.count(),
|
||||
rooms.count() + job->chunk().count() - 1);
|
||||
rooms.append(job->chunk());
|
||||
this->endInsertRows();
|
||||
|
||||
if (job->nextBatch().isEmpty()) {
|
||||
emit hasMoreChanged();
|
||||
}
|
||||
if (m_connection) {
|
||||
m_connection->disconnect(this);
|
||||
}
|
||||
|
||||
this->job = nullptr;
|
||||
});
|
||||
endResetModel();
|
||||
|
||||
m_connection = conn;
|
||||
|
||||
if (job) {
|
||||
job->abandon();
|
||||
job = nullptr;
|
||||
}
|
||||
|
||||
if (m_connection) {
|
||||
next();
|
||||
}
|
||||
|
||||
emit connectionChanged();
|
||||
emit serverChanged();
|
||||
emit hasMoreChanged();
|
||||
}
|
||||
|
||||
QVariant PublicRoomListModel::data(const QModelIndex& index, int role) const {
|
||||
if (!index.isValid())
|
||||
return QVariant();
|
||||
void PublicRoomListModel::setServer(const QString &value)
|
||||
{
|
||||
if (m_server == value)
|
||||
return;
|
||||
|
||||
m_server = value;
|
||||
|
||||
beginResetModel();
|
||||
|
||||
nextBatch = "";
|
||||
attempted = false;
|
||||
rooms.clear();
|
||||
|
||||
endResetModel();
|
||||
|
||||
if (job) {
|
||||
job->abandon();
|
||||
job = nullptr;
|
||||
}
|
||||
|
||||
if (m_connection) {
|
||||
next();
|
||||
}
|
||||
|
||||
emit serverChanged();
|
||||
emit hasMoreChanged();
|
||||
}
|
||||
|
||||
void PublicRoomListModel::setKeyword(const QString &value)
|
||||
{
|
||||
if (m_keyword == value)
|
||||
return;
|
||||
|
||||
m_keyword = value;
|
||||
|
||||
beginResetModel();
|
||||
|
||||
nextBatch = "";
|
||||
attempted = false;
|
||||
rooms.clear();
|
||||
|
||||
endResetModel();
|
||||
|
||||
if (job) {
|
||||
job->abandon();
|
||||
job = nullptr;
|
||||
}
|
||||
|
||||
if (m_connection) {
|
||||
next();
|
||||
}
|
||||
|
||||
emit keywordChanged();
|
||||
emit hasMoreChanged();
|
||||
}
|
||||
|
||||
void PublicRoomListModel::next(int count)
|
||||
{
|
||||
if (count < 1)
|
||||
return;
|
||||
|
||||
if (job) {
|
||||
qDebug() << "PublicRoomListModel: Other jobs running, ignore";
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!hasMore())
|
||||
return;
|
||||
|
||||
job = m_connection->callApi<QueryPublicRoomsJob>(m_server, count, nextBatch, QueryPublicRoomsJob::Filter {m_keyword});
|
||||
|
||||
connect(job, &BaseJob::finished, this, [=] {
|
||||
attempted = true;
|
||||
|
||||
if (job->status() == BaseJob::Success) {
|
||||
nextBatch = job->nextBatch();
|
||||
|
||||
this->beginInsertRows({}, rooms.count(), rooms.count() + job->chunk().count() - 1);
|
||||
rooms.append(job->chunk());
|
||||
this->endInsertRows();
|
||||
|
||||
if (job->nextBatch().isEmpty()) {
|
||||
emit hasMoreChanged();
|
||||
}
|
||||
}
|
||||
|
||||
this->job = nullptr;
|
||||
});
|
||||
}
|
||||
|
||||
QVariant PublicRoomListModel::data(const QModelIndex &index, int role) const
|
||||
{
|
||||
if (!index.isValid())
|
||||
return QVariant();
|
||||
|
||||
if (index.row() >= rooms.count()) {
|
||||
qDebug() << "PublicRoomListModel, something's wrong: index.row() >= "
|
||||
"rooms.count()";
|
||||
return {};
|
||||
}
|
||||
auto room = rooms.at(index.row());
|
||||
if (role == NameRole) {
|
||||
auto displayName = room.name;
|
||||
if (!displayName.isEmpty()) {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
displayName = room.canonicalAlias;
|
||||
if (!displayName.isEmpty()) {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
if (!room.aliases.isEmpty()) {
|
||||
displayName = room.aliases.front();
|
||||
}
|
||||
|
||||
if (!displayName.isEmpty()) {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
return room.roomId;
|
||||
}
|
||||
if (role == AvatarRole) {
|
||||
auto avatarUrl = room.avatarUrl;
|
||||
|
||||
if (avatarUrl.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return avatarUrl.remove(0, 6);
|
||||
}
|
||||
if (role == TopicRole) {
|
||||
return room.topic;
|
||||
}
|
||||
if (role == RoomIDRole) {
|
||||
return room.roomId;
|
||||
}
|
||||
if (role == MemberCountRole) {
|
||||
return room.numJoinedMembers;
|
||||
}
|
||||
if (role == AllowGuestsRole) {
|
||||
return room.guestCanJoin;
|
||||
}
|
||||
if (role == WorldReadableRole) {
|
||||
return room.worldReadable;
|
||||
}
|
||||
if (role == IsJoinedRole) {
|
||||
if (!m_connection)
|
||||
return {};
|
||||
|
||||
return m_connection->room(room.roomId, JoinState::Join) != nullptr;
|
||||
}
|
||||
|
||||
if (index.row() >= rooms.count()) {
|
||||
qDebug() << "PublicRoomListModel, something's wrong: index.row() >= "
|
||||
"rooms.count()";
|
||||
return {};
|
||||
}
|
||||
auto room = rooms.at(index.row());
|
||||
if (role == NameRole) {
|
||||
auto displayName = room.name;
|
||||
if (!displayName.isEmpty()) {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
displayName = room.canonicalAlias;
|
||||
if (!displayName.isEmpty()) {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
if (!room.aliases.isEmpty()) {
|
||||
displayName = room.aliases.front();
|
||||
}
|
||||
|
||||
if (!displayName.isEmpty()) {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
return room.roomId;
|
||||
}
|
||||
if (role == AvatarRole) {
|
||||
auto avatarUrl = room.avatarUrl;
|
||||
|
||||
if (avatarUrl.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return avatarUrl.remove(0, 6);
|
||||
}
|
||||
if (role == TopicRole) {
|
||||
return room.topic;
|
||||
}
|
||||
if (role == RoomIDRole) {
|
||||
return room.roomId;
|
||||
}
|
||||
if (role == MemberCountRole) {
|
||||
return room.numJoinedMembers;
|
||||
}
|
||||
if (role == AllowGuestsRole) {
|
||||
return room.guestCanJoin;
|
||||
}
|
||||
if (role == WorldReadableRole) {
|
||||
return room.worldReadable;
|
||||
}
|
||||
if (role == IsJoinedRole) {
|
||||
if (!m_connection)
|
||||
return {};
|
||||
|
||||
return m_connection->room(room.roomId, JoinState::Join) != nullptr;
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
QHash<int, QByteArray> PublicRoomListModel::roleNames() const {
|
||||
QHash<int, QByteArray> roles;
|
||||
QHash<int, QByteArray> PublicRoomListModel::roleNames() const
|
||||
{
|
||||
QHash<int, QByteArray> roles;
|
||||
|
||||
roles[NameRole] = "name";
|
||||
roles[AvatarRole] = "avatar";
|
||||
roles[TopicRole] = "topic";
|
||||
roles[RoomIDRole] = "roomID";
|
||||
roles[MemberCountRole] = "memberCount";
|
||||
roles[AllowGuestsRole] = "allowGuests";
|
||||
roles[WorldReadableRole] = "worldReadable";
|
||||
roles[IsJoinedRole] = "isJoined";
|
||||
roles[NameRole] = "name";
|
||||
roles[AvatarRole] = "avatar";
|
||||
roles[TopicRole] = "topic";
|
||||
roles[RoomIDRole] = "roomID";
|
||||
roles[MemberCountRole] = "memberCount";
|
||||
roles[AllowGuestsRole] = "allowGuests";
|
||||
roles[WorldReadableRole] = "worldReadable";
|
||||
roles[IsJoinedRole] = "isJoined";
|
||||
|
||||
return roles;
|
||||
return roles;
|
||||
}
|
||||
|
||||
int PublicRoomListModel::rowCount(const QModelIndex& parent) const {
|
||||
if (parent.isValid())
|
||||
return 0;
|
||||
int PublicRoomListModel::rowCount(const QModelIndex &parent) const
|
||||
{
|
||||
if (parent.isValid())
|
||||
return 0;
|
||||
|
||||
return rooms.count();
|
||||
return rooms.count();
|
||||
}
|
||||
|
||||
bool PublicRoomListModel::hasMore() const {
|
||||
return !(attempted && nextBatch.isEmpty());
|
||||
bool PublicRoomListModel::hasMore() const
|
||||
{
|
||||
return !(attempted && nextBatch.isEmpty());
|
||||
}
|
||||
|
||||
@@ -10,64 +10,72 @@
|
||||
|
||||
using namespace Quotient;
|
||||
|
||||
class PublicRoomListModel : public QAbstractListModel {
|
||||
Q_OBJECT
|
||||
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(bool hasMore READ hasMore NOTIFY hasMoreChanged)
|
||||
class PublicRoomListModel : public QAbstractListModel
|
||||
{
|
||||
Q_OBJECT
|
||||
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(bool hasMore READ hasMore NOTIFY hasMoreChanged)
|
||||
|
||||
public:
|
||||
enum EventRoles {
|
||||
NameRole = Qt::DisplayRole + 1,
|
||||
AvatarRole,
|
||||
TopicRole,
|
||||
RoomIDRole,
|
||||
MemberCountRole,
|
||||
AllowGuestsRole,
|
||||
WorldReadableRole,
|
||||
IsJoinedRole,
|
||||
};
|
||||
public:
|
||||
enum EventRoles {
|
||||
NameRole = Qt::DisplayRole + 1,
|
||||
AvatarRole,
|
||||
TopicRole,
|
||||
RoomIDRole,
|
||||
MemberCountRole,
|
||||
AllowGuestsRole,
|
||||
WorldReadableRole,
|
||||
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;
|
||||
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;
|
||||
bool hasMore() const;
|
||||
|
||||
Q_INVOKABLE void next(int count = 50);
|
||||
Q_INVOKABLE void next(int count = 50);
|
||||
|
||||
private:
|
||||
Connection* m_connection = nullptr;
|
||||
QString m_server;
|
||||
QString m_keyword;
|
||||
private:
|
||||
Connection *m_connection = nullptr;
|
||||
QString m_server;
|
||||
QString m_keyword;
|
||||
|
||||
bool attempted = false;
|
||||
QString nextBatch;
|
||||
bool attempted = false;
|
||||
QString nextBatch;
|
||||
|
||||
QVector<PublicRoomsChunk> rooms;
|
||||
QVector<PublicRoomsChunk> rooms;
|
||||
|
||||
QueryPublicRoomsJob* job = nullptr;
|
||||
QueryPublicRoomsJob *job = nullptr;
|
||||
|
||||
signals:
|
||||
void connectionChanged();
|
||||
void serverChanged();
|
||||
void keywordChanged();
|
||||
void hasMoreChanged();
|
||||
signals:
|
||||
void connectionChanged();
|
||||
void serverChanged();
|
||||
void keywordChanged();
|
||||
void hasMoreChanged();
|
||||
};
|
||||
|
||||
#endif // PUBLICROOMLISTMODEL_H
|
||||
#endif // PUBLICROOMLISTMODEL_H
|
||||
|
||||
@@ -11,251 +11,268 @@
|
||||
#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) {
|
||||
if (connection == m_connection)
|
||||
return;
|
||||
if (m_connection)
|
||||
m_connection->disconnect(this);
|
||||
if (!connection) {
|
||||
qDebug() << "Removing current connection...";
|
||||
m_connection = nullptr;
|
||||
void RoomListModel::setConnection(Connection *connection)
|
||||
{
|
||||
if (connection == m_connection)
|
||||
return;
|
||||
if (m_connection)
|
||||
m_connection->disconnect(this);
|
||||
if (!connection) {
|
||||
qDebug() << "Removing current connection...";
|
||||
m_connection = nullptr;
|
||||
beginResetModel();
|
||||
m_rooms.clear();
|
||||
endResetModel();
|
||||
return;
|
||||
}
|
||||
|
||||
m_connection = connection;
|
||||
|
||||
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::leftRoom, this, &RoomListModel::updateRoom);
|
||||
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));
|
||||
}
|
||||
});
|
||||
|
||||
doResetModel();
|
||||
}
|
||||
|
||||
void RoomListModel::doResetModel()
|
||||
{
|
||||
beginResetModel();
|
||||
m_rooms.clear();
|
||||
endResetModel();
|
||||
return;
|
||||
}
|
||||
|
||||
m_connection = connection;
|
||||
|
||||
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::leftRoom, this, &RoomListModel::updateRoom);
|
||||
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));
|
||||
}
|
||||
});
|
||||
|
||||
doResetModel();
|
||||
}
|
||||
|
||||
void RoomListModel::doResetModel() {
|
||||
beginResetModel();
|
||||
m_rooms.clear();
|
||||
for (auto r : m_connection->allRooms()) {
|
||||
doAddRoom(r);
|
||||
}
|
||||
endResetModel();
|
||||
refreshNotificationCount();
|
||||
}
|
||||
|
||||
SpectralRoom* RoomListModel::roomAt(int row) const {
|
||||
return m_rooms.at(row);
|
||||
}
|
||||
|
||||
void RoomListModel::doAddRoom(Room* r) {
|
||||
if (auto room = static_cast<SpectralRoom*>(r)) {
|
||||
m_rooms.append(room);
|
||||
connectRoomSignals(room);
|
||||
emit roomAdded(room);
|
||||
} else {
|
||||
qCritical() << "Attempt to add nullptr to the room list";
|
||||
Q_ASSERT(false);
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
if (lastEvent->isStateEvent())
|
||||
return;
|
||||
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));
|
||||
});
|
||||
connect(room, &Room::highlightCountChanged, this, [=] {
|
||||
if (room->highlightCount() == 0)
|
||||
return;
|
||||
if (room->timelineSize() == 0)
|
||||
return;
|
||||
const RoomEvent* lastEvent = room->messageEvents().rbegin()->get();
|
||||
if (lastEvent->isStateEvent())
|
||||
return;
|
||||
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));
|
||||
});
|
||||
connect(room, &Room::notificationCountChanged, this,
|
||||
&RoomListModel::refreshNotificationCount);
|
||||
}
|
||||
|
||||
void RoomListModel::refreshNotificationCount() {
|
||||
int count = 0;
|
||||
for (auto room : m_rooms) {
|
||||
count += room->notificationCount();
|
||||
}
|
||||
m_notificationCount = count;
|
||||
emit notificationCountChanged();
|
||||
}
|
||||
|
||||
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));
|
||||
return;
|
||||
}
|
||||
if (prev && room->id() != 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; });
|
||||
if (it != m_rooms.end()) {
|
||||
const int row = it - m_rooms.begin();
|
||||
// There's no guarantee that prev != newRoom
|
||||
if (*it == prev && *it != newRoom) {
|
||||
prev->disconnect(this);
|
||||
m_rooms.replace(row, newRoom);
|
||||
connectRoomSignals(newRoom);
|
||||
for (auto r : m_connection->allRooms()) {
|
||||
doAddRoom(r);
|
||||
}
|
||||
emit dataChanged(index(row), index(row));
|
||||
} else {
|
||||
beginInsertRows(QModelIndex(), m_rooms.count(), m_rooms.count());
|
||||
doAddRoom(newRoom);
|
||||
endInsertRows();
|
||||
}
|
||||
endResetModel();
|
||||
refreshNotificationCount();
|
||||
}
|
||||
|
||||
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())
|
||||
return; // Already deleted, nothing to do
|
||||
qDebug() << "Erasing room" << room->id();
|
||||
const int row = it - m_rooms.begin();
|
||||
beginRemoveRows(QModelIndex(), row, row);
|
||||
m_rooms.erase(it);
|
||||
endRemoveRows();
|
||||
SpectralRoom *RoomListModel::roomAt(int row) const
|
||||
{
|
||||
return m_rooms.at(row);
|
||||
}
|
||||
|
||||
int RoomListModel::rowCount(const QModelIndex& parent) const {
|
||||
if (parent.isValid())
|
||||
return 0;
|
||||
return m_rooms.count();
|
||||
void RoomListModel::doAddRoom(Room *r)
|
||||
{
|
||||
if (auto room = static_cast<SpectralRoom *>(r)) {
|
||||
m_rooms.append(room);
|
||||
connectRoomSignals(room);
|
||||
emit roomAdded(room);
|
||||
} else {
|
||||
qCritical() << "Attempt to add nullptr to the room list";
|
||||
Q_ASSERT(false);
|
||||
}
|
||||
}
|
||||
|
||||
QVariant RoomListModel::data(const QModelIndex& index, int role) const {
|
||||
if (!index.isValid())
|
||||
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();
|
||||
if (lastEvent->isStateEvent())
|
||||
return;
|
||||
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));
|
||||
});
|
||||
connect(room, &Room::highlightCountChanged, this, [=] {
|
||||
if (room->highlightCount() == 0)
|
||||
return;
|
||||
if (room->timelineSize() == 0)
|
||||
return;
|
||||
const RoomEvent *lastEvent = room->messageEvents().rbegin()->get();
|
||||
if (lastEvent->isStateEvent())
|
||||
return;
|
||||
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));
|
||||
});
|
||||
connect(room, &Room::notificationCountChanged, this, &RoomListModel::refreshNotificationCount);
|
||||
}
|
||||
|
||||
void RoomListModel::refreshNotificationCount()
|
||||
{
|
||||
int count = 0;
|
||||
for (auto room : m_rooms) {
|
||||
count += room->notificationCount();
|
||||
}
|
||||
m_notificationCount = count;
|
||||
emit notificationCountChanged();
|
||||
}
|
||||
|
||||
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));
|
||||
return;
|
||||
}
|
||||
if (prev && room->id() != 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;
|
||||
});
|
||||
if (it != m_rooms.end()) {
|
||||
const int row = it - m_rooms.begin();
|
||||
// There's no guarantee that prev != newRoom
|
||||
if (*it == prev && *it != newRoom) {
|
||||
prev->disconnect(this);
|
||||
m_rooms.replace(row, newRoom);
|
||||
connectRoomSignals(newRoom);
|
||||
}
|
||||
emit dataChanged(index(row), index(row));
|
||||
} else {
|
||||
beginInsertRows(QModelIndex(), m_rooms.count(), m_rooms.count());
|
||||
doAddRoom(newRoom);
|
||||
endInsertRows();
|
||||
}
|
||||
}
|
||||
|
||||
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())
|
||||
return; // Already deleted, nothing to do
|
||||
qDebug() << "Erasing room" << room->id();
|
||||
const int row = it - m_rooms.begin();
|
||||
beginRemoveRows(QModelIndex(), row, row);
|
||||
m_rooms.erase(it);
|
||||
endRemoveRows();
|
||||
}
|
||||
|
||||
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
|
||||
{
|
||||
if (!index.isValid())
|
||||
return QVariant();
|
||||
|
||||
if (index.row() >= m_rooms.count()) {
|
||||
qDebug() << "UserListModel: something wrong here...";
|
||||
return QVariant();
|
||||
}
|
||||
SpectralRoom *room = m_rooms.at(index.row());
|
||||
if (role == NameRole)
|
||||
return room->displayName();
|
||||
if (role == AvatarRole)
|
||||
return room->avatarMediaId();
|
||||
if (role == TopicRole)
|
||||
return room->topic();
|
||||
if (role == CategoryRole) {
|
||||
if (room->joinState() == JoinState::Invite)
|
||||
return RoomType::Invited;
|
||||
if (room->isFavourite())
|
||||
return RoomType::Favorite;
|
||||
if (room->isDirectChat())
|
||||
return RoomType::Direct;
|
||||
if (room->isLowPriority())
|
||||
return RoomType::Deprioritized;
|
||||
return RoomType::Normal;
|
||||
}
|
||||
if (role == UnreadCountRole)
|
||||
return room->unreadCount();
|
||||
if (role == NotificationCountRole)
|
||||
return room->notificationCount();
|
||||
if (role == HighlightCountRole)
|
||||
return room->highlightCount();
|
||||
if (role == LastEventRole)
|
||||
return room->lastEvent();
|
||||
if (role == LastActiveTimeRole)
|
||||
return room->lastActiveTime();
|
||||
if (role == JoinStateRole) {
|
||||
if (!room->successorId().isEmpty())
|
||||
return QStringLiteral("upgraded");
|
||||
return toCString(room->joinState());
|
||||
}
|
||||
if (role == CurrentRoomRole)
|
||||
return QVariant::fromValue(room);
|
||||
return QVariant();
|
||||
|
||||
if (index.row() >= m_rooms.count()) {
|
||||
qDebug() << "UserListModel: something wrong here...";
|
||||
return QVariant();
|
||||
}
|
||||
SpectralRoom* room = m_rooms.at(index.row());
|
||||
if (role == NameRole)
|
||||
return room->displayName();
|
||||
if (role == AvatarRole)
|
||||
return room->avatarMediaId();
|
||||
if (role == TopicRole)
|
||||
return room->topic();
|
||||
if (role == CategoryRole) {
|
||||
if (room->joinState() == JoinState::Invite)
|
||||
return RoomType::Invited;
|
||||
if (room->isFavourite())
|
||||
return RoomType::Favorite;
|
||||
if (room->isDirectChat())
|
||||
return RoomType::Direct;
|
||||
if (room->isLowPriority())
|
||||
return RoomType::Deprioritized;
|
||||
return RoomType::Normal;
|
||||
}
|
||||
if (role == UnreadCountRole)
|
||||
return room->unreadCount();
|
||||
if (role == NotificationCountRole)
|
||||
return room->notificationCount();
|
||||
if (role == HighlightCountRole)
|
||||
return room->highlightCount();
|
||||
if (role == LastEventRole)
|
||||
return room->lastEvent();
|
||||
if (role == LastActiveTimeRole)
|
||||
return room->lastActiveTime();
|
||||
if (role == JoinStateRole) {
|
||||
if (!room->successorId().isEmpty())
|
||||
return QStringLiteral("upgraded");
|
||||
return toCString(room->joinState());
|
||||
}
|
||||
if (role == CurrentRoomRole)
|
||||
return QVariant::fromValue(room);
|
||||
return QVariant();
|
||||
}
|
||||
|
||||
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";
|
||||
return;
|
||||
}
|
||||
const auto idx = index(it - m_rooms.begin());
|
||||
emit dataChanged(idx, idx, 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";
|
||||
return;
|
||||
}
|
||||
const auto idx = index(it - m_rooms.begin());
|
||||
emit dataChanged(idx, idx, roles);
|
||||
}
|
||||
|
||||
QHash<int, QByteArray> RoomListModel::roleNames() const {
|
||||
QHash<int, QByteArray> roles;
|
||||
roles[NameRole] = "name";
|
||||
roles[AvatarRole] = "avatar";
|
||||
roles[TopicRole] = "topic";
|
||||
roles[CategoryRole] = "category";
|
||||
roles[UnreadCountRole] = "unreadCount";
|
||||
roles[NotificationCountRole] = "notificationCount";
|
||||
roles[HighlightCountRole] = "highlightCount";
|
||||
roles[LastEventRole] = "lastEvent";
|
||||
roles[LastActiveTimeRole] = "lastActiveTime";
|
||||
roles[JoinStateRole] = "joinState";
|
||||
roles[CurrentRoomRole] = "currentRoom";
|
||||
return roles;
|
||||
QHash<int, QByteArray> RoomListModel::roleNames() const
|
||||
{
|
||||
QHash<int, QByteArray> roles;
|
||||
roles[NameRole] = "name";
|
||||
roles[AvatarRole] = "avatar";
|
||||
roles[TopicRole] = "topic";
|
||||
roles[CategoryRole] = "category";
|
||||
roles[UnreadCountRole] = "unreadCount";
|
||||
roles[NotificationCountRole] = "notificationCount";
|
||||
roles[HighlightCountRole] = "highlightCount";
|
||||
roles[LastEventRole] = "lastEvent";
|
||||
roles[LastActiveTimeRole] = "lastActiveTime";
|
||||
roles[JoinStateRole] = "joinState";
|
||||
roles[CurrentRoomRole] = "currentRoom";
|
||||
return roles;
|
||||
}
|
||||
|
||||
@@ -10,92 +10,87 @@
|
||||
|
||||
using namespace Quotient;
|
||||
|
||||
class RoomType : public QObject {
|
||||
Q_OBJECT
|
||||
class RoomType : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
enum Types {
|
||||
Invited = 1,
|
||||
Favorite,
|
||||
Direct,
|
||||
Normal,
|
||||
Deprioritized,
|
||||
};
|
||||
Q_ENUMS(Types)
|
||||
public:
|
||||
enum Types {
|
||||
Invited = 1,
|
||||
Favorite,
|
||||
Direct,
|
||||
Normal,
|
||||
Deprioritized,
|
||||
};
|
||||
Q_ENUMS(Types)
|
||||
};
|
||||
|
||||
class RoomListModel : public QAbstractListModel {
|
||||
Q_OBJECT
|
||||
Q_PROPERTY(Connection* connection READ connection WRITE setConnection)
|
||||
Q_PROPERTY(int notificationCount READ notificationCount NOTIFY
|
||||
notificationCountChanged)
|
||||
class RoomListModel : public QAbstractListModel
|
||||
{
|
||||
Q_OBJECT
|
||||
Q_PROPERTY(Connection *connection READ connection WRITE setConnection)
|
||||
Q_PROPERTY(int notificationCount READ notificationCount NOTIFY notificationCountChanged)
|
||||
|
||||
public:
|
||||
enum EventRoles {
|
||||
NameRole = Qt::UserRole + 1,
|
||||
AvatarRole,
|
||||
TopicRole,
|
||||
CategoryRole,
|
||||
UnreadCountRole,
|
||||
NotificationCountRole,
|
||||
HighlightCountRole,
|
||||
LastEventRole,
|
||||
LastActiveTimeRole,
|
||||
JoinStateRole,
|
||||
CurrentRoomRole,
|
||||
};
|
||||
Q_ENUM(EventRoles)
|
||||
public:
|
||||
enum EventRoles {
|
||||
NameRole = Qt::UserRole + 1,
|
||||
AvatarRole,
|
||||
TopicRole,
|
||||
CategoryRole,
|
||||
UnreadCountRole,
|
||||
NotificationCountRole,
|
||||
HighlightCountRole,
|
||||
LastEventRole,
|
||||
LastActiveTimeRole,
|
||||
JoinStateRole,
|
||||
CurrentRoomRole,
|
||||
};
|
||||
Q_ENUM(EventRoles)
|
||||
|
||||
RoomListModel(QObject* parent = nullptr);
|
||||
virtual ~RoomListModel() override;
|
||||
RoomListModel(QObject *parent = nullptr);
|
||||
virtual ~RoomListModel() override;
|
||||
|
||||
Connection* connection() const { return m_connection; }
|
||||
void setConnection(Connection* connection);
|
||||
void doResetModel();
|
||||
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;
|
||||
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 = {});
|
||||
void refreshNotificationCount();
|
||||
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;
|
||||
int m_notificationCount = 0;
|
||||
|
||||
void connectRoomSignals(SpectralRoom* room);
|
||||
void connectRoomSignals(SpectralRoom *room);
|
||||
|
||||
signals:
|
||||
void connectionChanged();
|
||||
void notificationCountChanged();
|
||||
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
|
||||
#endif // ROOMLISTMODEL_H
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -18,110 +18,105 @@
|
||||
|
||||
using namespace Quotient;
|
||||
|
||||
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)
|
||||
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)
|
||||
|
||||
public:
|
||||
explicit SpectralRoom(Connection* connection,
|
||||
QString roomId,
|
||||
JoinState joinState = {});
|
||||
public:
|
||||
explicit SpectralRoom(Connection *connection, QString roomId, JoinState joinState = {});
|
||||
|
||||
QVariantList getUsersTyping() const;
|
||||
QVariantList getUsersTyping() const;
|
||||
|
||||
QString lastEvent() const;
|
||||
bool isEventHighlighted(const Quotient::RoomEvent* e) const;
|
||||
QString lastEvent() const;
|
||||
bool isEventHighlighted(const Quotient::RoomEvent *e) const;
|
||||
|
||||
QDateTime lastActiveTime() const;
|
||||
QDateTime lastActiveTime() const;
|
||||
|
||||
bool hasFileUploading() const { return m_hasFileUploading; }
|
||||
void setHasFileUploading(bool value) {
|
||||
if (value == m_hasFileUploading) {
|
||||
return;
|
||||
bool hasFileUploading() const
|
||||
{
|
||||
return m_hasFileUploading;
|
||||
}
|
||||
m_hasFileUploading = value;
|
||||
emit hasFileUploadingChanged();
|
||||
}
|
||||
|
||||
int fileUploadingProgress() const { return m_fileUploadingProgress; }
|
||||
void setFileUploadingProgress(int value) {
|
||||
if (m_fileUploadingProgress == value) {
|
||||
return;
|
||||
void setHasFileUploading(bool value)
|
||||
{
|
||||
if (value == m_hasFileUploading) {
|
||||
return;
|
||||
}
|
||||
m_hasFileUploading = value;
|
||||
emit hasFileUploadingChanged();
|
||||
}
|
||||
m_fileUploadingProgress = value;
|
||||
emit fileUploadingProgressChanged();
|
||||
}
|
||||
|
||||
Q_INVOKABLE int savedTopVisibleIndex() const;
|
||||
Q_INVOKABLE int savedBottomVisibleIndex() const;
|
||||
Q_INVOKABLE void saveViewport(int topIndex, int bottomIndex);
|
||||
int fileUploadingProgress() const
|
||||
{
|
||||
return m_fileUploadingProgress;
|
||||
}
|
||||
void setFileUploadingProgress(int value)
|
||||
{
|
||||
if (m_fileUploadingProgress == value) {
|
||||
return;
|
||||
}
|
||||
m_fileUploadingProgress = value;
|
||||
emit fileUploadingProgressChanged();
|
||||
}
|
||||
|
||||
Q_INVOKABLE QVariantList getUsers(const QString& keyword) const;
|
||||
Q_INVOKABLE int savedTopVisibleIndex() const;
|
||||
Q_INVOKABLE int savedBottomVisibleIndex() const;
|
||||
Q_INVOKABLE void saveViewport(int topIndex, int bottomIndex);
|
||||
|
||||
Q_INVOKABLE QUrl urlToMxcUrl(QUrl mxcUrl);
|
||||
Q_INVOKABLE QVariantList getUsers(const QString &keyword) const;
|
||||
|
||||
QString avatarMediaId() const;
|
||||
Q_INVOKABLE QUrl urlToMxcUrl(QUrl mxcUrl);
|
||||
|
||||
QString eventToString(const RoomEvent& evt,
|
||||
Qt::TextFormat format = Qt::PlainText,
|
||||
bool removeReply = true) const;
|
||||
QString avatarMediaId() const;
|
||||
|
||||
Q_INVOKABLE bool containsUser(QString userID) const;
|
||||
QString eventToString(const RoomEvent &evt, Qt::TextFormat format = Qt::PlainText, bool removeReply = true) const;
|
||||
|
||||
Q_INVOKABLE bool canSendEvent(const QString& eventType) const;
|
||||
Q_INVOKABLE bool canSendState(const QString& eventType) const;
|
||||
Q_INVOKABLE bool containsUser(QString userID) const;
|
||||
|
||||
private:
|
||||
QString m_cachedInput;
|
||||
QSet<const Quotient::RoomEvent*> highlights;
|
||||
Q_INVOKABLE bool canSendEvent(const QString &eventType) const;
|
||||
Q_INVOKABLE bool canSendState(const QString &eventType) const;
|
||||
|
||||
bool m_hasFileUploading = false;
|
||||
int m_fileUploadingProgress = 0;
|
||||
private:
|
||||
QString m_cachedInput;
|
||||
QSet<const Quotient::RoomEvent *> highlights;
|
||||
|
||||
void checkForHighlights(const Quotient::TimelineItem& ti);
|
||||
bool m_hasFileUploading = false;
|
||||
int m_fileUploadingProgress = 0;
|
||||
|
||||
void onAddNewTimelineEvents(timeline_iter_t from) override;
|
||||
void onAddHistoricalTimelineEvents(rev_iter_t from) override;
|
||||
void onRedaction(const RoomEvent& prevEvent, const RoomEvent& after) override;
|
||||
void checkForHighlights(const Quotient::TimelineItem &ti);
|
||||
|
||||
static QString markdownToHTML(const QString& plaintext);
|
||||
void onAddNewTimelineEvents(timeline_iter_t from) override;
|
||||
void onAddHistoricalTimelineEvents(rev_iter_t from) override;
|
||||
void onRedaction(const RoomEvent &prevEvent, const RoomEvent &after) override;
|
||||
|
||||
private slots:
|
||||
void countChanged();
|
||||
static QString markdownToHTML(const QString &plaintext);
|
||||
|
||||
signals:
|
||||
void cachedInputChanged();
|
||||
void busyChanged();
|
||||
void hasFileUploadingChanged();
|
||||
void fileUploadingProgressChanged();
|
||||
void backgroundChanged();
|
||||
private slots:
|
||||
void countChanged();
|
||||
|
||||
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 changeAvatar(QUrl localFile);
|
||||
void addLocalAlias(const QString& alias);
|
||||
void removeLocalAlias(const QString& alias);
|
||||
void toggleReaction(const QString& eventId, const QString& reaction);
|
||||
signals:
|
||||
void cachedInputChanged();
|
||||
void busyChanged();
|
||||
void hasFileUploadingChanged();
|
||||
void fileUploadingProgressChanged();
|
||||
void backgroundChanged();
|
||||
|
||||
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 changeAvatar(QUrl localFile);
|
||||
void addLocalAlias(const QString &alias);
|
||||
void removeLocalAlias(const QString &alias);
|
||||
void toggleReaction(const QString &eventId, const QString &reaction);
|
||||
};
|
||||
|
||||
#endif // SpectralRoom_H
|
||||
#endif // SpectralRoom_H
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "spectraluser.h"
|
||||
|
||||
QColor SpectralUser::color() {
|
||||
return QColor::fromHslF(hueF(), 0.7, 0.5, 1);
|
||||
QColor SpectralUser::color()
|
||||
{
|
||||
return QColor::fromHslF(hueF(), 0.7, 0.5, 1);
|
||||
}
|
||||
|
||||
@@ -8,14 +8,17 @@
|
||||
|
||||
using namespace Quotient;
|
||||
|
||||
class SpectralUser : public User {
|
||||
Q_OBJECT
|
||||
Q_PROPERTY(QColor color READ color CONSTANT)
|
||||
public:
|
||||
SpectralUser(QString userId, Connection* connection)
|
||||
: User(userId, connection) {}
|
||||
class SpectralUser : public User
|
||||
{
|
||||
Q_OBJECT
|
||||
Q_PROPERTY(QColor color READ color CONSTANT)
|
||||
public:
|
||||
SpectralUser(QString userId, Connection *connection)
|
||||
: User(userId, connection)
|
||||
{
|
||||
}
|
||||
|
||||
QColor color();
|
||||
QColor color();
|
||||
};
|
||||
|
||||
#endif // SpectralUser_H
|
||||
#endif // SpectralUser_H
|
||||
|
||||
226
src/trayicon.cpp
226
src/trayicon.cpp
@@ -12,168 +12,168 @@
|
||||
#include <QtMacExtras>
|
||||
#endif
|
||||
|
||||
MsgCountComposedIcon::MsgCountComposedIcon(const QString& filename)
|
||||
: QIconEngine() {
|
||||
icon_ = QIcon(filename);
|
||||
MsgCountComposedIcon::MsgCountComposedIcon(const QString &filename)
|
||||
: QIconEngine()
|
||||
{
|
||||
icon_ = QIcon(filename);
|
||||
}
|
||||
|
||||
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);
|
||||
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);
|
||||
|
||||
icon_.paint(painter, rect, Qt::AlignCenter, mode, state);
|
||||
icon_.paint(painter, rect, Qt::AlignCenter, mode, state);
|
||||
|
||||
if (isOnline && msgCount <= 0)
|
||||
return;
|
||||
if (isOnline && msgCount <= 0)
|
||||
return;
|
||||
|
||||
QColor backgroundColor("red");
|
||||
QColor textColor("white");
|
||||
QColor backgroundColor("red");
|
||||
QColor textColor("white");
|
||||
|
||||
QBrush brush;
|
||||
brush.setStyle(Qt::SolidPattern);
|
||||
brush.setColor(backgroundColor);
|
||||
QBrush brush;
|
||||
brush.setStyle(Qt::SolidPattern);
|
||||
brush.setColor(backgroundColor);
|
||||
|
||||
painter->setBrush(brush);
|
||||
painter->setPen(Qt::NoPen);
|
||||
painter->setFont(QFont("Open Sans", 8, QFont::Black));
|
||||
painter->setBrush(brush);
|
||||
painter->setPen(Qt::NoPen);
|
||||
painter->setFont(QFont("Open Sans", 8, QFont::Black));
|
||||
|
||||
QRectF bubble(rect.width() - BubbleDiameter, rect.height() - BubbleDiameter,
|
||||
BubbleDiameter, BubbleDiameter);
|
||||
painter->drawEllipse(bubble);
|
||||
painter->setPen(QPen(textColor));
|
||||
painter->setBrush(Qt::NoBrush);
|
||||
if (!isOnline) {
|
||||
painter->drawText(bubble, Qt::AlignCenter, "x");
|
||||
} else if (msgCount >= 100) {
|
||||
painter->drawText(bubble, Qt::AlignCenter, "99+");
|
||||
} else {
|
||||
painter->drawText(bubble, Qt::AlignCenter, QString::number(msgCount));
|
||||
}
|
||||
QRectF bubble(rect.width() - BubbleDiameter, rect.height() - BubbleDiameter, BubbleDiameter, BubbleDiameter);
|
||||
painter->drawEllipse(bubble);
|
||||
painter->setPen(QPen(textColor));
|
||||
painter->setBrush(Qt::NoBrush);
|
||||
if (!isOnline) {
|
||||
painter->drawText(bubble, Qt::AlignCenter, "x");
|
||||
} else if (msgCount >= 100) {
|
||||
painter->drawText(bubble, Qt::AlignCenter, "99+");
|
||||
} else {
|
||||
painter->drawText(bubble, Qt::AlignCenter, QString::number(msgCount));
|
||||
}
|
||||
}
|
||||
|
||||
QIconEngine* MsgCountComposedIcon::clone() const {
|
||||
return new MsgCountComposedIcon(*this);
|
||||
QIconEngine *MsgCountComposedIcon::clone() const
|
||||
{
|
||||
return new MsgCountComposedIcon(*this);
|
||||
}
|
||||
|
||||
QList<QSize> MsgCountComposedIcon::availableSizes(QIcon::Mode mode,
|
||||
QIcon::State state) const {
|
||||
Q_UNUSED(mode)
|
||||
Q_UNUSED(state)
|
||||
QList<QSize> sizes;
|
||||
sizes.append(QSize(24, 24));
|
||||
sizes.append(QSize(32, 32));
|
||||
sizes.append(QSize(48, 48));
|
||||
sizes.append(QSize(64, 64));
|
||||
sizes.append(QSize(128, 128));
|
||||
sizes.append(QSize(256, 256));
|
||||
return sizes;
|
||||
QList<QSize> MsgCountComposedIcon::availableSizes(QIcon::Mode mode, QIcon::State state) const
|
||||
{
|
||||
Q_UNUSED(mode)
|
||||
Q_UNUSED(state)
|
||||
QList<QSize> sizes;
|
||||
sizes.append(QSize(24, 24));
|
||||
sizes.append(QSize(32, 32));
|
||||
sizes.append(QSize(48, 48));
|
||||
sizes.append(QSize(64, 64));
|
||||
sizes.append(QSize(128, 128));
|
||||
sizes.append(QSize(256, 256));
|
||||
return sizes;
|
||||
}
|
||||
|
||||
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);
|
||||
{
|
||||
QPainter painter(&result);
|
||||
paint(&painter, QRect(QPoint(0, 0), size), mode, state);
|
||||
}
|
||||
return result;
|
||||
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);
|
||||
{
|
||||
QPainter painter(&result);
|
||||
paint(&painter, QRect(QPoint(0, 0), size), mode, state);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
TrayIcon::TrayIcon(QObject* parent) : QSystemTrayIcon(parent) {
|
||||
QMenu* menu = new QMenu();
|
||||
viewAction_ = new QAction(tr("Show"), parent);
|
||||
quitAction_ = new QAction(tr("Quit"), parent);
|
||||
TrayIcon::TrayIcon(QObject *parent)
|
||||
: QSystemTrayIcon(parent)
|
||||
{
|
||||
QMenu *menu = new QMenu();
|
||||
viewAction_ = new QAction(tr("Show"), parent);
|
||||
quitAction_ = new QAction(tr("Quit"), parent);
|
||||
|
||||
connect(viewAction_, &QAction::triggered, this, &TrayIcon::showWindow);
|
||||
connect(quitAction_, &QAction::triggered, this, QApplication::quit);
|
||||
connect(viewAction_, &QAction::triggered, this, &TrayIcon::showWindow);
|
||||
connect(quitAction_, &QAction::triggered, this, QApplication::quit);
|
||||
|
||||
menu->addAction(viewAction_);
|
||||
menu->addAction(quitAction_);
|
||||
menu->addAction(viewAction_);
|
||||
menu->addAction(quitAction_);
|
||||
|
||||
setContextMenu(menu);
|
||||
setContextMenu(menu);
|
||||
}
|
||||
|
||||
void TrayIcon::setNotificationCount(int count) {
|
||||
m_notificationCount = count;
|
||||
void TrayIcon::setNotificationCount(int count)
|
||||
{
|
||||
m_notificationCount = count;
|
||||
// Use the native badge counter in MacOS.
|
||||
#if defined(Q_OS_MAC)
|
||||
auto labelText = count == 0 ? "" : QString::number(count);
|
||||
auto labelText = count == 0 ? "" : QString::number(count);
|
||||
|
||||
if (labelText == QtMac::badgeLabelText())
|
||||
return;
|
||||
if (labelText == QtMac::badgeLabelText())
|
||||
return;
|
||||
|
||||
QtMac::setBadgeLabelText(labelText);
|
||||
QtMac::setBadgeLabelText(labelText);
|
||||
#elif defined(Q_OS_WIN)
|
||||
// FIXME: Find a way to use Windows apis for the badge counter (if any).
|
||||
#else
|
||||
if (!icon_ || count == icon_->msgCount)
|
||||
return;
|
||||
if (!icon_ || count == icon_->msgCount)
|
||||
return;
|
||||
|
||||
// Custom drawing on Linux.
|
||||
MsgCountComposedIcon* tmp =
|
||||
static_cast<MsgCountComposedIcon*>(icon_->clone());
|
||||
tmp->msgCount = count;
|
||||
// Custom drawing on Linux.
|
||||
MsgCountComposedIcon *tmp = static_cast<MsgCountComposedIcon *>(icon_->clone());
|
||||
tmp->msgCount = count;
|
||||
|
||||
setIcon(QIcon(tmp));
|
||||
setIcon(QIcon(tmp));
|
||||
|
||||
icon_ = tmp;
|
||||
icon_ = tmp;
|
||||
#endif
|
||||
emit notificationCountChanged();
|
||||
emit notificationCountChanged();
|
||||
}
|
||||
|
||||
void TrayIcon::setIsOnline(bool online) {
|
||||
m_isOnline = 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);
|
||||
if (online) {
|
||||
auto labelText = m_notificationCount == 0 ? "" : QString::number(m_notificationCount);
|
||||
|
||||
if (labelText == QtMac::badgeLabelText())
|
||||
return;
|
||||
if (labelText == QtMac::badgeLabelText())
|
||||
return;
|
||||
|
||||
QtMac::setBadgeLabelText(labelText);
|
||||
} else {
|
||||
auto labelText = "x";
|
||||
QtMac::setBadgeLabelText(labelText);
|
||||
} else {
|
||||
auto labelText = "x";
|
||||
|
||||
if (labelText == QtMac::badgeLabelText())
|
||||
return;
|
||||
if (labelText == QtMac::badgeLabelText())
|
||||
return;
|
||||
|
||||
QtMac::setBadgeLabelText(labelText);
|
||||
}
|
||||
QtMac::setBadgeLabelText(labelText);
|
||||
}
|
||||
#elif defined(Q_OS_WIN)
|
||||
// FIXME: Find a way to use Windows apis for the badge counter (if any).
|
||||
#else
|
||||
if (!icon_ || online == icon_->isOnline)
|
||||
return;
|
||||
if (!icon_ || online == icon_->isOnline)
|
||||
return;
|
||||
|
||||
// Custom drawing on Linux.
|
||||
MsgCountComposedIcon* tmp =
|
||||
static_cast<MsgCountComposedIcon*>(icon_->clone());
|
||||
tmp->isOnline = online;
|
||||
// Custom drawing on Linux.
|
||||
MsgCountComposedIcon *tmp = static_cast<MsgCountComposedIcon *>(icon_->clone());
|
||||
tmp->isOnline = online;
|
||||
|
||||
setIcon(QIcon(tmp));
|
||||
setIcon(QIcon(tmp));
|
||||
|
||||
icon_ = tmp;
|
||||
icon_ = tmp;
|
||||
#endif
|
||||
emit isOnlineChanged();
|
||||
emit isOnlineChanged();
|
||||
}
|
||||
|
||||
void TrayIcon::setIconSource(const QString& source) {
|
||||
m_iconSource = source;
|
||||
void TrayIcon::setIconSource(const QString &source)
|
||||
{
|
||||
m_iconSource = source;
|
||||
#if defined(Q_OS_MAC) || defined(Q_OS_WIN)
|
||||
setIcon(QIcon(source));
|
||||
setIcon(QIcon(source));
|
||||
#else
|
||||
icon_ = new MsgCountComposedIcon(source);
|
||||
setIcon(QIcon(icon_));
|
||||
icon_->isOnline = m_isOnline;
|
||||
icon_->msgCount = m_notificationCount;
|
||||
icon_ = new MsgCountComposedIcon(source);
|
||||
setIcon(QIcon(icon_));
|
||||
icon_->isOnline = m_isOnline;
|
||||
icon_->msgCount = m_notificationCount;
|
||||
#endif
|
||||
emit iconSourceChanged();
|
||||
emit iconSourceChanged();
|
||||
}
|
||||
|
||||
@@ -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?
|
||||
int msgCount = 0;
|
||||
bool isOnline = true; // Default to false?
|
||||
|
||||
private:
|
||||
const int BubbleDiameter = 14;
|
||||
private:
|
||||
const int BubbleDiameter = 14;
|
||||
|
||||
QIcon icon_;
|
||||
QIcon icon_;
|
||||
};
|
||||
|
||||
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)
|
||||
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(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; }
|
||||
void setNotificationCount(int count);
|
||||
int notificationCount()
|
||||
{
|
||||
return m_notificationCount;
|
||||
}
|
||||
void setNotificationCount(int count);
|
||||
|
||||
bool isOnline() { return m_isOnline; }
|
||||
void setIsOnline(bool online);
|
||||
bool isOnline()
|
||||
{
|
||||
return m_isOnline;
|
||||
}
|
||||
void setIsOnline(bool online);
|
||||
|
||||
signals:
|
||||
void notificationCountChanged();
|
||||
void iconSourceChanged();
|
||||
void isOnlineChanged();
|
||||
signals:
|
||||
void notificationCountChanged();
|
||||
void iconSourceChanged();
|
||||
void isOnlineChanged();
|
||||
|
||||
void showWindow();
|
||||
void showWindow();
|
||||
|
||||
private:
|
||||
QString m_iconSource;
|
||||
int m_notificationCount = 0;
|
||||
bool m_isOnline = true;
|
||||
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
|
||||
#endif // TRAYICON_H
|
||||
|
||||
@@ -1,156 +1,163 @@
|
||||
#include "userdirectorylistmodel.h"
|
||||
|
||||
UserDirectoryListModel::UserDirectoryListModel(QObject* parent)
|
||||
: QAbstractListModel(parent) {}
|
||||
|
||||
void UserDirectoryListModel::setConnection(Connection* conn) {
|
||||
if (m_connection == conn)
|
||||
return;
|
||||
|
||||
beginResetModel();
|
||||
|
||||
m_limited = false;
|
||||
attempted = false;
|
||||
users.clear();
|
||||
|
||||
if (m_connection) {
|
||||
m_connection->disconnect(this);
|
||||
}
|
||||
|
||||
endResetModel();
|
||||
|
||||
m_connection = conn;
|
||||
|
||||
if (job) {
|
||||
job->abandon();
|
||||
job = nullptr;
|
||||
}
|
||||
|
||||
emit connectionChanged();
|
||||
emit limitedChanged();
|
||||
UserDirectoryListModel::UserDirectoryListModel(QObject *parent)
|
||||
: QAbstractListModel(parent)
|
||||
{
|
||||
}
|
||||
|
||||
void UserDirectoryListModel::setKeyword(const QString& value) {
|
||||
if (m_keyword == value)
|
||||
return;
|
||||
void UserDirectoryListModel::setConnection(Connection *conn)
|
||||
{
|
||||
if (m_connection == conn)
|
||||
return;
|
||||
|
||||
m_keyword = value;
|
||||
beginResetModel();
|
||||
|
||||
m_limited = false;
|
||||
attempted = false;
|
||||
m_limited = false;
|
||||
attempted = false;
|
||||
users.clear();
|
||||
|
||||
if (job) {
|
||||
job->abandon();
|
||||
job = nullptr;
|
||||
}
|
||||
|
||||
emit keywordChanged();
|
||||
emit limitedChanged();
|
||||
}
|
||||
|
||||
void UserDirectoryListModel::search(int count) {
|
||||
if (count < 1)
|
||||
return;
|
||||
|
||||
if (job) {
|
||||
qDebug() << "UserDirectoryListModel: Other jobs running, ignore";
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (attempted)
|
||||
return;
|
||||
|
||||
job = m_connection->callApi<SearchUserDirectoryJob>(m_keyword, count);
|
||||
|
||||
connect(job, &BaseJob::finished, this, [=] {
|
||||
attempted = true;
|
||||
|
||||
if (job->status() == BaseJob::Success) {
|
||||
auto users = job->results();
|
||||
|
||||
this->beginResetModel();
|
||||
|
||||
this->users = users;
|
||||
this->m_limited = job->limited();
|
||||
|
||||
this->endResetModel();
|
||||
if (m_connection) {
|
||||
m_connection->disconnect(this);
|
||||
}
|
||||
|
||||
this->job = nullptr;
|
||||
endResetModel();
|
||||
|
||||
m_connection = conn;
|
||||
|
||||
if (job) {
|
||||
job->abandon();
|
||||
job = nullptr;
|
||||
}
|
||||
|
||||
emit connectionChanged();
|
||||
emit limitedChanged();
|
||||
});
|
||||
}
|
||||
|
||||
QVariant UserDirectoryListModel::data(const QModelIndex& index,
|
||||
int role) const {
|
||||
if (!index.isValid())
|
||||
return QVariant();
|
||||
void UserDirectoryListModel::setKeyword(const QString &value)
|
||||
{
|
||||
if (m_keyword == value)
|
||||
return;
|
||||
|
||||
m_keyword = value;
|
||||
|
||||
m_limited = false;
|
||||
attempted = false;
|
||||
|
||||
if (job) {
|
||||
job->abandon();
|
||||
job = nullptr;
|
||||
}
|
||||
|
||||
emit keywordChanged();
|
||||
emit limitedChanged();
|
||||
}
|
||||
|
||||
void UserDirectoryListModel::search(int count)
|
||||
{
|
||||
if (count < 1)
|
||||
return;
|
||||
|
||||
if (job) {
|
||||
qDebug() << "UserDirectoryListModel: Other jobs running, ignore";
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (attempted)
|
||||
return;
|
||||
|
||||
job = m_connection->callApi<SearchUserDirectoryJob>(m_keyword, count);
|
||||
|
||||
connect(job, &BaseJob::finished, this, [=] {
|
||||
attempted = true;
|
||||
|
||||
if (job->status() == BaseJob::Success) {
|
||||
auto users = job->results();
|
||||
|
||||
this->beginResetModel();
|
||||
|
||||
this->users = users;
|
||||
this->m_limited = job->limited();
|
||||
|
||||
this->endResetModel();
|
||||
}
|
||||
|
||||
this->job = nullptr;
|
||||
|
||||
emit limitedChanged();
|
||||
});
|
||||
}
|
||||
|
||||
QVariant UserDirectoryListModel::data(const QModelIndex &index, int role) const
|
||||
{
|
||||
if (!index.isValid())
|
||||
return QVariant();
|
||||
|
||||
if (index.row() >= users.count()) {
|
||||
qDebug() << "UserDirectoryListModel, something's wrong: index.row() >= "
|
||||
"users.count()";
|
||||
return {};
|
||||
}
|
||||
auto user = users.at(index.row());
|
||||
if (role == NameRole) {
|
||||
auto displayName = user.displayName;
|
||||
if (!displayName.isEmpty()) {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
displayName = user.userId;
|
||||
if (!displayName.isEmpty()) {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
return "Unknown User";
|
||||
}
|
||||
if (role == AvatarRole) {
|
||||
auto avatarUrl = user.avatarUrl;
|
||||
|
||||
if (avatarUrl.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return avatarUrl.remove(0, 6);
|
||||
}
|
||||
if (role == UserIDRole) {
|
||||
return user.userId;
|
||||
}
|
||||
if (role == DirectChatsRole) {
|
||||
if (!m_connection)
|
||||
return {};
|
||||
|
||||
auto userObj = m_connection->user(user.userId);
|
||||
auto directChats = m_connection->directChats();
|
||||
|
||||
if (userObj && directChats.contains(userObj)) {
|
||||
auto directChatsForUser = directChats.values(userObj);
|
||||
if (!directChatsForUser.isEmpty()) {
|
||||
return QVariant::fromValue(directChatsForUser);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (index.row() >= users.count()) {
|
||||
qDebug() << "UserDirectoryListModel, something's wrong: index.row() >= "
|
||||
"users.count()";
|
||||
return {};
|
||||
}
|
||||
auto user = users.at(index.row());
|
||||
if (role == NameRole) {
|
||||
auto displayName = user.displayName;
|
||||
if (!displayName.isEmpty()) {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
displayName = user.userId;
|
||||
if (!displayName.isEmpty()) {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
return "Unknown User";
|
||||
}
|
||||
if (role == AvatarRole) {
|
||||
auto avatarUrl = user.avatarUrl;
|
||||
|
||||
if (avatarUrl.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return avatarUrl.remove(0, 6);
|
||||
}
|
||||
if (role == UserIDRole) {
|
||||
return user.userId;
|
||||
}
|
||||
if (role == DirectChatsRole) {
|
||||
if (!m_connection)
|
||||
return {};
|
||||
|
||||
auto userObj = m_connection->user(user.userId);
|
||||
auto directChats = m_connection->directChats();
|
||||
|
||||
if (userObj && directChats.contains(userObj)) {
|
||||
auto directChatsForUser = directChats.values(userObj);
|
||||
if (!directChatsForUser.isEmpty()) {
|
||||
return QVariant::fromValue(directChatsForUser);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
QHash<int, QByteArray> UserDirectoryListModel::roleNames() const {
|
||||
QHash<int, QByteArray> roles;
|
||||
QHash<int, QByteArray> UserDirectoryListModel::roleNames() const
|
||||
{
|
||||
QHash<int, QByteArray> roles;
|
||||
|
||||
roles[NameRole] = "name";
|
||||
roles[AvatarRole] = "avatar";
|
||||
roles[UserIDRole] = "userID";
|
||||
roles[DirectChatsRole] = "directChats";
|
||||
roles[NameRole] = "name";
|
||||
roles[AvatarRole] = "avatar";
|
||||
roles[UserIDRole] = "userID";
|
||||
roles[DirectChatsRole] = "directChats";
|
||||
|
||||
return roles;
|
||||
return roles;
|
||||
}
|
||||
|
||||
int UserDirectoryListModel::rowCount(const QModelIndex& parent) const {
|
||||
if (parent.isValid())
|
||||
return 0;
|
||||
int UserDirectoryListModel::rowCount(const QModelIndex &parent) const
|
||||
{
|
||||
if (parent.isValid())
|
||||
return 0;
|
||||
|
||||
return users.count();
|
||||
return users.count();
|
||||
}
|
||||
|
||||
@@ -9,54 +9,62 @@
|
||||
|
||||
using namespace Quotient;
|
||||
|
||||
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(bool limited READ limited NOTIFY limitedChanged)
|
||||
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(bool limited READ limited NOTIFY limitedChanged)
|
||||
|
||||
public:
|
||||
enum EventRoles {
|
||||
NameRole = Qt::DisplayRole + 1,
|
||||
AvatarRole,
|
||||
UserIDRole,
|
||||
DirectChatsRole,
|
||||
};
|
||||
public:
|
||||
enum EventRoles {
|
||||
NameRole = Qt::DisplayRole + 1,
|
||||
AvatarRole,
|
||||
UserIDRole,
|
||||
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;
|
||||
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);
|
||||
Q_INVOKABLE void search(int count = 50);
|
||||
|
||||
private:
|
||||
Connection* m_connection = nullptr;
|
||||
QString m_keyword;
|
||||
bool m_limited = false;
|
||||
private:
|
||||
Connection *m_connection = nullptr;
|
||||
QString m_keyword;
|
||||
bool m_limited = false;
|
||||
|
||||
bool attempted = false;
|
||||
bool attempted = false;
|
||||
|
||||
QVector<SearchUserDirectoryJob::User> users;
|
||||
QVector<SearchUserDirectoryJob::User> users;
|
||||
|
||||
SearchUserDirectoryJob* job = nullptr;
|
||||
SearchUserDirectoryJob *job = nullptr;
|
||||
|
||||
signals:
|
||||
void connectionChanged();
|
||||
void keywordChanged();
|
||||
void limitedChanged();
|
||||
signals:
|
||||
void connectionChanged();
|
||||
void keywordChanged();
|
||||
void limitedChanged();
|
||||
};
|
||||
|
||||
#endif // USERDIRECTORYLISTMODEL_H
|
||||
#endif // USERDIRECTORYLISTMODEL_H
|
||||
|
||||
@@ -12,170 +12,185 @@
|
||||
|
||||
#include "spectraluser.h"
|
||||
|
||||
UserListModel::UserListModel(QObject* parent)
|
||||
: QAbstractListModel(parent), m_currentRoom(nullptr) {}
|
||||
|
||||
void UserListModel::setRoom(Quotient::Room* room) {
|
||||
if (m_currentRoom == room)
|
||||
return;
|
||||
|
||||
using namespace Quotient;
|
||||
beginResetModel();
|
||||
if (m_currentRoom) {
|
||||
m_currentRoom->disconnect(this);
|
||||
// m_currentRoom->connection()->disconnect(this);
|
||||
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);
|
||||
{
|
||||
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);});
|
||||
}
|
||||
connect(m_currentRoom->connection(), &Connection::loggedOut, this,
|
||||
[=] { setRoom(nullptr); });
|
||||
qDebug() << m_users.count() << "user(s) in the room";
|
||||
}
|
||||
endResetModel();
|
||||
emit roomChanged();
|
||||
UserListModel::UserListModel(QObject *parent)
|
||||
: QAbstractListModel(parent)
|
||||
, m_currentRoom(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
Quotient::User* UserListModel::userAt(QModelIndex index) const {
|
||||
if (index.row() < 0 || index.row() >= m_users.size())
|
||||
return nullptr;
|
||||
return m_users.at(index.row());
|
||||
void UserListModel::setRoom(Quotient::Room *room)
|
||||
{
|
||||
if (m_currentRoom == room)
|
||||
return;
|
||||
|
||||
using namespace Quotient;
|
||||
beginResetModel();
|
||||
if (m_currentRoom) {
|
||||
m_currentRoom->disconnect(this);
|
||||
// m_currentRoom->connection()->disconnect(this);
|
||||
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);
|
||||
{
|
||||
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);
|
||||
});
|
||||
}
|
||||
connect(m_currentRoom->connection(), &Connection::loggedOut, this, [=] {
|
||||
setRoom(nullptr);
|
||||
});
|
||||
qDebug() << m_users.count() << "user(s) in the room";
|
||||
}
|
||||
endResetModel();
|
||||
emit roomChanged();
|
||||
}
|
||||
|
||||
QVariant UserListModel::data(const QModelIndex& index, int role) const {
|
||||
if (!index.isValid())
|
||||
return QVariant();
|
||||
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
|
||||
{
|
||||
if (!index.isValid())
|
||||
return QVariant();
|
||||
|
||||
if (index.row() >= m_users.count()) {
|
||||
qDebug() << "UserListModel, something's wrong: index.row() >= m_users.count()";
|
||||
return {};
|
||||
}
|
||||
auto user = m_users.at(index.row());
|
||||
if (role == NameRole) {
|
||||
return user->displayname(m_currentRoom);
|
||||
}
|
||||
if (role == UserIDRole) {
|
||||
return user->id();
|
||||
}
|
||||
if (role == AvatarRole) {
|
||||
return user->avatarMediaId(m_currentRoom);
|
||||
}
|
||||
if (role == ObjectRole) {
|
||||
return QVariant::fromValue(user);
|
||||
}
|
||||
if (role == PermRole) {
|
||||
auto pl = m_currentRoom->getCurrentState<RoomPowerLevelsEvent>();
|
||||
auto userPl = pl->powerLevelForUser(user->id());
|
||||
|
||||
if (userPl == pl->content().usersDefault) { // Shortcut
|
||||
return UserType::Member;
|
||||
}
|
||||
|
||||
if (userPl < pl->powerLevelForState("m.room.message")) {
|
||||
return UserType::Muted;
|
||||
}
|
||||
|
||||
auto userPls = pl->users();
|
||||
|
||||
int highestPl = pl->usersDefault();
|
||||
QHash<QString, int>::const_iterator i = userPls.constBegin();
|
||||
while (i != userPls.constEnd()) {
|
||||
if (i.value() > highestPl) {
|
||||
highestPl = i.value();
|
||||
}
|
||||
|
||||
++i;
|
||||
}
|
||||
|
||||
if (userPl == highestPl) {
|
||||
return UserType::Owner;
|
||||
}
|
||||
|
||||
if (userPl >= pl->powerLevelForState("m.room.power_levels")) {
|
||||
return UserType::Admin;
|
||||
}
|
||||
|
||||
if (userPl >= pl->ban() || userPl >= pl->kick() || userPl >= pl->redact()) {
|
||||
return UserType::Moderator;
|
||||
}
|
||||
|
||||
return UserType::Member;
|
||||
}
|
||||
|
||||
if (index.row() >= m_users.count()) {
|
||||
qDebug()
|
||||
<< "UserListModel, something's wrong: index.row() >= m_users.count()";
|
||||
return {};
|
||||
}
|
||||
auto user = m_users.at(index.row());
|
||||
if (role == NameRole) {
|
||||
return user->displayname(m_currentRoom);
|
||||
}
|
||||
if (role == UserIDRole) {
|
||||
return user->id();
|
||||
}
|
||||
if (role == AvatarRole) {
|
||||
return user->avatarMediaId(m_currentRoom);
|
||||
}
|
||||
if (role == ObjectRole) {
|
||||
return QVariant::fromValue(user);
|
||||
}
|
||||
if (role == PermRole) {
|
||||
auto pl = m_currentRoom->getCurrentState<RoomPowerLevelsEvent>();
|
||||
auto userPl = pl->powerLevelForUser(user->id());
|
||||
|
||||
if (userPl == pl->content().usersDefault) { // Shortcut
|
||||
return UserType::Member;
|
||||
}
|
||||
|
||||
if (userPl < pl->powerLevelForState("m.room.message")) {
|
||||
return UserType::Muted;
|
||||
}
|
||||
|
||||
auto userPls = pl->users();
|
||||
|
||||
int highestPl = pl->usersDefault();
|
||||
QHash<QString, int>::const_iterator i = userPls.constBegin();
|
||||
while (i != userPls.constEnd()) {
|
||||
if (i.value() > highestPl) {
|
||||
highestPl = i.value();
|
||||
}
|
||||
|
||||
++i;
|
||||
}
|
||||
|
||||
if (userPl == highestPl) {
|
||||
return UserType::Owner;
|
||||
}
|
||||
|
||||
if (userPl >= pl->powerLevelForState("m.room.power_levels")) {
|
||||
return UserType::Admin;
|
||||
}
|
||||
|
||||
if (userPl >= pl->ban() || userPl >= pl->kick() || userPl >= pl->redact()) {
|
||||
return UserType::Moderator;
|
||||
}
|
||||
|
||||
return UserType::Member;
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
int UserListModel::rowCount(const QModelIndex& parent) const {
|
||||
if (parent.isValid())
|
||||
return 0;
|
||||
int UserListModel::rowCount(const QModelIndex &parent) const
|
||||
{
|
||||
if (parent.isValid())
|
||||
return 0;
|
||||
|
||||
return m_users.count();
|
||||
return m_users.count();
|
||||
}
|
||||
|
||||
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);});
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
void UserListModel::userRemoved(Quotient::User* user) {
|
||||
auto pos = findUserPos(user);
|
||||
if (pos != m_users.size()) {
|
||||
beginRemoveRows(QModelIndex(), pos, pos);
|
||||
m_users.removeAt(pos);
|
||||
endRemoveRows();
|
||||
user->disconnect(this);
|
||||
} else
|
||||
qWarning() << "Trying to remove a room member not in the user list";
|
||||
void UserListModel::userRemoved(Quotient::User *user)
|
||||
{
|
||||
auto pos = findUserPos(user);
|
||||
if (pos != m_users.size()) {
|
||||
beginRemoveRows(QModelIndex(), pos, pos);
|
||||
m_users.removeAt(pos);
|
||||
endRemoveRows();
|
||||
user->disconnect(this);
|
||||
} else
|
||||
qWarning() << "Trying to remove a room member not in the user list";
|
||||
}
|
||||
|
||||
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);
|
||||
else
|
||||
qWarning() << "Trying to access a room member not in the user list";
|
||||
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);
|
||||
else
|
||||
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 {
|
||||
return findUserPos(m_currentRoom->roomMembername(user));
|
||||
int UserListModel::findUserPos(User *user) const
|
||||
{
|
||||
return findUserPos(m_currentRoom->roomMembername(user));
|
||||
}
|
||||
|
||||
int UserListModel::findUserPos(const QString& username) const {
|
||||
return m_currentRoom->memberSorter().lowerBoundIndex(m_users, username);
|
||||
int UserListModel::findUserPos(const QString &username) const
|
||||
{
|
||||
return m_currentRoom->memberSorter().lowerBoundIndex(m_users, username);
|
||||
}
|
||||
|
||||
QHash<int, QByteArray> UserListModel::roleNames() const {
|
||||
QHash<int, QByteArray> roles;
|
||||
QHash<int, QByteArray> UserListModel::roleNames() const
|
||||
{
|
||||
QHash<int, QByteArray> roles;
|
||||
|
||||
roles[NameRole] = "name";
|
||||
roles[UserIDRole] = "userId";
|
||||
roles[AvatarRole] = "avatar";
|
||||
roles[ObjectRole] = "user";
|
||||
roles[PermRole] = "perm";
|
||||
roles[NameRole] = "name";
|
||||
roles[UserIDRole] = "userId";
|
||||
roles[AvatarRole] = "avatar";
|
||||
roles[ObjectRole] = "user";
|
||||
roles[PermRole] = "perm";
|
||||
|
||||
return roles;
|
||||
return roles;
|
||||
}
|
||||
|
||||
@@ -6,65 +6,70 @@
|
||||
#include <QObject>
|
||||
#include <QtCore/QAbstractListModel>
|
||||
|
||||
namespace Quotient {
|
||||
namespace Quotient
|
||||
{
|
||||
class Connection;
|
||||
class Room;
|
||||
class User;
|
||||
} // namespace Quotient
|
||||
} // namespace Quotient
|
||||
|
||||
class UserType : public QObject {
|
||||
Q_OBJECT
|
||||
class UserType : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
public:
|
||||
enum Types {
|
||||
Owner = 1,
|
||||
Admin,
|
||||
Moderator,
|
||||
Member,
|
||||
Muted,
|
||||
Owner = 1,
|
||||
Admin,
|
||||
Moderator,
|
||||
Member,
|
||||
Muted,
|
||||
};
|
||||
Q_ENUMS(Types)
|
||||
};
|
||||
|
||||
class UserListModel : public QAbstractListModel {
|
||||
Q_OBJECT
|
||||
Q_PROPERTY(
|
||||
Quotient::Room* room READ room WRITE setRoom NOTIFY roomChanged)
|
||||
public:
|
||||
enum EventRoles {
|
||||
NameRole = Qt::UserRole + 1,
|
||||
UserIDRole,
|
||||
AvatarRole,
|
||||
ObjectRole,
|
||||
PermRole,
|
||||
};
|
||||
class UserListModel : public QAbstractListModel
|
||||
{
|
||||
Q_OBJECT
|
||||
Q_PROPERTY(Quotient::Room *room READ room WRITE setRoom NOTIFY roomChanged)
|
||||
public:
|
||||
enum EventRoles {
|
||||
NameRole = Qt::UserRole + 1,
|
||||
UserIDRole,
|
||||
AvatarRole,
|
||||
ObjectRole,
|
||||
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;
|
||||
QHash<int, QByteArray> roleNames() const override;
|
||||
|
||||
signals:
|
||||
void roomChanged();
|
||||
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
|
||||
#endif // USERLISTMODEL_H
|
||||
|
||||
21
src/utils.h
21
src/utils.h
@@ -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
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user