--- /dev/null
+---
+Language: Cpp
+# BasedOnStyle: LLVM
+AccessModifierOffset: -4
+AlignAfterOpenBracket: Align
+AlignConsecutiveAssignments: false
+AlignConsecutiveDeclarations: false
+AlignEscapedNewlines: Right
+AlignOperands: true
+AlignTrailingComments: true
+AllowAllParametersOfDeclarationOnNextLine: true
+AllowShortBlocksOnASingleLine: false
+AllowShortCaseLabelsOnASingleLine: false
+AllowShortFunctionsOnASingleLine: Inline
+AllowShortIfStatementsOnASingleLine: false
+AllowShortLoopsOnASingleLine: false
+AlwaysBreakAfterDefinitionReturnType: None
+AlwaysBreakAfterReturnType: None
+AlwaysBreakBeforeMultilineStrings: false
+AlwaysBreakTemplateDeclarations: true
+BinPackArguments: false
+BinPackParameters: false
+BraceWrapping:
+ AfterClass: true
+ AfterControlStatement: false
+ AfterEnum: true
+ AfterFunction: true
+ AfterNamespace: false
+ AfterObjCDeclaration: false
+ AfterStruct: true
+ AfterUnion: false
+ AfterExternBlock: false
+ BeforeCatch: true
+ BeforeElse: true
+ IndentBraces: false
+ SplitEmptyFunction: true
+ SplitEmptyRecord: false
+ SplitEmptyNamespace: false
+BreakBeforeBinaryOperators: All
+BreakBeforeBraces: Custom
+BreakBeforeInheritanceComma: false
+BreakBeforeTernaryOperators: true
+BreakConstructorInitializers: BeforeComma
+BreakAfterJavaFieldAnnotations: false
+BreakStringLiterals: true
+ColumnLimit: 140
+CommentPragmas: '^ IWYU pragma:'
+CompactNamespaces: false
+ConstructorInitializerAllOnOneLineOrOnePerLine: false
+ConstructorInitializerIndentWidth: 4
+ContinuationIndentWidth: 4
+Cpp11BracedListStyle: true
+DerivePointerAlignment: false
+DisableFormat: false
+ExperimentalAutoDetectBinPacking: false
+FixNamespaceComments: true
+ForEachMacros:
+ - foreach
+ - Q_FOREACH
+ - BOOST_FOREACH
+IncludeBlocks: Regroup
+IncludeCategories:
+ - Regex: '^".*\-export\.h"'
+ Priority: -1
+ - Regex: '^<Q.*'
+ Priority: 3
+ - Regex: '^<.*\.h'
+ Priority: 4
+ - Regex: '<[[:alnum:]_]+>'
+ Priority: 1
+ - Regex: '<[.]*>'
+ Priority: 2
+ - Regex: '^"moc_.*"'
+ Priority: 9
+ - Regex: '^"ui_.*"'
+ Priority: 8
+ - Regex: '^".*/.*"'
+ Priority: 7
+ - Regex: '^".*"'
+ Priority: 6
+ - Regex: '.*'
+ Priority: 5
+IncludeIsMainRegex: '(Test)?$'
+IndentCaseLabels: false
+IndentPPDirectives: AfterHash
+IndentWidth: 4
+IndentWrappedFunctionNames: true
+JavaScriptQuotes: Leave
+JavaScriptWrapImports: true
+KeepEmptyLinesAtTheStartOfBlocks: false
+MacroBlockBegin: ''
+MacroBlockEnd: ''
+MaxEmptyLinesToKeep: 1
+NamespaceIndentation: None
+ObjCBlockIndentWidth: 2
+ObjCSpaceAfterProperty: false
+ObjCSpaceBeforeProtocolList: true
+PenaltyBreakAssignment: 200
+PenaltyBreakBeforeFirstCallParameter: 500
+PenaltyBreakComment: 300
+PenaltyBreakFirstLessLess: 120
+PenaltyBreakString: 1000
+PenaltyExcessCharacter: 10
+PenaltyReturnTypeOnItsOwnLine: 600
+PointerAlignment: Left
+ReflowComments: true
+SortIncludes: true
+SortUsingDeclarations: true
+SpaceAfterCStyleCast: false
+SpaceAfterTemplateKeyword: false
+SpaceBeforeAssignmentOperators: true
+SpaceBeforeCpp11BracedList: false
+SpaceBeforeCtorInitializerColon: true
+SpaceBeforeParens: ControlStatements
+SpaceBeforeRangeBasedForLoopColon: true
+SpaceInEmptyParentheses: false
+SpacesBeforeTrailingComments: 2
+SpacesInAngles: false
+SpacesInContainerLiterals: false
+SpacesInCStyleCastParentheses: false
+SpacesInParentheses: false
+SpacesInSquareBrackets: false
+Standard: Cpp11
+TabWidth: 8
+UseTab: Never
+...
#include "client.h"
-AbstractMessageProcessor::AbstractMessageProcessor(QObject *parent)
+AbstractMessageProcessor::AbstractMessageProcessor(QObject* parent)
: QObject(parent)
-{
-}
+{}
Q_OBJECT
public:
- AbstractMessageProcessor(QObject *parent);
+ AbstractMessageProcessor(QObject* parent);
virtual void reset() = 0;
public slots:
- virtual void process(Message &msg) = 0;
- virtual void process(QList<Message> &msgs) = 0;
+ virtual void process(Message& msg) = 0;
+ virtual void process(QList<Message>& msgs) = 0;
virtual void networkRemoved(NetworkId id) = 0;
protected:
// updateBufferActivity also sets the Message::Redirected flag which is later used
// to determine where a message should be displayed. therefore it's crucial that it
// is called before inserting the message into the model
- inline void preProcess(Message &msg) { Client::networkModel()->updateBufferActivity(msg); }
+ inline void preProcess(Message& msg) { Client::networkModel()->updateBufferActivity(msg); }
};
Q_OBJECT
public:
- AbstractUi(QObject *parent = nullptr) : QObject(parent) {}
- virtual void init() = 0; // called after the client is initialized
- virtual MessageModel *createMessageModel(QObject *parent) = 0;
- virtual AbstractMessageProcessor *createMessageProcessor(QObject *parent) = 0;
+ AbstractUi(QObject* parent = nullptr)
+ : QObject(parent)
+ {}
+ virtual void init() = 0; // called after the client is initialized
+ virtual MessageModel* createMessageModel(QObject* parent) = 0;
+ virtual AbstractMessageProcessor* createMessageProcessor(QObject* parent) = 0;
public slots:
virtual void connectedToCore() {}
virtual void disconnectedFromCore() {}
signals:
- void connectToCore(const QVariantMap &connInfo);
+ void connectToCore(const QVariantMap& connInfo);
void disconnectFromCore();
};
#include "bufferviewoverlay.h"
#include "clientbacklogmanager.h"
-BacklogRequester::BacklogRequester(bool buffering, RequesterType requesterType, ClientBacklogManager *backlogManager)
- : backlogManager(backlogManager),
- _isBuffering(buffering),
- _requesterType(requesterType),
- _totalBuffers(0)
+BacklogRequester::BacklogRequester(bool buffering, RequesterType requesterType, ClientBacklogManager* backlogManager)
+ : backlogManager(backlogManager)
+ , _isBuffering(buffering)
+ , _requesterType(requesterType)
+ , _totalBuffers(0)
{
Q_ASSERT(backlogManager);
}
-
-void BacklogRequester::setWaitingBuffers(const QSet<BufferId> &buffers)
+void BacklogRequester::setWaitingBuffers(const QSet<BufferId>& buffers)
{
_buffersWaiting = buffers;
_totalBuffers = _buffersWaiting.count();
}
-
void BacklogRequester::addWaitingBuffer(BufferId buffer)
{
_buffersWaiting << buffer;
_totalBuffers++;
}
-
-bool BacklogRequester::buffer(BufferId bufferId, const MessageList &messages)
+bool BacklogRequester::buffer(BufferId bufferId, const MessageList& messages)
{
_bufferedMessages << messages;
_buffersWaiting.remove(bufferId);
return !_buffersWaiting.isEmpty();
}
-
BufferIdList BacklogRequester::allBufferIds() const
{
QSet<BufferId> bufferIds = Client::bufferViewOverlay()->bufferIds();
return bufferIds.toList();
}
-
void BacklogRequester::flushBuffer()
{
if (!_buffersWaiting.isEmpty()) {
- qWarning() << Q_FUNC_INFO << "was called before all backlog was received:"
- << _buffersWaiting.count() << "buffers are waiting.";
+ qWarning() << Q_FUNC_INFO << "was called before all backlog was received:" << _buffersWaiting.count() << "buffers are waiting.";
}
_bufferedMessages.clear();
_totalBuffers = 0;
_buffersWaiting.clear();
}
-
// ========================================
// FIXED BACKLOG REQUESTER
// ========================================
-FixedBacklogRequester::FixedBacklogRequester(ClientBacklogManager *backlogManager)
+FixedBacklogRequester::FixedBacklogRequester(ClientBacklogManager* backlogManager)
: BacklogRequester(true, BacklogRequester::PerBufferFixed, backlogManager)
{
BacklogSettings backlogSettings;
_backlogCount = backlogSettings.fixedBacklogAmount();
}
-
-void FixedBacklogRequester::requestBacklog(const BufferIdList &bufferIds)
+void FixedBacklogRequester::requestBacklog(const BufferIdList& bufferIds)
{
setWaitingBuffers(bufferIds);
- backlogManager->emitMessagesRequested(QObject::tr("Requesting a total of up to %1 backlog messages for %2 buffers").arg(_backlogCount * bufferIds.count()).arg(bufferIds.count()));
- foreach(BufferId bufferId, bufferIds) {
+ backlogManager->emitMessagesRequested(QObject::tr("Requesting a total of up to %1 backlog messages for %2 buffers")
+ .arg(_backlogCount * bufferIds.count())
+ .arg(bufferIds.count()));
+ foreach (BufferId bufferId, bufferIds) {
backlogManager->requestBacklog(bufferId, -1, -1, _backlogCount);
}
}
-
// ========================================
// GLOBAL UNREAD BACKLOG REQUESTER
// ========================================
-GlobalUnreadBacklogRequester::GlobalUnreadBacklogRequester(ClientBacklogManager *backlogManager)
+GlobalUnreadBacklogRequester::GlobalUnreadBacklogRequester(ClientBacklogManager* backlogManager)
: BacklogRequester(false, BacklogRequester::GlobalUnread, backlogManager)
{
BacklogSettings backlogSettings;
_additional = backlogSettings.globalUnreadBacklogAdditional();
}
-
void GlobalUnreadBacklogRequester::requestInitialBacklog()
{
MsgId oldestUnreadMessage;
- foreach(BufferId bufferId, allBufferIds()) {
+ foreach (BufferId bufferId, allBufferIds()) {
MsgId msgId = Client::networkModel()->lastSeenMsgId(bufferId);
if (!oldestUnreadMessage.isValid() || oldestUnreadMessage > msgId)
oldestUnreadMessage = msgId;
}
- backlogManager->emitMessagesRequested(QObject::tr("Requesting up to %1 of all unread backlog messages (plus additional %2)").arg(_limit).arg(_additional));
+ backlogManager->emitMessagesRequested(
+ QObject::tr("Requesting up to %1 of all unread backlog messages (plus additional %2)").arg(_limit).arg(_additional));
backlogManager->requestBacklogAll(oldestUnreadMessage, -1, _limit, _additional);
}
-
// ========================================
// PER BUFFER UNREAD BACKLOG REQUESTER
// ========================================
-PerBufferUnreadBacklogRequester::PerBufferUnreadBacklogRequester(ClientBacklogManager *backlogManager)
+PerBufferUnreadBacklogRequester::PerBufferUnreadBacklogRequester(ClientBacklogManager* backlogManager)
: BacklogRequester(true, BacklogRequester::PerBufferUnread, backlogManager)
{
BacklogSettings backlogSettings;
_additional = backlogSettings.perBufferUnreadBacklogAdditional();
}
-
-void PerBufferUnreadBacklogRequester::requestBacklog(const BufferIdList &bufferIds)
+void PerBufferUnreadBacklogRequester::requestBacklog(const BufferIdList& bufferIds)
{
setWaitingBuffers(bufferIds);
- backlogManager->emitMessagesRequested(QObject::tr("Requesting a total of up to %1 unread backlog messages for %2 buffers").arg((_limit + _additional) * bufferIds.count()).arg(bufferIds.count()));
- foreach(BufferId bufferId, bufferIds) {
+ backlogManager->emitMessagesRequested(QObject::tr("Requesting a total of up to %1 unread backlog messages for %2 buffers")
+ .arg((_limit + _additional) * bufferIds.count())
+ .arg(bufferIds.count()));
+ foreach (BufferId bufferId, bufferIds) {
backlogManager->requestBacklog(bufferId, Client::networkModel()->lastSeenMsgId(bufferId), -1, _limit, _additional);
}
}
class BacklogRequester
{
public:
- enum RequesterType {
+ enum RequesterType
+ {
InvalidRequester = 0,
PerBufferFixed,
PerBufferUnread,
GlobalUnread
};
- BacklogRequester(bool buffering, RequesterType requesterType, ClientBacklogManager *backlogManger);
+ BacklogRequester(bool buffering, RequesterType requesterType, ClientBacklogManager* backlogManger);
virtual ~BacklogRequester() = default;
inline bool isBuffering() { return _isBuffering; }
inline RequesterType type() { return _requesterType; }
- inline const QList<Message> &bufferedMessages() { return _bufferedMessages; }
+ inline const QList<Message>& bufferedMessages() { return _bufferedMessages; }
inline int buffersWaiting() const { return _buffersWaiting.count(); }
inline int totalBuffers() const { return _totalBuffers; }
- bool buffer(BufferId bufferId, const MessageList &messages); //! returns false if it was the last missing backlogpart
+ bool buffer(BufferId bufferId, const MessageList& messages); //! returns false if it was the last missing backlogpart
- virtual void requestBacklog(const BufferIdList &bufferIds) = 0;
+ virtual void requestBacklog(const BufferIdList& bufferIds) = 0;
virtual inline void requestInitialBacklog() { requestBacklog(allBufferIds()); }
virtual void flushBuffer();
protected:
BufferIdList allBufferIds() const;
- inline void setWaitingBuffers(const QList<BufferId> &buffers) { setWaitingBuffers(buffers.toSet()); }
- void setWaitingBuffers(const QSet<BufferId> &buffers);
+ inline void setWaitingBuffers(const QList<BufferId>& buffers) { setWaitingBuffers(buffers.toSet()); }
+ void setWaitingBuffers(const QSet<BufferId>& buffers);
void addWaitingBuffer(BufferId buffer);
- ClientBacklogManager *backlogManager;
+ ClientBacklogManager* backlogManager;
private:
bool _isBuffering;
QSet<BufferId> _buffersWaiting;
};
-
// ========================================
// FIXED BACKLOG REQUESTER
// ========================================
class FixedBacklogRequester : public BacklogRequester
{
public:
- FixedBacklogRequester(ClientBacklogManager *backlogManager);
- void requestBacklog(const BufferIdList &bufferIds) override;
+ FixedBacklogRequester(ClientBacklogManager* backlogManager);
+ void requestBacklog(const BufferIdList& bufferIds) override;
private:
int _backlogCount;
};
-
// ========================================
// GLOBAL UNREAD BACKLOG REQUESTER
// ========================================
class GlobalUnreadBacklogRequester : public BacklogRequester
{
public:
- GlobalUnreadBacklogRequester(ClientBacklogManager *backlogManager);
+ GlobalUnreadBacklogRequester(ClientBacklogManager* backlogManager);
void requestInitialBacklog() override;
- void requestBacklog(const BufferIdList &) override {}
+ void requestBacklog(const BufferIdList&) override {}
private:
int _limit;
int _additional;
};
-
// ========================================
// PER BUFFER UNREAD BACKLOG REQUESTER
// ========================================
class PerBufferUnreadBacklogRequester : public BacklogRequester
{
public:
- PerBufferUnreadBacklogRequester(ClientBacklogManager *backlogManager);
- void requestBacklog(const BufferIdList &bufferIds) override;
+ PerBufferUnreadBacklogRequester(ClientBacklogManager* backlogManager);
+ void requestBacklog(const BufferIdList& bufferIds) override;
private:
int _limit;
int _additional;
};
-
-#endif //BACKLOGREQUESTER_H
+#endif // BACKLOGREQUESTER_H
: ClientSettings("Backlog")
{}
-
int BacklogSettings::requesterType() const
{
return localValue("RequesterType", BacklogRequester::PerBufferUnread).toInt();
}
-
void BacklogSettings::setRequesterType(int requesterType)
{
setLocalValue("RequesterType", requesterType);
}
-
int BacklogSettings::dynamicBacklogAmount() const
{
return localValue("DynamicBacklogAmount", 200).toInt();
}
-
void BacklogSettings::setDynamicBacklogAmount(int amount)
{
return setLocalValue("DynamicBacklogAmount", amount);
}
-
int BacklogSettings::fixedBacklogAmount() const
{
return localValue("FixedBacklogAmount", 500).toInt();
}
-
void BacklogSettings::setFixedBacklogAmount(int amount)
{
return setLocalValue("FixedBacklogAmount", amount);
}
-
int BacklogSettings::globalUnreadBacklogLimit() const
{
return localValue("GlobalUnreadBacklogLimit", 5000).toInt();
}
-
void BacklogSettings::setGlobalUnreadBacklogLimit(int limit)
{
return setLocalValue("GlobalUnreadBacklogLimit", limit);
}
-
int BacklogSettings::globalUnreadBacklogAdditional() const
{
return localValue("GlobalUnreadBacklogAdditional", 100).toInt();
}
-
void BacklogSettings::setGlobalUnreadBacklogAdditional(int additional)
{
return setLocalValue("GlobalUnreadBacklogAdditional", additional);
}
-
int BacklogSettings::perBufferUnreadBacklogLimit() const
{
return localValue("PerBufferUnreadBacklogLimit", 200).toInt();
}
-
void BacklogSettings::setPerBufferUnreadBacklogLimit(int limit)
{
return setLocalValue("PerBufferUnreadBacklogLimit", limit);
}
-
int BacklogSettings::perBufferUnreadBacklogAdditional() const
{
return localValue("PerBufferUnreadBacklogAdditional", 50).toInt();
}
-
void BacklogSettings::setPerBufferUnreadBacklogAdditional(int additional)
{
return setLocalValue("PerBufferUnreadBacklogAdditional", additional);
#include "networkmodel.h"
#include "quassel.h"
-BufferModel::BufferModel(NetworkModel *parent)
- : QSortFilterProxyModel(parent),
- _selectionModelSynchronizer(this)
+BufferModel::BufferModel(NetworkModel* parent)
+ : QSortFilterProxyModel(parent)
+ , _selectionModelSynchronizer(this)
{
setSourceModel(parent);
if (Quassel::isOptionSet("debugbufferswitches")) {
- connect(_selectionModelSynchronizer.selectionModel(), &QItemSelectionModel::currentChanged,
- this, &BufferModel::debug_currentChanged);
+ connect(_selectionModelSynchronizer.selectionModel(), &QItemSelectionModel::currentChanged, this, &BufferModel::debug_currentChanged);
}
connect(Client::instance(), &Client::networkCreated, this, &BufferModel::newNetwork);
connect(this, &QAbstractItemModel::rowsInserted, this, &BufferModel::newBuffers);
}
-
-bool BufferModel::filterAcceptsRow(int sourceRow, const QModelIndex &parent) const
+bool BufferModel::filterAcceptsRow(int sourceRow, const QModelIndex& parent) const
{
Q_UNUSED(sourceRow);
// only networks and buffers are allowed
return false;
}
-
void BufferModel::newNetwork(NetworkId id)
{
- const Network *net = Client::network(id);
+ const Network* net = Client::network(id);
Q_ASSERT(net);
- connect(net, &Network::connectionStateSet,
- this, &BufferModel::networkConnectionChanged);
+ connect(net, &Network::connectionStateSet, this, &BufferModel::networkConnectionChanged);
}
-
void BufferModel::networkConnectionChanged(Network::ConnectionState state)
{
switch (state) {
if (currentIndex().isValid())
return;
{
- auto *net = qobject_cast<Network *>(sender());
+ auto* net = qobject_cast<Network*>(sender());
Q_ASSERT(net);
setCurrentIndex(mapFromSource(Client::networkModel()->networkIndex(net->networkId())));
}
}
}
-
-void BufferModel::synchronizeView(QAbstractItemView *view)
+void BufferModel::synchronizeView(QAbstractItemView* view)
{
_selectionModelSynchronizer.synchronizeSelectionModel(view->selectionModel());
}
-
-void BufferModel::setCurrentIndex(const QModelIndex &newCurrent)
+void BufferModel::setCurrentIndex(const QModelIndex& newCurrent)
{
_selectionModelSynchronizer.selectionModel()->setCurrentIndex(newCurrent, QItemSelectionModel::Current);
_selectionModelSynchronizer.selectionModel()->select(newCurrent, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
}
-
-void BufferModel::switchToBuffer(const BufferId &bufferId)
+void BufferModel::switchToBuffer(const BufferId& bufferId)
{
QModelIndex source_index = Client::networkModel()->bufferIndex(bufferId);
setCurrentIndex(mapFromSource(source_index));
}
-
-void BufferModel::switchToBufferIndex(const QModelIndex &bufferIdx)
+void BufferModel::switchToBufferIndex(const QModelIndex& bufferIdx)
{
// we accept indexes that directly belong to us or our parent - nothing else
if (bufferIdx.model() == this) {
qWarning() << "BufferModel::switchToBufferIndex(const QModelIndex &):" << bufferIdx << "does not belong to BufferModel or NetworkModel";
}
-
-void BufferModel::switchToOrJoinBuffer(NetworkId networkId, const QString &name, bool isQuery)
+void BufferModel::switchToOrJoinBuffer(NetworkId networkId, const QString& name, bool isQuery)
{
BufferId bufId = Client::networkModel()->bufferId(networkId, name);
if (bufId.isValid()) {
}
}
-
void BufferModel::debug_currentChanged(QModelIndex current, QModelIndex previous)
{
Q_UNUSED(previous);
- qDebug() << "Switched current Buffer: " << current << current.data().toString() << "Buffer:" << current.data(NetworkModel::BufferIdRole).value<BufferId>();
+ qDebug() << "Switched current Buffer: " << current << current.data().toString()
+ << "Buffer:" << current.data(NetworkModel::BufferIdRole).value<BufferId>();
}
-
-void BufferModel::newBuffers(const QModelIndex &parent, int start, int end)
+void BufferModel::newBuffers(const QModelIndex& parent, int start, int end)
{
if (parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
return;
}
}
-
void BufferModel::newBuffer(BufferId bufferId)
{
BufferInfo bufferInfo = Client::networkModel()->bufferInfo(bufferId);
- if (_bufferToSwitchTo.first == bufferInfo.networkId()
- && _bufferToSwitchTo.second == bufferInfo.bufferName()) {
+ if (_bufferToSwitchTo.first == bufferInfo.networkId() && _bufferToSwitchTo.second == bufferInfo.bufferName()) {
_bufferToSwitchTo.first = 0;
_bufferToSwitchTo.second.clear();
switchToBuffer(bufferId);
}
}
-
-void BufferModel::switchToBufferAfterCreation(NetworkId network, const QString &name)
+void BufferModel::switchToBufferAfterCreation(NetworkId network, const QString& name)
{
_bufferToSwitchTo = qMakePair(network, name);
}
#include "client-export.h"
-#include <QSortFilterProxyModel>
#include <QItemSelectionModel>
#include <QPair>
+#include <QSortFilterProxyModel>
#include "network.h"
#include "networkmodel.h"
-#include "types.h"
#include "selectionmodelsynchronizer.h"
+#include "types.h"
class QAbstractItemView;
Q_OBJECT
public:
- BufferModel(NetworkModel *parent = nullptr);
+ BufferModel(NetworkModel* parent = nullptr);
- bool filterAcceptsRow(int sourceRow, const QModelIndex &parent) const override;
+ bool filterAcceptsRow(int sourceRow, const QModelIndex& parent) const override;
- inline const SelectionModelSynchronizer *selectionModelSynchronizer() const { return &_selectionModelSynchronizer; }
- inline QItemSelectionModel *standardSelectionModel() const { return _selectionModelSynchronizer.selectionModel(); }
+ inline const SelectionModelSynchronizer* selectionModelSynchronizer() const { return &_selectionModelSynchronizer; }
+ inline QItemSelectionModel* standardSelectionModel() const { return _selectionModelSynchronizer.selectionModel(); }
- inline void synchronizeSelectionModel(QItemSelectionModel *selectionModel) { _selectionModelSynchronizer.synchronizeSelectionModel(selectionModel); }
- void synchronizeView(QAbstractItemView *view);
+ inline void synchronizeSelectionModel(QItemSelectionModel* selectionModel)
+ {
+ _selectionModelSynchronizer.synchronizeSelectionModel(selectionModel);
+ }
+ void synchronizeView(QAbstractItemView* view);
inline QModelIndex currentIndex() { return standardSelectionModel()->currentIndex(); }
inline BufferId currentBuffer() { return currentIndex().data(NetworkModel::BufferIdRole).value<BufferId>(); }
public slots:
- void setCurrentIndex(const QModelIndex &newCurrent);
- void switchToBuffer(const BufferId &bufferId);
- void switchToBufferIndex(const QModelIndex &bufferIdx);
- void switchToOrJoinBuffer(NetworkId network, const QString &bufferName, bool isQuery = false);
- void switchToOrStartQuery(NetworkId network, const QString &nick)
- {
- switchToOrJoinBuffer(network, nick, true);
- }
-
+ void setCurrentIndex(const QModelIndex& newCurrent);
+ void switchToBuffer(const BufferId& bufferId);
+ void switchToBufferIndex(const QModelIndex& bufferIdx);
+ void switchToOrJoinBuffer(NetworkId network, const QString& bufferName, bool isQuery = false);
+ void switchToOrStartQuery(NetworkId network, const QString& nick) { switchToOrJoinBuffer(network, nick, true); }
- void switchToBufferAfterCreation(NetworkId network, const QString &name);
+ void switchToBufferAfterCreation(NetworkId network, const QString& name);
private slots:
void debug_currentChanged(QModelIndex current, QModelIndex previous);
void newNetwork(NetworkId id);
void networkConnectionChanged(Network::ConnectionState state);
- void newBuffers(const QModelIndex &parent, int start, int end);
+ void newBuffers(const QModelIndex& parent, int start, int end);
private:
void newBuffer(BufferId bufferId);
BufferSettings::BufferSettings(BufferId bufferId)
: ClientSettings(QString("Buffer/%1").arg(bufferId.toInt()))
-{
-}
-
+{}
-BufferSettings::BufferSettings(const QString &idString)
+BufferSettings::BufferSettings(const QString& idString)
: ClientSettings(QString("Buffer/%1").arg(idString))
-{
-}
+{}
-
-void BufferSettings::setValue(const QString &key, const QVariant &data)
+void BufferSettings::setValue(const QString& key, const QVariant& data)
{
setLocalValue(key, data);
}
-
-QVariant BufferSettings::value(const QString &key, const QVariant &def) const
+QVariant BufferSettings::value(const QString& key, const QVariant& def) const
{
return localValue(key, def);
}
-
void BufferSettings::filterMessage(Message::Type msgType, bool filter)
{
if (!hasFilter())
setLocalValue("MessageTypeFilter", localValue("MessageTypeFilter", 0).toInt() & ~msgType);
}
-
bool BufferSettings::hasFilter() const
{
return localValue("hasMessageTypeFilter", false).toBool();
}
-
int BufferSettings::messageFilter() const
{
return localValue("MessageTypeFilter", 0).toInt();
}
-
void BufferSettings::setMessageFilter(int filter)
{
if (!hasFilter())
setLocalValue("MessageTypeFilter", filter);
}
-
void BufferSettings::removeFilter()
{
setLocalValue("hasMessageTypeFilter", false);
removeLocalKey("MessageTypeFilter");
}
-
bool BufferSettings::showUserStateIcons() const
{
return localValue("ShowUserStateIcons", true).toBool();
}
-
void BufferSettings::enableUserStateIcons(bool enabled)
{
setLocalValue("ShowUserStateIcons", enabled);
}
-
int BufferSettings::userNoticesTarget() const
{
return localValue("UserNoticesTarget", RedirectTarget::DefaultBuffer | RedirectTarget::CurrentBuffer).toInt();
}
-
void BufferSettings::setUserNoticesTarget(int target)
{
setLocalValue("UserNoticesTarget", target);
}
-
int BufferSettings::serverNoticesTarget() const
{
return localValue("ServerNoticesTarget", RedirectTarget::StatusBuffer).toInt();
}
-
void BufferSettings::setServerNoticesTarget(int target)
{
setLocalValue("ServerNoticesTarget", target);
}
-
int BufferSettings::errorMsgsTarget() const
{
return localValue("ErrorMsgsTarget", RedirectTarget::DefaultBuffer).toInt();
}
-
void BufferSettings::setErrorMsgsTarget(int target)
{
setLocalValue("ErrorMsgsTarget", target);
class CLIENT_EXPORT BufferSettings : public ClientSettings
{
public:
- enum RedirectTarget {
+ enum RedirectTarget
+ {
DefaultBuffer = 0x01,
- StatusBuffer = 0x02,
+ StatusBuffer = 0x02,
CurrentBuffer = 0x04
};
- BufferSettings(const QString &idString = "__default__");
+ BufferSettings(const QString& idString = "__default__");
BufferSettings(BufferId bufferId);
- void setValue(const QString &key, const QVariant &data);
- QVariant value(const QString &key, const QVariant &def = {}) const;
+ void setValue(const QString& key, const QVariant& data);
+ QVariant value(const QString& key, const QVariant& def = {}) const;
// Message Filter (default and per view)
bool hasFilter() const;
const int BufferViewOverlay::_updateEventId = QEvent::registerEventType();
-BufferViewOverlay::BufferViewOverlay(QObject *parent)
+BufferViewOverlay::BufferViewOverlay(QObject* parent)
: QObject(parent)
-{
-}
-
+{}
void BufferViewOverlay::reset()
{
_tempRemovedBuffers.clear();
}
-
void BufferViewOverlay::save()
{
CoreAccountSettings().setBufferViewOverlay(_bufferViewIds);
}
-
void BufferViewOverlay::restore()
{
QSet<int> currentIds = _bufferViewIds;
}
}
-
void BufferViewOverlay::addView(int viewId)
{
if (_bufferViewIds.contains(viewId))
return;
- BufferViewConfig *config = Client::bufferViewManager()->bufferViewConfig(viewId);
+ BufferViewConfig* config = Client::bufferViewManager()->bufferViewConfig(viewId);
if (!config) {
qDebug() << "BufferViewOverlay::addView(): no such buffer view:" << viewId;
return;
if (wasInitialized) {
BufferIdList buffers;
if (config->networkId().isValid()) {
- foreach(BufferId bufferId, config->bufferList()) {
+ foreach (BufferId bufferId, config->bufferList()) {
if (Client::networkModel()->networkId(bufferId) == config->networkId())
buffers << bufferId;
}
- foreach(BufferId bufferId, config->temporarilyRemovedBuffers().toList()) {
+ foreach (BufferId bufferId, config->temporarilyRemovedBuffers().toList()) {
if (Client::networkModel()->networkId(bufferId) == config->networkId())
buffers << bufferId;
}
save();
}
-
void BufferViewOverlay::removeView(int viewId)
{
if (!_bufferViewIds.contains(viewId))
return;
_bufferViewIds.remove(viewId);
- BufferViewConfig *config = Client::bufferViewManager()->bufferViewConfig(viewId);
+ BufferViewConfig* config = Client::bufferViewManager()->bufferViewConfig(viewId);
if (config)
disconnect(config, nullptr, this, nullptr);
save();
}
-
-void BufferViewOverlay::viewInitialized(BufferViewConfig *config)
+void BufferViewOverlay::viewInitialized(BufferViewConfig* config)
{
if (!config) {
qWarning() << "BufferViewOverlay::viewInitialized() received invalid view!";
emit initDone();
}
-
void BufferViewOverlay::viewInitialized()
{
- auto *config = qobject_cast<BufferViewConfig *>(sender());
+ auto* config = qobject_cast<BufferViewConfig*>(sender());
Q_ASSERT(config);
viewInitialized(config);
}
-
void BufferViewOverlay::update()
{
if (_aboutToUpdate) {
QCoreApplication::postEvent(this, new QEvent((QEvent::Type)_updateEventId));
}
-
void BufferViewOverlay::updateHelper()
{
if (!_aboutToUpdate)
QSet<BufferId> tempRemovedBuffers;
if (Client::bufferViewManager()) {
- BufferViewConfig *config = nullptr;
+ BufferViewConfig* config = nullptr;
QSet<int>::const_iterator viewIter;
for (viewIter = _bufferViewIds.constBegin(); viewIter != _bufferViewIds.constEnd(); ++viewIter) {
config = Client::bufferViewManager()->bufferViewConfig(*viewIter);
emit hasChanged();
}
-
-QSet<BufferId> BufferViewOverlay::filterBuffersByConfig(const QList<BufferId> &buffers, const BufferViewConfig *config)
+QSet<BufferId> BufferViewOverlay::filterBuffersByConfig(const QList<BufferId>& buffers, const BufferViewConfig* config)
{
Q_ASSERT(config);
QSet<BufferId> bufferIds;
BufferInfo bufferInfo;
- foreach(BufferId bufferId, buffers) {
+ foreach (BufferId bufferId, buffers) {
bufferInfo = Client::networkModel()->bufferInfo(bufferId);
if (!(bufferInfo.type() & config->allowedBufferTypes()))
continue;
return bufferIds;
}
-
-void BufferViewOverlay::customEvent(QEvent *event)
+void BufferViewOverlay::customEvent(QEvent* event)
{
if (event->type() == _updateEventId) {
updateHelper();
}
}
-
bool BufferViewOverlay::allNetworks()
{
updateHelper();
return _networkIds.contains(NetworkId());
}
-
-const QSet<NetworkId> &BufferViewOverlay::networkIds()
+const QSet<NetworkId>& BufferViewOverlay::networkIds()
{
updateHelper();
return _networkIds;
}
-
-const QSet<BufferId> &BufferViewOverlay::bufferIds()
+const QSet<BufferId>& BufferViewOverlay::bufferIds()
{
updateHelper();
return _buffers;
}
-
-const QSet<BufferId> &BufferViewOverlay::removedBufferIds()
+const QSet<BufferId>& BufferViewOverlay::removedBufferIds()
{
updateHelper();
return _removedBuffers;
}
-
-const QSet<BufferId> &BufferViewOverlay::tempRemovedBufferIds()
+const QSet<BufferId>& BufferViewOverlay::tempRemovedBufferIds()
{
updateHelper();
return _tempRemovedBuffers;
}
-
int BufferViewOverlay::allowedBufferTypes()
{
updateHelper();
return _allowedBufferTypes;
}
-
int BufferViewOverlay::minimumActivity()
{
updateHelper();
Q_OBJECT
public:
- BufferViewOverlay(QObject *parent = nullptr);
+ BufferViewOverlay(QObject* parent = nullptr);
- inline const QSet<int> &bufferViewIds() { return _bufferViewIds; }
+ inline const QSet<int>& bufferViewIds() { return _bufferViewIds; }
bool allNetworks();
- const QSet<NetworkId> &networkIds();
- const QSet<BufferId> &bufferIds();
- const QSet<BufferId> &removedBufferIds();
- const QSet<BufferId> &tempRemovedBufferIds();
+ const QSet<NetworkId>& networkIds();
+ const QSet<BufferId>& bufferIds();
+ const QSet<BufferId>& removedBufferIds();
+ const QSet<BufferId>& tempRemovedBufferIds();
int allowedBufferTypes();
int minimumActivity();
void initDone();
protected:
- void customEvent(QEvent *event) override;
+ void customEvent(QEvent* event) override;
private slots:
void viewInitialized();
- void viewInitialized(BufferViewConfig *config);
+ void viewInitialized(BufferViewConfig* config);
private:
void updateHelper();
- QSet<BufferId> filterBuffersByConfig(const QList<BufferId> &buffers, const BufferViewConfig *config);
+ QSet<BufferId> filterBuffersByConfig(const QList<BufferId>& buffers, const BufferViewConfig* config);
bool _aboutToUpdate{false};
#include "client.h"
+#include <cstdio>
+#include <cstdlib>
+
#include "abstractmessageprocessor.h"
#include "abstractui.h"
#include "bufferinfo.h"
#include "bufferviewconfig.h"
#include "bufferviewoverlay.h"
#include "clientaliasmanager.h"
+#include "clientauthhandler.h"
#include "clientbacklogmanager.h"
#include "clientbufferviewmanager.h"
-#include "clientirclisthelper.h"
#include "clientidentity.h"
#include "clientignorelistmanager.h"
+#include "clientirclisthelper.h"
#include "clienttransfermanager.h"
#include "clientuserinputhandler.h"
#include "coreaccountmodel.h"
#include "signalproxy.h"
#include "transfermodel.h"
#include "util.h"
-#include "clientauthhandler.h"
-#include <cstdio>
-#include <cstdlib>
-
-Client::Client(std::unique_ptr<AbstractUi> ui, QObject *parent)
- : QObject(parent), Singleton<Client>(this),
- _signalProxy(new SignalProxy(SignalProxy::Client, this)),
- _mainUi(std::move(ui)),
- _networkModel(new NetworkModel(this)),
- _bufferModel(new BufferModel(_networkModel)),
- _backlogManager(new ClientBacklogManager(this)),
- _bufferViewOverlay(new BufferViewOverlay(this)),
- _coreInfo(new CoreInfo(this)),
- _ircListHelper(new ClientIrcListHelper(this)),
- _inputHandler(new ClientUserInputHandler(this)),
- _transferModel(new TransferModel(this)),
- _messageModel(_mainUi->createMessageModel(this)),
- _messageProcessor(_mainUi->createMessageProcessor(this)),
- _coreAccountModel(new CoreAccountModel(this)),
- _coreConnection(new CoreConnection(this))
+Client::Client(std::unique_ptr<AbstractUi> ui, QObject* parent)
+ : QObject(parent)
+ , Singleton<Client>(this)
+ , _signalProxy(new SignalProxy(SignalProxy::Client, this))
+ , _mainUi(std::move(ui))
+ , _networkModel(new NetworkModel(this))
+ , _bufferModel(new BufferModel(_networkModel))
+ , _backlogManager(new ClientBacklogManager(this))
+ , _bufferViewOverlay(new BufferViewOverlay(this))
+ , _coreInfo(new CoreInfo(this))
+ , _ircListHelper(new ClientIrcListHelper(this))
+ , _inputHandler(new ClientUserInputHandler(this))
+ , _transferModel(new TransferModel(this))
+ , _messageModel(_mainUi->createMessageModel(this))
+ , _messageProcessor(_mainUi->createMessageProcessor(this))
+ , _coreAccountModel(new CoreAccountModel(this))
+ , _coreConnection(new CoreConnection(this))
{
#ifdef EMBED_DATA
Q_INIT_RESOURCE(data);
connect(backlogManager(), &ClientBacklogManager::messagesReceived, _messageModel, &MessageModel::messagesReceived);
connect(coreConnection(), &CoreConnection::stateChanged, this, &Client::connectionStateChanged);
- SignalProxy *p = signalProxy();
+ SignalProxy* p = signalProxy();
- p->attachSlot(SIGNAL(displayMsg(const Message &)), this, SLOT(recvMessage(const Message &)));
+ p->attachSlot(SIGNAL(displayMsg(const Message&)), this, SLOT(recvMessage(const Message&)));
p->attachSlot(SIGNAL(displayStatusMsg(QString, QString)), this, SLOT(recvStatusMsg(QString, QString)));
p->attachSlot(SIGNAL(bufferInfoUpdated(BufferInfo)), _networkModel, SLOT(bufferUpdated(BufferInfo)));
p->attachSignal(inputHandler(), SIGNAL(sendInput(BufferInfo, QString)));
p->attachSignal(this, SIGNAL(requestNetworkStates()));
- p->attachSignal(this, SIGNAL(requestCreateIdentity(const Identity &, const QVariantMap &)), SIGNAL(createIdentity(const Identity &, const QVariantMap &)));
+ p->attachSignal(this,
+ SIGNAL(requestCreateIdentity(const Identity&, const QVariantMap&)),
+ SIGNAL(createIdentity(const Identity&, const QVariantMap&)));
p->attachSignal(this, SIGNAL(requestRemoveIdentity(IdentityId)), SIGNAL(removeIdentity(IdentityId)));
- p->attachSlot(SIGNAL(identityCreated(const Identity &)), this, SLOT(coreIdentityCreated(const Identity &)));
+ p->attachSlot(SIGNAL(identityCreated(const Identity&)), this, SLOT(coreIdentityCreated(const Identity&)));
p->attachSlot(SIGNAL(identityRemoved(IdentityId)), this, SLOT(coreIdentityRemoved(IdentityId)));
- p->attachSignal(this, SIGNAL(requestCreateNetwork(const NetworkInfo &, const QStringList &)), SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)));
+ p->attachSignal(this,
+ SIGNAL(requestCreateNetwork(const NetworkInfo&, const QStringList&)),
+ SIGNAL(createNetwork(const NetworkInfo&, const QStringList&)));
p->attachSignal(this, SIGNAL(requestRemoveNetwork(NetworkId)), SIGNAL(removeNetwork(NetworkId)));
p->attachSlot(SIGNAL(networkCreated(NetworkId)), this, SLOT(coreNetworkCreated(NetworkId)));
p->attachSlot(SIGNAL(networkRemoved(NetworkId)), this, SLOT(coreNetworkRemoved(NetworkId)));
- p->attachSignal(this, SIGNAL(requestPasswordChange(PeerPtr,QString,QString,QString)), SIGNAL(changePassword(PeerPtr,QString,QString,QString)));
- p->attachSlot(SIGNAL(passwordChanged(PeerPtr,bool)), this, SLOT(corePasswordChanged(PeerPtr,bool)));
+ p->attachSignal(this,
+ SIGNAL(requestPasswordChange(PeerPtr, QString, QString, QString)),
+ SIGNAL(changePassword(PeerPtr, QString, QString, QString)));
+ p->attachSlot(SIGNAL(passwordChanged(PeerPtr, bool)), this, SLOT(corePasswordChanged(PeerPtr, bool)));
p->attachSignal(this, SIGNAL(requestKickClient(int)), SIGNAL(kickClient(int)));
p->attachSlot(SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
coreConnection()->init();
}
-
Client::~Client()
{
disconnectFromCore();
}
-
-AbstractUi *Client::mainUi()
+AbstractUi* Client::mainUi()
{
return instance()->_mainUi.get();
}
-
bool Client::isCoreFeatureEnabled(Quassel::Feature feature)
{
return coreConnection()->peer() ? coreConnection()->peer()->hasFeature(feature) : false;
}
-
bool Client::isConnected()
{
return instance()->_connected;
}
-
bool Client::internalCore()
{
return currentCoreAccount().isInternal();
}
-
void Client::onDbUpgradeInProgress(bool inProgress)
{
emit dbUpgradeInProgress(inProgress);
}
-
-void Client::onExitRequested(int exitCode, const QString &reason)
+void Client::onExitRequested(int exitCode, const QString& reason)
{
if (!reason.isEmpty()) {
qCritical() << reason;
QCoreApplication::exit(exitCode);
}
-
/*** Network handling ***/
QList<NetworkId> Client::networkIds()
return instance()->_networks.keys();
}
-
-const Network *Client::network(NetworkId networkid)
+const Network* Client::network(NetworkId networkid)
{
- if (instance()->_networks.contains(networkid)) return instance()->_networks[networkid];
- else return nullptr;
+ if (instance()->_networks.contains(networkid))
+ return instance()->_networks[networkid];
+ else
+ return nullptr;
}
-
-void Client::createNetwork(const NetworkInfo &info, const QStringList &persistentChannels)
+void Client::createNetwork(const NetworkInfo& info, const QStringList& persistentChannels)
{
emit instance()->requestCreateNetwork(info, persistentChannels);
}
-
void Client::removeNetwork(NetworkId id)
{
emit instance()->requestRemoveNetwork(id);
}
-
-void Client::updateNetwork(const NetworkInfo &info)
+void Client::updateNetwork(const NetworkInfo& info)
{
- Network *netptr = instance()->_networks.value(info.networkId, 0);
+ Network* netptr = instance()->_networks.value(info.networkId, 0);
if (!netptr) {
qWarning() << "Update for unknown network requested:" << info;
return;
netptr->requestSetNetworkInfo(info);
}
-
-void Client::addNetwork(Network *net)
+void Client::addNetwork(Network* net)
{
net->setProxy(signalProxy());
signalProxy()->synchronize(net);
emit instance()->networkCreated(net->networkId());
}
-
void Client::coreNetworkCreated(NetworkId id)
{
if (_networks.contains(id)) {
qWarning() << "Creation of already existing network requested!";
return;
}
- auto *net = new Network(id, this);
+ auto* net = new Network(id, this);
addNetwork(net);
}
-
void Client::coreNetworkRemoved(NetworkId id)
{
if (!_networks.contains(id))
return;
- Network *net = _networks.take(id);
+ Network* net = _networks.take(id);
emit networkRemoved(net->networkId());
net->deleteLater();
}
-
/*** Identity handling ***/
QList<IdentityId> Client::identityIds()
return instance()->_identities.keys();
}
-
-const Identity *Client::identity(IdentityId id)
+const Identity* Client::identity(IdentityId id)
{
- if (instance()->_identities.contains(id)) return instance()->_identities[id];
- else return nullptr;
+ if (instance()->_identities.contains(id))
+ return instance()->_identities[id];
+ else
+ return nullptr;
}
-
-void Client::createIdentity(const CertIdentity &id)
+void Client::createIdentity(const CertIdentity& id)
{
QVariantMap additional;
#ifdef HAVE_SSL
emit instance()->requestCreateIdentity(id, additional);
}
-
-void Client::updateIdentity(IdentityId id, const QVariantMap &ser)
+void Client::updateIdentity(IdentityId id, const QVariantMap& ser)
{
- Identity *idptr = instance()->_identities.value(id, 0);
+ Identity* idptr = instance()->_identities.value(id, 0);
if (!idptr) {
qWarning() << "Update for unknown identity requested:" << id;
return;
idptr->requestUpdate(ser);
}
-
void Client::removeIdentity(IdentityId id)
{
emit instance()->requestRemoveIdentity(id);
}
-
-void Client::coreIdentityCreated(const Identity &other)
+void Client::coreIdentityCreated(const Identity& other)
{
if (!_identities.contains(other.id())) {
- auto *identity = new Identity(other, this);
+ auto* identity = new Identity(other, this);
_identities[other.id()] = identity;
identity->setInitialized();
signalProxy()->synchronize(identity);
}
}
-
void Client::coreIdentityRemoved(IdentityId id)
{
if (_identities.contains(id)) {
emit identityRemoved(id);
- Identity *i = _identities.take(id);
+ Identity* i = _identities.take(id);
i->deleteLater();
}
}
-
/*** User input handling ***/
-void Client::userInput(const BufferInfo &bufferInfo, const QString &message)
+void Client::userInput(const BufferInfo& bufferInfo, const QString& message)
{
// we need to make sure that AliasManager is ready before processing input
if (aliasManager() && aliasManager()->isInitialized())
instance()->_userInputBuffer.append(qMakePair(bufferInfo, message));
}
-
void Client::sendBufferedUserInput()
{
for (int i = 0; i < _userInputBuffer.count(); i++)
_userInputBuffer.clear();
}
-
/*** core connection stuff ***/
void Client::connectionStateChanged(CoreConnection::ConnectionState state)
}
}
-
void Client::setSyncedToCore()
{
// create buffersyncer
connect(bufferSyncer(), &BufferSyncer::highlightCountChanged, _networkModel, &NetworkModel::highlightCountChanged);
connect(networkModel(), &NetworkModel::requestSetLastSeenMsg, bufferSyncer(), &BufferSyncer::requestSetLastSeenMsg);
- SignalProxy *p = signalProxy();
+ SignalProxy* p = signalProxy();
p->synchronize(bufferSyncer());
// create a new BufferViewManager
_highlightRuleManager = new HighlightRuleManager(this);
p->synchronize(highlightRuleManager());
// Listen to network removed events
- connect(this, &Client::networkRemoved,
- _highlightRuleManager, &HighlightRuleManager::networkRemoved);
-
-/* not ready yet
- // create TransferManager and DccConfig if core supports them
- Q_ASSERT(!_dccConfig);
- Q_ASSERT(!_transferManager);
- if (isCoreFeatureEnabled(Quassel::Feature::DccFileTransfer)) {
- _dccConfig = new DccConfig(this);
- p->synchronize(dccConfig());
- _transferManager = new ClientTransferManager(this);
- _transferModel->setManager(_transferManager);
- p->synchronize(transferManager());
- }
-*/
+ connect(this, &Client::networkRemoved, _highlightRuleManager, &HighlightRuleManager::networkRemoved);
+
+ /* not ready yet
+ // create TransferManager and DccConfig if core supports them
+ Q_ASSERT(!_dccConfig);
+ Q_ASSERT(!_transferManager);
+ if (isCoreFeatureEnabled(Quassel::Feature::DccFileTransfer)) {
+ _dccConfig = new DccConfig(this);
+ p->synchronize(dccConfig());
+ _transferManager = new ClientTransferManager(this);
+ _transferModel->setManager(_transferManager);
+ p->synchronize(transferManager());
+ }
+ */
// trigger backlog request once all active bufferviews are initialized
connect(bufferViewOverlay(), &BufferViewOverlay::initDone, this, &Client::finishConnectionInitialization);
}
}
-
void Client::requestInitialBacklog()
{
_backlogManager->requestInitialBacklog();
}
-
void Client::requestLegacyCoreInfo()
{
// On older cores, the CoreInfo object was only synchronized on demand. Synchronize now if
}
}
-
void Client::disconnectFromCore()
{
if (!coreConnection()->isConnected())
coreConnection()->disconnectFromCore();
}
-
void Client::setDisconnectedFromCore()
{
_connected = false;
_messageModel->clear();
_networkModel->clear();
- QHash<NetworkId, Network *>::iterator netIter = _networks.begin();
+ QHash<NetworkId, Network*>::iterator netIter = _networks.begin();
while (netIter != _networks.end()) {
- Network *net = netIter.value();
+ Network* net = netIter.value();
emit networkRemoved(net->networkId());
disconnect(net, &Network::destroyed, this, nullptr);
netIter = _networks.erase(netIter);
}
Q_ASSERT(_networks.isEmpty());
- QHash<IdentityId, Identity *>::iterator idIter = _identities.begin();
+ QHash<IdentityId, Identity*>::iterator idIter = _identities.begin();
while (idIter != _identities.end()) {
emit identityRemoved(idIter.key());
- Identity *id = idIter.value();
+ Identity* id = idIter.value();
idIter = _identities.erase(idIter);
id->deleteLater();
}
}
}
-
/*** ***/
void Client::networkDestroyed()
{
- auto *net = static_cast<Network *>(sender());
- QHash<NetworkId, Network *>::iterator netIter = _networks.begin();
+ auto* net = static_cast<Network*>(sender());
+ QHash<NetworkId, Network*>::iterator netIter = _networks.begin();
while (netIter != _networks.end()) {
if (*netIter == net) {
netIter = _networks.erase(netIter);
}
}
-
// Hmm... we never used this...
void Client::recvStatusMsg(QString /*net*/, QString /*msg*/)
{
- //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
+ // recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
}
-
-void Client::recvMessage(const Message &msg)
+void Client::recvMessage(const Message& msg)
{
Message msg_ = msg;
messageProcessor()->process(msg_);
}
-
-void Client::setBufferLastSeenMsg(BufferId id, const MsgId &msgId)
+void Client::setBufferLastSeenMsg(BufferId id, const MsgId& msgId)
{
if (bufferSyncer())
bufferSyncer()->requestSetLastSeenMsg(id, msgId);
}
-
-void Client::setMarkerLine(BufferId id, const MsgId &msgId)
+void Client::setMarkerLine(BufferId id, const MsgId& msgId)
{
if (bufferSyncer())
bufferSyncer()->requestSetMarkerLine(id, msgId);
}
-
MsgId Client::markerLine(BufferId id)
{
if (id.isValid() && networkModel())
return {};
}
-
void Client::removeBuffer(BufferId id)
{
- if (!bufferSyncer()) return;
+ if (!bufferSyncer())
+ return;
bufferSyncer()->requestRemoveBuffer(id);
}
-
-void Client::renameBuffer(BufferId bufferId, const QString &newName)
+void Client::renameBuffer(BufferId bufferId, const QString& newName)
{
if (!bufferSyncer())
return;
bufferSyncer()->requestRenameBuffer(bufferId, newName);
}
-
void Client::mergeBuffersPermanently(BufferId bufferId1, BufferId bufferId2)
{
if (!bufferSyncer())
bufferSyncer()->requestMergeBuffersPermanently(bufferId1, bufferId2);
}
-
void Client::purgeKnownBufferIds()
{
if (!bufferSyncer())
bufferSyncer()->requestPurgeBufferIds();
}
-
void Client::bufferRemoved(BufferId bufferId)
{
// select a sane buffer (status buffer)
networkModel()->removeBuffer(bufferId);
}
-
-void Client::bufferRenamed(BufferId bufferId, const QString &newName)
+void Client::bufferRenamed(BufferId bufferId, const QString& newName)
{
QModelIndex bufferIndex = networkModel()->bufferIndex(bufferId);
if (bufferIndex.isValid()) {
}
}
-
void Client::buffersPermanentlyMerged(BufferId bufferId1, BufferId bufferId2)
{
QModelIndex idx = networkModel()->bufferIndex(bufferId1);
networkModel()->removeBuffer(bufferId2);
}
-
void Client::markBufferAsRead(BufferId id)
{
if (bufferSyncer() && id.isValid())
bufferSyncer()->requestMarkBufferAsRead(id);
}
-
void Client::refreshLegacyCoreInfo()
{
instance()->requestLegacyCoreInfo();
}
-
-void Client::changePassword(const QString &oldPassword, const QString &newPassword) {
+void Client::changePassword(const QString& oldPassword, const QString& newPassword)
+{
CoreAccount account = currentCoreAccount();
account.setPassword(newPassword);
coreAccountModel()->createOrUpdateAccount(account);
emit instance()->requestPasswordChange(nullptr, account.user(), oldPassword, newPassword);
}
-
void Client::kickClient(int peerId)
{
emit instance()->requestKickClient(peerId);
}
-
void Client::corePasswordChanged(PeerPtr, bool success)
{
if (success)
#include <QPointer>
#include "bufferinfo.h"
-#include "coreinfo.h"
#include "coreaccount.h"
#include "coreconnection.h"
+#include "coreinfo.h"
#include "highlightrulemanager.h"
#include "quassel.h"
#include "singleton.h"
Q_OBJECT
public:
- enum ClientMode {
+ enum ClientMode
+ {
LocalCore,
RemoteCore
};
- Client(std::unique_ptr<AbstractUi>, QObject *parent = nullptr);
+ Client(std::unique_ptr<AbstractUi>, QObject* parent = nullptr);
~Client() override;
- static AbstractUi *mainUi();
+ static AbstractUi* mainUi();
static QList<NetworkId> networkIds();
- static const Network *network(NetworkId);
+ static const Network* network(NetworkId);
static QList<IdentityId> identityIds();
- static const Identity *identity(IdentityId);
+ static const Identity* identity(IdentityId);
//! Request creation of an identity with the given data.
/** The request will be sent to the core, and will be propagated back to all the clients
* with a new valid IdentityId.
* \param identity The identity template for the new identity. It does not need to have a valid ID.
*/
- static void createIdentity(const CertIdentity &identity);
+ static void createIdentity(const CertIdentity& identity);
//! Request update of an identity with the given data.
/** The request will be sent to the core, and will be propagated back to all the clients.
* \param id The identity to be updated.
* \param serializedData The identity's content (cf. SyncableObject::toVariantMap())
*/
- static void updateIdentity(IdentityId id, const QVariantMap &serializedData);
+ static void updateIdentity(IdentityId id, const QVariantMap& serializedData);
//! Request removal of the identity with the given ID from the core (and all the clients, of course).
/** \param id The ID of the identity to be removed.
*/
static void removeIdentity(IdentityId id);
- static void createNetwork(const NetworkInfo &info, const QStringList &persistentChannels = QStringList());
- static void updateNetwork(const NetworkInfo &info);
+ static void createNetwork(const NetworkInfo& info, const QStringList& persistentChannels = QStringList());
+ static void updateNetwork(const NetworkInfo& info);
static void removeNetwork(NetworkId id);
- static inline NetworkModel *networkModel() { return instance()->_networkModel; }
- static inline BufferModel *bufferModel() { return instance()->_bufferModel; }
- static inline MessageModel *messageModel() { return instance()->_messageModel; }
- static inline AbstractMessageProcessor *messageProcessor() { return instance()->_messageProcessor; }
- static inline SignalProxy *signalProxy() { return instance()->_signalProxy; }
-
- static inline ClientAliasManager *aliasManager() { return instance()->_aliasManager; }
- static inline ClientBacklogManager *backlogManager() { return instance()->_backlogManager; }
- static inline CoreInfo *coreInfo() { return instance()->_coreInfo; }
- static inline DccConfig *dccConfig() { return instance()->_dccConfig; }
- static inline ClientIrcListHelper *ircListHelper() { return instance()->_ircListHelper; }
- static inline ClientBufferViewManager *bufferViewManager() { return instance()->_bufferViewManager; }
- static inline BufferViewOverlay *bufferViewOverlay() { return instance()->_bufferViewOverlay; }
- static inline ClientUserInputHandler *inputHandler() { return instance()->_inputHandler; }
- static inline NetworkConfig *networkConfig() { return instance()->_networkConfig; }
- static inline ClientIgnoreListManager *ignoreListManager() { return instance()->_ignoreListManager; }
- static inline HighlightRuleManager *highlightRuleManager() { return instance()->_highlightRuleManager; }
- static inline ClientTransferManager *transferManager() { return instance()->_transferManager; }
- static inline TransferModel *transferModel() { return instance()->_transferModel; }
-
- static inline BufferSyncer *bufferSyncer() { return instance()->_bufferSyncer; }
-
- static inline CoreAccountModel *coreAccountModel() { return instance()->_coreAccountModel; }
- static inline CoreConnection *coreConnection() { return instance()->_coreConnection; }
+ static inline NetworkModel* networkModel() { return instance()->_networkModel; }
+ static inline BufferModel* bufferModel() { return instance()->_bufferModel; }
+ static inline MessageModel* messageModel() { return instance()->_messageModel; }
+ static inline AbstractMessageProcessor* messageProcessor() { return instance()->_messageProcessor; }
+ static inline SignalProxy* signalProxy() { return instance()->_signalProxy; }
+
+ static inline ClientAliasManager* aliasManager() { return instance()->_aliasManager; }
+ static inline ClientBacklogManager* backlogManager() { return instance()->_backlogManager; }
+ static inline CoreInfo* coreInfo() { return instance()->_coreInfo; }
+ static inline DccConfig* dccConfig() { return instance()->_dccConfig; }
+ static inline ClientIrcListHelper* ircListHelper() { return instance()->_ircListHelper; }
+ static inline ClientBufferViewManager* bufferViewManager() { return instance()->_bufferViewManager; }
+ static inline BufferViewOverlay* bufferViewOverlay() { return instance()->_bufferViewOverlay; }
+ static inline ClientUserInputHandler* inputHandler() { return instance()->_inputHandler; }
+ static inline NetworkConfig* networkConfig() { return instance()->_networkConfig; }
+ static inline ClientIgnoreListManager* ignoreListManager() { return instance()->_ignoreListManager; }
+ static inline HighlightRuleManager* highlightRuleManager() { return instance()->_highlightRuleManager; }
+ static inline ClientTransferManager* transferManager() { return instance()->_transferManager; }
+ static inline TransferModel* transferModel() { return instance()->_transferModel; }
+
+ static inline BufferSyncer* bufferSyncer() { return instance()->_bufferSyncer; }
+
+ static inline CoreAccountModel* coreAccountModel() { return instance()->_coreAccountModel; }
+ static inline CoreConnection* coreConnection() { return instance()->_coreConnection; }
static inline CoreAccount currentCoreAccount() { return coreConnection()->currentAccount(); }
static bool isCoreFeatureEnabled(Quassel::Feature feature);
static bool isConnected();
static bool internalCore();
- static void userInput(const BufferInfo &bufferInfo, const QString &message);
+ static void userInput(const BufferInfo& bufferInfo, const QString& message);
- static void setBufferLastSeenMsg(BufferId id, const MsgId &msgId); // this is synced to core and other clients
- static void setMarkerLine(BufferId id, const MsgId &msgId); // this is synced to core and other clients
+ static void setBufferLastSeenMsg(BufferId id, const MsgId& msgId); // this is synced to core and other clients
+ static void setMarkerLine(BufferId id, const MsgId& msgId); // this is synced to core and other clients
static MsgId markerLine(BufferId id);
static void removeBuffer(BufferId id);
- static void renameBuffer(BufferId bufferId, const QString &newName);
+ static void renameBuffer(BufferId bufferId, const QString& newName);
static void mergeBuffersPermanently(BufferId bufferId1, BufferId bufferId2);
static void purgeKnownBufferIds();
*/
static void refreshLegacyCoreInfo();
- static void changePassword(const QString &oldPassword, const QString &newPassword);
+ static void changePassword(const QString& oldPassword, const QString& newPassword);
static void kickClient(int peerId);
- void displayIgnoreList(QString ignoreRule) {
- emit showIgnoreList(ignoreRule);
- }
+ void displayIgnoreList(QString ignoreRule) { emit showIgnoreList(ignoreRule); }
/**
* Request to show the channel list dialog for the network, optionally searching by channel name
* @param channelFilters Partial channel name to search for, or empty to show all
* @param listImmediately If true, immediately list channels, otherwise just show dialog
*/
- void displayChannelList(NetworkId networkId, const QString &channelFilters = {},
- bool listImmediately = false)
+ void displayChannelList(NetworkId networkId, const QString& channelFilters = {}, bool listImmediately = false)
{
emit showChannelList(networkId, channelFilters, listImmediately);
}
signals:
void requestNetworkStates();
- void showConfigWizard(const QVariantMap &coredata);
+ void showConfigWizard(const QVariantMap& coredata);
/**
* Request to show the channel list dialog for the network, optionally searching by channel name
* @param channelFilters Partial channel name to search for, or empty to show all
* @param listImmediately If true, immediately list channels, otherwise just show dialog
*/
- void showChannelList(NetworkId networkId, const QString &channelFilters = {},
- bool listImmediately = false);
+ void showChannelList(NetworkId networkId, const QString& channelFilters = {}, bool listImmediately = false);
void showIgnoreList(QString ignoreRule);
void identityRemoved(IdentityId id);
//! Sent to the core when an identity shall be created. Should not be used elsewhere.
- void requestCreateIdentity(const Identity &, const QVariantMap &);
+ void requestCreateIdentity(const Identity&, const QVariantMap&);
//! Sent to the core when an identity shall be removed. Should not be used elsewhere.
void requestRemoveIdentity(IdentityId);
void networkCreated(NetworkId id);
void networkRemoved(NetworkId id);
- void requestCreateNetwork(const NetworkInfo &info, const QStringList &persistentChannels = QStringList());
+ void requestCreateNetwork(const NetworkInfo& info, const QStringList& persistentChannels = QStringList());
void requestRemoveNetwork(NetworkId);
//! Emitted when a buffer has been marked as read
void bufferMarkedAsRead(BufferId id);
//! Requests a password change (user name must match the currently logged in user)
- void requestPasswordChange(PeerPtr peer, const QString &userName, const QString &oldPassword, const QString &newPassword);
+ void requestPasswordChange(PeerPtr peer, const QString& userName, const QString& oldPassword, const QString& newPassword);
void requestKickClient(int peerId);
void passwordChanged(bool success);
void dbUpgradeInProgress(bool inProgress);
//! Emitted before an exit request is handled
- void exitRequested(const QString &reason);
+ void exitRequested(const QString& reason);
public slots:
void disconnectFromCore();
void bufferRemoved(BufferId bufferId);
- void bufferRenamed(BufferId bufferId, const QString &newName);
+ void bufferRenamed(BufferId bufferId, const QString& newName);
void buffersPermanentlyMerged(BufferId bufferId1, BufferId bufferId2);
void markBufferAsRead(BufferId id);
void onDbUpgradeInProgress(bool inProgress);
- void onExitRequested(int exitCode, const QString &reason);
+ void onExitRequested(int exitCode, const QString& reason);
private slots:
void setSyncedToCore();
void setDisconnectedFromCore();
void connectionStateChanged(CoreConnection::ConnectionState);
- void recvMessage(const Message &message);
+ void recvMessage(const Message& message);
void recvStatusMsg(QString network, QString message);
void networkDestroyed();
- void coreIdentityCreated(const Identity &);
+ void coreIdentityCreated(const Identity&);
void coreIdentityRemoved(IdentityId);
void coreNetworkCreated(NetworkId);
void coreNetworkRemoved(NetworkId);
*/
void requestLegacyCoreInfo();
- static void addNetwork(Network *);
+ static void addNetwork(Network*);
- SignalProxy *_signalProxy{nullptr};
+ SignalProxy* _signalProxy{nullptr};
std::unique_ptr<AbstractUi> _mainUi;
- NetworkModel *_networkModel{nullptr};
- BufferModel *_bufferModel{nullptr};
- BufferSyncer *_bufferSyncer{nullptr};
- ClientAliasManager *_aliasManager{nullptr};
- ClientBacklogManager *_backlogManager{nullptr};
- ClientBufferViewManager *_bufferViewManager{nullptr};
- BufferViewOverlay *_bufferViewOverlay{nullptr};
- CoreInfo *_coreInfo{nullptr};
- DccConfig *_dccConfig{nullptr};
- ClientIrcListHelper *_ircListHelper{nullptr};
- ClientUserInputHandler *_inputHandler{nullptr};
- NetworkConfig *_networkConfig{nullptr};
- ClientIgnoreListManager *_ignoreListManager{nullptr};
- HighlightRuleManager *_highlightRuleManager{nullptr};
- ClientTransferManager *_transferManager{nullptr};
- TransferModel *_transferModel{nullptr};
-
- MessageModel *_messageModel{nullptr};
- AbstractMessageProcessor *_messageProcessor{nullptr};
-
- CoreAccountModel *_coreAccountModel{nullptr};
- CoreConnection *_coreConnection{nullptr};
+ NetworkModel* _networkModel{nullptr};
+ BufferModel* _bufferModel{nullptr};
+ BufferSyncer* _bufferSyncer{nullptr};
+ ClientAliasManager* _aliasManager{nullptr};
+ ClientBacklogManager* _backlogManager{nullptr};
+ ClientBufferViewManager* _bufferViewManager{nullptr};
+ BufferViewOverlay* _bufferViewOverlay{nullptr};
+ CoreInfo* _coreInfo{nullptr};
+ DccConfig* _dccConfig{nullptr};
+ ClientIrcListHelper* _ircListHelper{nullptr};
+ ClientUserInputHandler* _inputHandler{nullptr};
+ NetworkConfig* _networkConfig{nullptr};
+ ClientIgnoreListManager* _ignoreListManager{nullptr};
+ HighlightRuleManager* _highlightRuleManager{nullptr};
+ ClientTransferManager* _transferManager{nullptr};
+ TransferModel* _transferModel{nullptr};
+
+ MessageModel* _messageModel{nullptr};
+ AbstractMessageProcessor* _messageProcessor{nullptr};
+
+ CoreAccountModel* _coreAccountModel{nullptr};
+ CoreConnection* _coreConnection{nullptr};
ClientMode clientMode{};
- QHash<NetworkId, Network *> _networks;
- QHash<IdentityId, Identity *> _identities;
+ QHash<NetworkId, Network*> _networks;
+ QHash<IdentityId, Identity*> _identities;
bool _connected{false};
- QList<QPair<BufferInfo, QString> > _userInputBuffer;
+ QList<QPair<BufferInfo, QString>> _userInputBuffer;
friend class CoreConnection;
};
#include "client.h"
-ClientAliasManager::ClientAliasManager(QObject *parent)
+ClientAliasManager::ClientAliasManager(QObject* parent)
: AliasManager(parent)
-{
-}
-
+{}
-const Network *ClientAliasManager::network(NetworkId id) const
+const Network* ClientAliasManager::network(NetworkId id) const
{
return Client::network(id);
}
Q_OBJECT
public:
- explicit ClientAliasManager(QObject *parent = nullptr);
+ explicit ClientAliasManager(QObject* parent = nullptr);
protected:
- const Network *network(NetworkId) const override;
+ const Network* network(NetworkId) const override;
};
#include <QtEndian>
#ifdef HAVE_SSL
- #include <QSslSocket>
+# include <QSslSocket>
#else
- #include <QTcpSocket>
+# include <QTcpSocket>
#endif
#include "client.h"
using namespace Protocol;
-ClientAuthHandler::ClientAuthHandler(CoreAccount account, QObject *parent)
- : AuthHandler(parent),
- _peer(nullptr),
- _account(account),
- _probing(false),
- _legacy(false),
- _connectionFeatures(0)
-{
-
-}
+ClientAuthHandler::ClientAuthHandler(CoreAccount account, QObject* parent)
+ : AuthHandler(parent)
+ , _peer(nullptr)
+ , _account(account)
+ , _probing(false)
+ , _legacy(false)
+ , _connectionFeatures(0)
+{}
-
-Peer *ClientAuthHandler::peer() const
+Peer* ClientAuthHandler::peer() const
{
return _peer;
}
-
void ClientAuthHandler::connectToCore()
{
CoreAccountSettings s;
#ifdef HAVE_SSL
- auto *socket = new QSslSocket(this);
+ auto* socket = new QSslSocket(this);
// make sure the warning is shown if we happen to connect without SSL support later
s.setAccountValue("ShowNoClientSslWarning", true);
#else
s.setAccountValue("ShowNoClientSslWarning", false);
}
}
- QTcpSocket *socket = new QTcpSocket(this);
+ QTcpSocket* socket = new QTcpSocket(this);
#endif
#ifndef QT_NO_NETWORKPROXY
QNetworkProxy proxy;
proxy.setType(_account.proxyType());
- if (_account.proxyType() == QNetworkProxy::Socks5Proxy ||
- _account.proxyType() == QNetworkProxy::HttpProxy) {
+ if (_account.proxyType() == QNetworkProxy::Socks5Proxy || _account.proxyType() == QNetworkProxy::HttpProxy) {
proxy.setHostName(_account.proxyHostName());
proxy.setPort(_account.proxyPort());
proxy.setUser(_account.proxyUser());
if (_account.proxyType() == QNetworkProxy::DefaultProxy) {
QNetworkProxyFactory::setUseSystemConfiguration(true);
- } else {
+ }
+ else {
QNetworkProxyFactory::setUseSystemConfiguration(false);
socket->setProxy(proxy);
}
socket->connectToHost(_account.hostName(), _account.port());
}
-
void ClientAuthHandler::onSocketStateChanged(QAbstractSocket::SocketState socketState)
{
QString text;
- switch(socketState) {
- case QAbstractSocket::HostLookupState:
- if (!_legacy)
- text = tr("Looking up %1...").arg(_account.hostName());
- break;
- case QAbstractSocket::ConnectingState:
- if (!_legacy)
- text = tr("Connecting to %1...").arg(_account.hostName());
- break;
- case QAbstractSocket::ConnectedState:
- text = tr("Connected to %1").arg(_account.hostName());
- break;
- case QAbstractSocket::ClosingState:
- if (!_probing)
- text = tr("Disconnecting from %1...").arg(_account.hostName());
- break;
- case QAbstractSocket::UnconnectedState:
- if (!_probing) {
- text = tr("Disconnected");
- // Ensure the disconnected() signal is sent even if we haven't reached the Connected state yet.
- // The baseclass implementation will make sure to only send the signal once.
- // However, we do want to prefer a potential socket error signal that may be on route already, so
- // give this a chance to overtake us by spinning the loop...
- QTimer::singleShot(0, this, &ClientAuthHandler::onSocketDisconnected);
- }
- break;
- default:
- break;
+ switch (socketState) {
+ case QAbstractSocket::HostLookupState:
+ if (!_legacy)
+ text = tr("Looking up %1...").arg(_account.hostName());
+ break;
+ case QAbstractSocket::ConnectingState:
+ if (!_legacy)
+ text = tr("Connecting to %1...").arg(_account.hostName());
+ break;
+ case QAbstractSocket::ConnectedState:
+ text = tr("Connected to %1").arg(_account.hostName());
+ break;
+ case QAbstractSocket::ClosingState:
+ if (!_probing)
+ text = tr("Disconnecting from %1...").arg(_account.hostName());
+ break;
+ case QAbstractSocket::UnconnectedState:
+ if (!_probing) {
+ text = tr("Disconnected");
+ // Ensure the disconnected() signal is sent even if we haven't reached the Connected state yet.
+ // The baseclass implementation will make sure to only send the signal once.
+ // However, we do want to prefer a potential socket error signal that may be on route already, so
+ // give this a chance to overtake us by spinning the loop...
+ QTimer::singleShot(0, this, &ClientAuthHandler::onSocketDisconnected);
+ }
+ break;
+ default:
+ break;
}
if (!text.isEmpty()) {
return;
}
- _probing = false; // all other errors are unrelated to probing and should be handled
+ _probing = false; // all other errors are unrelated to probing and should be handled
AuthHandler::onSocketError(error);
}
-
void ClientAuthHandler::onSocketDisconnected()
{
if (_probing && _legacy) {
AuthHandler::onSocketDisconnected();
}
-
void ClientAuthHandler::onSocketConnected()
{
if (_peer) {
// First connection attempt, try probing for a capable core
_probing = true;
- QDataStream stream(socket()); // stream handles the endianness for us
+ QDataStream stream(socket()); // stream handles the endianness for us
stream.setVersion(QDataStream::Qt_4_2);
quint32 magic = Protocol::magic;
PeerFactory::ProtoList protos = PeerFactory::supportedProtocols();
for (int i = 0; i < protos.count(); ++i) {
quint32 reply = protos[i].first;
- reply |= protos[i].second<<8;
+ reply |= protos[i].second << 8;
if (i == protos.count() - 1)
- reply |= 0x80000000; // end list
+ reply |= 0x80000000; // end list
stream << reply;
}
- socket()->flush(); // make sure the probing data is sent immediately
+ socket()->flush(); // make sure the probing data is sent immediately
return;
}
qDebug() << "Legacy core detected, switching to compatibility mode";
- auto *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(Protocol::LegacyProtocol, 0), this, socket(), Compressor::NoCompression, this);
+ auto* peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(Protocol::LegacyProtocol, 0),
+ this,
+ socket(),
+ Compressor::NoCompression,
+ this);
// Only needed for the legacy peer, as all others check the protocol version before instantiation
connect(peer, &RemotePeer::protocolVersionMismatch, this, &ClientAuthHandler::onProtocolVersionMismatch);
setPeer(peer);
}
-
void ClientAuthHandler::onReadyRead()
{
if (socket()->bytesAvailable() < 4)
return;
if (!_probing)
- return; // make sure to not read more data than needed
+ return; // make sure to not read more data than needed
_probing = false;
disconnect(socket(), &QIODevice::readyRead, this, &ClientAuthHandler::onReadyRead);
quint32 reply;
- socket()->read((char *)&reply, 4);
+ socket()->read((char*)&reply, 4);
reply = qFromBigEndian<quint32>(reply);
auto type = static_cast<Protocol::Type>(reply & 0xff);
- auto protoFeatures = static_cast<quint16>(reply>>8 & 0xffff);
- _connectionFeatures = static_cast<quint8>(reply>>24);
+ auto protoFeatures = static_cast<quint16>(reply >> 8 & 0xffff);
+ _connectionFeatures = static_cast<quint8>(reply >> 24);
Compressor::CompressionLevel level;
if (_connectionFeatures & Protocol::Compression)
else
level = Compressor::NoCompression;
- RemotePeer *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(type, protoFeatures), this, socket(), level, this);
+ RemotePeer* peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(type, protoFeatures), this, socket(), level, this);
if (!peer) {
qWarning() << "No valid protocol supported for this core!";
emit errorPopup(tr("<b>Incompatible Quassel Core!</b><br>"
setPeer(peer);
}
-
void ClientAuthHandler::onProtocolVersionMismatch(int actual, int expected)
{
emit errorPopup(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
- "We need at least protocol v%1, but the core speaks v%2 only.").arg(expected, actual));
+ "We need at least protocol v%1, but the core speaks v%2 only.")
+ .arg(expected, actual));
requestDisconnect(tr("Incompatible protocol version, connection to core refused"));
}
-
-void ClientAuthHandler::setPeer(RemotePeer *peer)
+void ClientAuthHandler::setPeer(RemotePeer* peer)
{
qDebug().nospace() << "Using " << qPrintable(peer->protocolName()) << "...";
checkAndEnableSsl(_connectionFeatures & Protocol::Encryption);
}
-
void ClientAuthHandler::startRegistration()
{
emit statusMessage(tr("Synchronizing to core..."));
_peer->dispatch(RegisterClient(Quassel::Features{}, Quassel::buildInfo().fancyVersionString, Quassel::buildInfo().commitDate, useSsl));
}
-
-void ClientAuthHandler::handle(const ClientDenied &msg)
+void ClientAuthHandler::handle(const ClientDenied& msg)
{
emit errorPopup(msg.errorString);
requestDisconnect(tr("The core refused connection from this client"));
}
-
-void ClientAuthHandler::handle(const ClientRegistered &msg)
+void ClientAuthHandler::handle(const ClientRegistered& msg)
{
_coreConfigured = msg.coreConfigured;
_backendInfo = msg.backendInfo;
_peer->setFeatures(std::move(msg.features));
// The legacy protocol enables SSL at this point
- if(_legacy && _account.useSsl())
+ if (_legacy && _account.useSsl())
checkAndEnableSsl(msg.sslSupported);
else
onConnectionReady();
}
-
void ClientAuthHandler::onConnectionReady()
{
- const auto &coreFeatures = _peer->features();
+ const auto& coreFeatures = _peer->features();
auto unsupported = coreFeatures.toStringList(false);
if (!unsupported.isEmpty()) {
quInfo() << qPrintable(tr("Core does not support the following features: %1").arg(unsupported.join(", ")));
// start wizard
emit startCoreSetup(_backendInfo, _authenticatorInfo);
}
- else // TODO: check if we need LoginEnabled
+ else // TODO: check if we need LoginEnabled
login();
}
-
-void ClientAuthHandler::setupCore(const SetupData &setupData)
+void ClientAuthHandler::setupCore(const SetupData& setupData)
{
_peer->dispatch(setupData);
}
-
-void ClientAuthHandler::handle(const SetupFailed &msg)
+void ClientAuthHandler::handle(const SetupFailed& msg)
{
emit coreSetupFailed(msg.errorString);
}
-
-void ClientAuthHandler::handle(const SetupDone &msg)
+void ClientAuthHandler::handle(const SetupDone& msg)
{
Q_UNUSED(msg)
emit coreSetupSuccessful();
}
-
-void ClientAuthHandler::login(const QString &user, const QString &password, bool remember)
+void ClientAuthHandler::login(const QString& user, const QString& password, bool remember)
{
_account.setUser(user);
_account.setPassword(password);
login();
}
-
-void ClientAuthHandler::login(const QString &previousError)
+void ClientAuthHandler::login(const QString& previousError)
{
emit statusMessage(tr("Logging in..."));
if (_account.user().isEmpty() || _account.password().isEmpty() || !previousError.isEmpty()) {
bool valid = false;
- emit userAuthenticationRequired(&_account, &valid, previousError); // *must* be a synchronous call
+ emit userAuthenticationRequired(&_account, &valid, previousError); // *must* be a synchronous call
if (!valid || _account.user().isEmpty() || _account.password().isEmpty()) {
requestDisconnect(tr("Login canceled"));
return;
_peer->dispatch(Login(_account.user(), _account.password()));
}
-
-void ClientAuthHandler::handle(const LoginFailed &msg)
+void ClientAuthHandler::handle(const LoginFailed& msg)
{
login(msg.errorString);
}
-
-void ClientAuthHandler::handle(const LoginSuccess &msg)
+void ClientAuthHandler::handle(const LoginSuccess& msg)
{
Q_UNUSED(msg)
emit loginSuccessful(_account);
}
-
-void ClientAuthHandler::handle(const SessionState &msg)
+void ClientAuthHandler::handle(const SessionState& msg)
{
- disconnect(socket(), nullptr, this, nullptr); // this is the last message we shall ever get
+ disconnect(socket(), nullptr, this, nullptr); // this is the last message we shall ever get
// give up ownership of the peer; CoreSession takes responsibility now
_peer->setParent(nullptr);
emit handshakeComplete(_peer, msg);
}
-
/*** SSL Stuff ***/
void ClientAuthHandler::checkAndEnableSsl(bool coreSupportsSsl)
// Make sure the warning is shown next time we don't have SSL in the core
s.setAccountValue("ShowNoCoreSslWarning", true);
- auto *sslSocket = qobject_cast<QSslSocket *>(socket());
+ auto* sslSocket = qobject_cast<QSslSocket*>(socket());
Q_ASSERT(sslSocket);
connect(sslSocket, &QSslSocket::encrypted, this, &ClientAuthHandler::onSslSocketEncrypted);
connect(sslSocket, selectOverload<const QList<QSslError>&>(&QSslSocket::sslErrors), this, &ClientAuthHandler::onSslErrors);
void ClientAuthHandler::onSslSocketEncrypted()
{
- auto *socket = qobject_cast<QSslSocket *>(sender());
+ auto* socket = qobject_cast<QSslSocket*>(sender());
Q_ASSERT(socket);
if (!socket->sslErrors().count()) {
startRegistration();
}
-
void ClientAuthHandler::onSslErrors()
{
- auto *socket = qobject_cast<QSslSocket *>(sender());
+ auto* socket = qobject_cast<QSslSocket*>(sender());
Q_ASSERT(socket);
CoreAccountSettings s;
QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
- ClientAuthHandler::DigestVersion knownDigestVersion = static_cast<ClientAuthHandler::DigestVersion>(s.accountValue("SslCertDigestVersion").toInt());
+ ClientAuthHandler::DigestVersion knownDigestVersion = static_cast<ClientAuthHandler::DigestVersion>(
+ s.accountValue("SslCertDigestVersion").toInt());
QByteArray calculatedDigest;
switch (knownDigestVersion) {
#pragma once
-#include "compressor.h"
#include "authhandler.h"
+#include "compressor.h"
#include "coreaccount.h"
class QSslSocket;
Q_OBJECT
public:
- enum DigestVersion {
+ enum DigestVersion
+ {
Md5,
Sha2_512,
- Latest=Sha2_512
+ Latest = Sha2_512
};
- ClientAuthHandler(CoreAccount account, QObject *parent = nullptr);
+ ClientAuthHandler(CoreAccount account, QObject* parent = nullptr);
- Peer *peer() const;
+ Peer* peer() const;
public slots:
void connectToCore();
- void login(const QString &previousError = QString());
- void login(const QString &user, const QString &password, bool remember);
- void setupCore(const Protocol::SetupData &setupData);
+ void login(const QString& previousError = QString());
+ void login(const QString& user, const QString& password, bool remember);
+ void setupCore(const Protocol::SetupData& setupData);
signals:
- void statusMessage(const QString &message);
- void errorMessage(const QString &message);
- void errorPopup(const QString &message);
+ void statusMessage(const QString& message);
+ void errorMessage(const QString& message);
+ void errorPopup(const QString& message);
void transferProgress(int current, int max);
- void requestDisconnect(const QString &errorString = QString(), bool wantReconnect = false);
+ void requestDisconnect(const QString& errorString = QString(), bool wantReconnect = false);
void connectionReady();
- void loginSuccessful(const CoreAccount &account);
- void handshakeComplete(RemotePeer *peer, const Protocol::SessionState &sessionState);
+ void loginSuccessful(const CoreAccount& account);
+ void handshakeComplete(RemotePeer* peer, const Protocol::SessionState& sessionState);
// These signals MUST be handled synchronously!
- void userAuthenticationRequired(CoreAccount *account, bool *valid, const QString &errorMessage = QString());
- void handleNoSslInClient(bool *accepted);
- void handleNoSslInCore(bool *accepted);
+ void userAuthenticationRequired(CoreAccount* account, bool* valid, const QString& errorMessage = QString());
+ void handleNoSslInClient(bool* accepted);
+ void handleNoSslInCore(bool* accepted);
#ifdef HAVE_SSL
- void handleSslErrors(const QSslSocket *socket, bool *accepted, bool *permanently);
+ void handleSslErrors(const QSslSocket* socket, bool* accepted, bool* permanently);
#endif
void encrypted(bool isEncrypted = true);
- void startCoreSetup(const QVariantList &backendInfo, const QVariantList &authenticatorInfo);
+ void startCoreSetup(const QVariantList& backendInfo, const QVariantList& authenticatorInfo);
void coreSetupSuccessful();
- void coreSetupFailed(const QString &error);
+ void coreSetupFailed(const QString& error);
private:
using AuthHandler::handle;
- void handle(const Protocol::ClientDenied &msg) override;
- void handle(const Protocol::ClientRegistered &msg) override;
- void handle(const Protocol::SetupFailed &msg) override;
- void handle(const Protocol::SetupDone &msg) override;
- void handle(const Protocol::LoginFailed &msg) override;
- void handle(const Protocol::LoginSuccess &msg) override;
- void handle(const Protocol::SessionState &msg) override;
+ void handle(const Protocol::ClientDenied& msg) override;
+ void handle(const Protocol::ClientRegistered& msg) override;
+ void handle(const Protocol::SetupFailed& msg) override;
+ void handle(const Protocol::SetupDone& msg) override;
+ void handle(const Protocol::LoginFailed& msg) override;
+ void handle(const Protocol::LoginSuccess& msg) override;
+ void handle(const Protocol::SessionState& msg) override;
- void setPeer(RemotePeer *peer);
+ void setPeer(RemotePeer* peer);
void checkAndEnableSsl(bool coreSupportsSsl);
void startRegistration();
void onConnectionReady();
private:
- RemotePeer *_peer;
+ RemotePeer* _peer;
bool _coreConfigured;
QVariantList _backendInfo;
QVariantList _authenticatorInfo;
#include "clientbacklogmanager.h"
-#include "abstractmessageprocessor.h"
-#include "backlogsettings.h"
-#include "backlogrequester.h"
-#include "client.h"
-
#include <ctime>
#include <QDebug>
-ClientBacklogManager::ClientBacklogManager(QObject *parent)
- : BacklogManager(parent)
-{
-}
+#include "abstractmessageprocessor.h"
+#include "backlogrequester.h"
+#include "backlogsettings.h"
+#include "client.h"
+ClientBacklogManager::ClientBacklogManager(QObject* parent)
+ : BacklogManager(parent)
+{}
QVariantList ClientBacklogManager::requestBacklog(BufferId bufferId, MsgId first, MsgId last, int limit, int additional)
{
return BacklogManager::requestBacklog(bufferId, first, last, limit, additional);
}
-
void ClientBacklogManager::receiveBacklog(BufferId bufferId, MsgId first, MsgId last, int limit, int additional, QVariantList msgs)
{
- Q_UNUSED(first) Q_UNUSED(last) Q_UNUSED(limit) Q_UNUSED(additional)
+ Q_UNUSED(first)
+ Q_UNUSED(last)
+ Q_UNUSED(limit)
+ Q_UNUSED(additional)
emit messagesReceived(bufferId, msgs.count());
MessageList msglist;
- foreach(QVariant v, msgs) {
+ foreach (QVariant v, msgs) {
Message msg = v.value<Message>();
msg.setFlags(msg.flags() | Message::Backlog);
msglist << msg;
}
}
-
void ClientBacklogManager::receiveBacklogAll(MsgId first, MsgId last, int limit, int additional, QVariantList msgs)
{
- Q_UNUSED(first) Q_UNUSED(last) Q_UNUSED(limit) Q_UNUSED(additional)
+ Q_UNUSED(first)
+ Q_UNUSED(last)
+ Q_UNUSED(limit)
+ Q_UNUSED(additional)
MessageList msglist;
- foreach(QVariant v, msgs) {
+ foreach (QVariant v, msgs) {
Message msg = v.value<Message>();
msg.setFlags(msg.flags() | Message::Backlog);
msglist << msg;
dispatchMessages(msglist);
}
-
void ClientBacklogManager::requestInitialBacklog()
{
if (_initBacklogRequested) {
}
}
-
-BufferIdList ClientBacklogManager::filterNewBufferIds(const BufferIdList &bufferIds)
+BufferIdList ClientBacklogManager::filterNewBufferIds(const BufferIdList& bufferIds)
{
BufferIdList newBuffers;
QSet<BufferId> availableBuffers = Client::networkModel()->allBufferIds().toSet();
- foreach(BufferId bufferId, bufferIds) {
+ foreach (BufferId bufferId, bufferIds) {
if (_buffersRequested.contains(bufferId) || !availableBuffers.contains(bufferId))
continue;
newBuffers << bufferId;
return newBuffers;
}
-
-void ClientBacklogManager::checkForBacklog(const QList<BufferId> &bufferIds)
+void ClientBacklogManager::checkForBacklog(const QList<BufferId>& bufferIds)
{
// we ingore all backlogrequests until we had our initial request
if (!_initBacklogRequested) {
break;
case BacklogRequester::PerBufferUnread:
case BacklogRequester::PerBufferFixed:
- default:
- {
+ default: {
BufferIdList buffers = filterNewBufferIds(bufferIds);
if (!buffers.isEmpty())
_requester->requestBacklog(buffers);
};
}
-
bool ClientBacklogManager::isBuffering()
{
return _requester && _requester->isBuffering();
}
-
-void ClientBacklogManager::dispatchMessages(const MessageList &messages, bool sort)
+void ClientBacklogManager::dispatchMessages(const MessageList& messages, bool sort)
{
if (messages.isEmpty())
return;
emit messagesProcessed(tr("Processed %1 messages in %2 seconds.").arg(messages.count()).arg((float)(end_t - start_t) / CLOCKS_PER_SEC));
}
-
void ClientBacklogManager::reset()
{
delete _requester;
Q_OBJECT
public:
- ClientBacklogManager(QObject *parent = nullptr);
+ ClientBacklogManager(QObject* parent = nullptr);
// helper for the backlogRequester, as it isn't a QObject and can't emit itself
- inline void emitMessagesRequested(const QString &msg) const { emit messagesRequested(msg); }
+ inline void emitMessagesRequested(const QString& msg) const { emit messagesRequested(msg); }
void reset();
void requestInitialBacklog();
void checkForBacklog(BufferId bufferId);
- void checkForBacklog(const BufferIdList &bufferIds);
+ void checkForBacklog(const BufferIdList& bufferIds);
signals:
void messagesReceived(BufferId bufferId, int count) const;
- void messagesRequested(const QString &) const;
- void messagesProcessed(const QString &) const;
+ void messagesRequested(const QString&) const;
+ void messagesProcessed(const QString&) const;
void updateProgress(int, int);
private:
bool isBuffering();
- BufferIdList filterNewBufferIds(const BufferIdList &bufferIds);
+ BufferIdList filterNewBufferIds(const BufferIdList& bufferIds);
- void dispatchMessages(const MessageList &messages, bool sort = false);
+ void dispatchMessages(const MessageList& messages, bool sort = false);
- BacklogRequester *_requester{nullptr};
+ BacklogRequester* _requester{nullptr};
bool _initBacklogRequested{false};
QSet<BufferId> _buffersRequested;
};
-
// inlines
inline void ClientBacklogManager::checkForBacklog(BufferId bufferId)
{
#include "clientbufferviewconfig.h"
-ClientBufferViewConfig::ClientBufferViewConfig(int bufferViewId, QObject *parent)
- : BufferViewConfig(bufferViewId, parent),
- _locked(false)
+ClientBufferViewConfig::ClientBufferViewConfig(int bufferViewId, QObject* parent)
+ : BufferViewConfig(bufferViewId, parent)
+ , _locked(false)
{
connect(this, &SyncableObject::initDone, this, &ClientBufferViewConfig::ensureDecoration);
}
-
// currently we don't have a possibility to configure disableDecoration
// if we have an old config this value can be true which is... bad.
// so we upgrade the core stored bufferViewConfig.
Q_OBJECT
public:
- ClientBufferViewConfig(int bufferViewId, QObject *parent = nullptr);
+ ClientBufferViewConfig(int bufferViewId, QObject* parent = nullptr);
inline bool isLocked() { return _locked || sortAlphabetically(); }
inline void setLocked(bool locked) { _locked = locked; }
inline void unlock() { setLocked(false); };
private slots:
- void ensureDecoration(); // remove this in next release
+ void ensureDecoration(); // remove this in next release
private:
bool _locked;
#include "clientbufferviewmanager.h"
-#include "clientbufferviewconfig.h"
#include "client.h"
+#include "clientbufferviewconfig.h"
#include "networkmodel.h"
-ClientBufferViewManager::ClientBufferViewManager(SignalProxy *proxy, QObject *parent)
+ClientBufferViewManager::ClientBufferViewManager(SignalProxy* proxy, QObject* parent)
: BufferViewManager(proxy, parent)
-{
-}
+{}
-
-BufferViewConfig *ClientBufferViewManager::bufferViewConfigFactory(int bufferViewConfigId)
+BufferViewConfig* ClientBufferViewManager::bufferViewConfigFactory(int bufferViewConfigId)
{
return new ClientBufferViewConfig(bufferViewConfigId, this);
}
-
-QList<ClientBufferViewConfig *> ClientBufferViewManager::clientBufferViewConfigs() const
+QList<ClientBufferViewConfig*> ClientBufferViewManager::clientBufferViewConfigs() const
{
- QList<ClientBufferViewConfig *> clientConfigs;
- foreach(BufferViewConfig *config, bufferViewConfigs()) {
- clientConfigs << static_cast<ClientBufferViewConfig *>(config);
+ QList<ClientBufferViewConfig*> clientConfigs;
+ foreach (BufferViewConfig* config, bufferViewConfigs()) {
+ clientConfigs << static_cast<ClientBufferViewConfig*>(config);
}
return clientConfigs;
}
-
-ClientBufferViewConfig *ClientBufferViewManager::clientBufferViewConfig(int bufferViewId) const
+ClientBufferViewConfig* ClientBufferViewManager::clientBufferViewConfig(int bufferViewId) const
{
- return static_cast<ClientBufferViewConfig *>(bufferViewConfig(bufferViewId));
+ return static_cast<ClientBufferViewConfig*>(bufferViewConfig(bufferViewId));
}
-
void ClientBufferViewManager::setInitialized()
{
if (bufferViewConfigs().isEmpty()) {
Q_OBJECT
public:
- ClientBufferViewManager(SignalProxy *proxy, QObject *parent = nullptr);
+ ClientBufferViewManager(SignalProxy* proxy, QObject* parent = nullptr);
- QList<ClientBufferViewConfig *> clientBufferViewConfigs() const;
- ClientBufferViewConfig *clientBufferViewConfig(int bufferViewId) const;
+ QList<ClientBufferViewConfig*> clientBufferViewConfigs() const;
+ ClientBufferViewConfig* clientBufferViewConfig(int bufferViewId) const;
public slots:
void setInitialized() override;
protected:
- BufferViewConfig *bufferViewConfigFactory(int bufferViewConfigId) override;
+ BufferViewConfig* bufferViewConfigFactory(int bufferViewConfigId) override;
};
#include "client.h"
#include "signalproxy.h"
-CertIdentity::CertIdentity(IdentityId id, QObject *parent)
+CertIdentity::CertIdentity(IdentityId id, QObject* parent)
: Identity(id, parent)
-{
-}
+{}
-
-CertIdentity::CertIdentity(const Identity &other, QObject *parent)
+CertIdentity::CertIdentity(const Identity& other, QObject* parent)
: Identity(other, parent)
-{
-}
-
+{}
-CertIdentity::CertIdentity(const CertIdentity &other, QObject *parent)
+CertIdentity::CertIdentity(const CertIdentity& other, QObject* parent)
: Identity(other, parent)
#ifdef HAVE_SSL
, _isDirty(other._isDirty)
, _sslKey(other._sslKey)
, _sslCert(other._sslCert)
#endif
-{
-}
-
+{}
#ifdef HAVE_SSL
void CertIdentity::enableEditSsl(bool enable)
return;
_certManager = new ClientCertManager(id(), this);
- if (isValid()) { // this means we are not a newly created Identity but have a proper Id
+ if (isValid()) { // this means we are not a newly created Identity but have a proper Id
Client::signalProxy()->synchronize(_certManager);
connect(_certManager, &SyncableObject::updated, this, &CertIdentity::markClean);
connect(_certManager, &SyncableObject::initDone, this, &CertIdentity::markClean);
}
}
-
-void CertIdentity::setSslKey(const QSslKey &key)
+void CertIdentity::setSslKey(const QSslKey& key)
{
if (key.toPem() == _sslKey.toPem())
return;
_isDirty = true;
}
-
-void CertIdentity::setSslCert(const QSslCertificate &cert)
+void CertIdentity::setSslCert(const QSslCertificate& cert)
{
if (cert.toPem() == _sslCert.toPem())
return;
_isDirty = true;
}
-
void CertIdentity::requestUpdateSslSettings()
{
if (!_certManager)
_certManager->requestUpdate(_certManager->toVariantMap());
}
-
void CertIdentity::markClean()
{
_isDirty = false;
emit sslSettingsUpdated();
}
-
// ========================================
// ClientCertManager
// ========================================
-void ClientCertManager::setSslKey(const QByteArray &encoded)
+void ClientCertManager::setSslKey(const QByteArray& encoded)
{
QSslKey key(encoded, QSsl::Rsa);
if (key.isNull() && Client::isCoreFeatureEnabled(Quassel::Feature::EcdsaCertfpKeys))
_certIdentity->setSslKey(key);
}
-
-void ClientCertManager::setSslCert(const QByteArray &encoded)
+void ClientCertManager::setSslCert(const QByteArray& encoded)
{
_certIdentity->setSslCert(QSslCertificate(encoded));
}
-#endif // HAVE_SSL
+#endif // HAVE_SSL
Q_OBJECT
public:
- CertIdentity(IdentityId id = 0, QObject *parent = nullptr);
- CertIdentity(const Identity &other, QObject *parent = nullptr);
- CertIdentity(const CertIdentity &other, QObject *parent = nullptr);
+ CertIdentity(IdentityId id = 0, QObject* parent = nullptr);
+ CertIdentity(const Identity& other, QObject* parent = nullptr);
+ CertIdentity(const CertIdentity& other, QObject* parent = nullptr);
#ifdef HAVE_SSL
inline bool isDirty() const { return _isDirty; }
#ifdef HAVE_SSL
void enableEditSsl(bool enable = true);
- inline const QSslKey &sslKey() const { return _sslKey; }
- inline const QSslCertificate &sslCert() const { return _sslCert; }
+ inline const QSslKey& sslKey() const { return _sslKey; }
+ inline const QSslCertificate& sslCert() const { return _sslCert; }
- void setSslKey(const QSslKey &key);
- void setSslCert(const QSslCertificate &cert);
+ void setSslKey(const QSslKey& key);
+ void setSslCert(const QSslCertificate& cert);
public slots:
void requestUpdateSslSettings();
void markClean();
private:
- ClientCertManager *_certManager{nullptr};
+ ClientCertManager* _certManager{nullptr};
bool _isDirty{false};
QSslKey _sslKey;
QSslCertificate _sslCert;
-#endif //HAVE_SSL
+#endif // HAVE_SSL
};
-
// ========================================
// ClientCertManager
// ========================================
Q_OBJECT
public:
- ClientCertManager(IdentityId id, CertIdentity *parent) : CertManager(id, parent), _certIdentity(parent) {}
+ ClientCertManager(IdentityId id, CertIdentity* parent)
+ : CertManager(id, parent)
+ , _certIdentity(parent)
+ {}
- inline const QSslKey &sslKey() const override { return _certIdentity->sslKey(); }
- inline const QSslCertificate &sslCert() const override { return _certIdentity->sslCert(); }
+ inline const QSslKey& sslKey() const override { return _certIdentity->sslKey(); }
+ inline const QSslCertificate& sslCert() const override { return _certIdentity->sslCert(); }
public slots:
- void setSslKey(const QByteArray &encoded) override;
- void setSslCert(const QByteArray &encoded) override;
+ void setSslKey(const QByteArray& encoded) override;
+ void setSslCert(const QByteArray& encoded) override;
private:
- CertIdentity *_certIdentity;
+ CertIdentity* _certIdentity;
};
-#endif //HAVE_SSL
+#endif // HAVE_SSL
#include "clientignorelistmanager.h"
-ClientIgnoreListManager::ClientIgnoreListManager(QObject *parent)
+ClientIgnoreListManager::ClientIgnoreListManager(QObject* parent)
: IgnoreListManager(parent)
{
connect(this, &SyncableObject::updatedRemotely, this, &ClientIgnoreListManager::ignoreListChanged);
}
-
-bool ClientIgnoreListManager::pureMatch(const IgnoreListItem &item, const QString &string) const
+bool ClientIgnoreListManager::pureMatch(const IgnoreListItem& item, const QString& string) const
{
return (item.contentsMatcher().match(string));
}
-
-QMap<QString, bool> ClientIgnoreListManager::matchingRulesForHostmask(const QString &hostmask, const QString &network, const QString &channel) const
+QMap<QString, bool> ClientIgnoreListManager::matchingRulesForHostmask(const QString& hostmask,
+ const QString& network,
+ const QString& channel) const
{
QMap<QString, bool> result;
- foreach(IgnoreListItem item, ignoreList()) {
+ foreach (IgnoreListItem item, ignoreList()) {
if (item.type() == SenderIgnore && pureMatch(item, hostmask)
- && ((network.isEmpty() && channel.isEmpty())
- || item.scope() == GlobalScope
+ && ((network.isEmpty() && channel.isEmpty()) || item.scope() == GlobalScope
|| (item.scope() == NetworkScope && item.scopeRuleMatcher().match(network))
|| (item.scope() == ChannelScope && item.scopeRuleMatcher().match(channel)))) {
result[item.contents()] = item.isEnabled();
#include "client-export.h"
-#include "ignorelistmanager.h"
#include <QMap>
+#include "ignorelistmanager.h"
+
class CLIENT_EXPORT ClientIgnoreListManager : public IgnoreListManager
{
Q_OBJECT
public:
- explicit ClientIgnoreListManager(QObject *parent = nullptr);
+ explicit ClientIgnoreListManager(QObject* parent = nullptr);
//! Fetch all matching ignore rules for a given hostmask
/** \param hostmask The hostmask of the user
- * \param network The network name
- * \param channel The channel name
- * \return Returns a QMap with the rule as key and a bool, representing if the rule is enabled or not, as value
- */
- QMap<QString, bool> matchingRulesForHostmask(const QString &hostmask, const QString &network, const QString &channel) const;
+ * \param network The network name
+ * \param channel The channel name
+ * \return Returns a QMap with the rule as key and a bool, representing if the rule is enabled or not, as value
+ */
+ QMap<QString, bool> matchingRulesForHostmask(const QString& hostmask, const QString& network, const QString& channel) const;
signals:
void ignoreListChanged();
private:
// matches an ignore rule against a given string
- bool pureMatch(const IgnoreListItem &item, const QString &string) const;
+ bool pureMatch(const IgnoreListItem& item, const QString& string) const;
};
#include "client.h"
#include "irclistmodel.h"
-QVariantList ClientIrcListHelper::requestChannelList(const NetworkId &netId, const QStringList &channelFilters)
+QVariantList ClientIrcListHelper::requestChannelList(const NetworkId& netId, const QStringList& channelFilters)
{
_netId = netId;
return IrcListHelper::requestChannelList(netId, channelFilters);
}
-
-void ClientIrcListHelper::receiveChannelList(const NetworkId &netId, const QStringList &channelFilters, const QVariantList &channels)
+void ClientIrcListHelper::receiveChannelList(const NetworkId& netId, const QStringList& channelFilters, const QVariantList& channels)
{
QVariantList::const_iterator iter = channels.constBegin();
QVariantList::const_iterator iterEnd = channels.constEnd();
emit channelListReceived(netId, channelFilters, channelList);
}
-
-void ClientIrcListHelper::reportFinishedList(const NetworkId &netId)
+void ClientIrcListHelper::reportFinishedList(const NetworkId& netId)
{
if (_netId == netId) {
requestChannelList(netId, QStringList());
Q_OBJECT
public:
- inline ClientIrcListHelper(QObject *object = nullptr) : IrcListHelper(object) {};
+ inline ClientIrcListHelper(QObject* object = nullptr)
+ : IrcListHelper(object){};
public slots:
- QVariantList requestChannelList(const NetworkId &netId, const QStringList &channelFilters) override;
- void receiveChannelList(const NetworkId &netId, const QStringList &channelFilters, const QVariantList &channels) override;
- void reportFinishedList(const NetworkId &netId) override;
- inline void reportError(const QString &error) override { emit errorReported(error); }
+ QVariantList requestChannelList(const NetworkId& netId, const QStringList& channelFilters) override;
+ void receiveChannelList(const NetworkId& netId, const QStringList& channelFilters, const QVariantList& channels) override;
+ void reportFinishedList(const NetworkId& netId) override;
+ inline void reportError(const QString& error) override { emit errorReported(error); }
signals:
- void channelListReceived(const NetworkId &netId, const QStringList &channelFilters, const QList<IrcListHelper::ChannelDescription> &channelList);
- void finishedListReported(const NetworkId &netId);
- void errorReported(const QString &error);
+ void channelListReceived(const NetworkId& netId,
+ const QStringList& channelFilters,
+ const QList<IrcListHelper::ChannelDescription>& channelList);
+ void finishedListReported(const NetworkId& netId);
+ void errorReported(const QString& error);
private:
NetworkId _netId;
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
-#include <utility>
-
-#include <QStringList>
-
#include "clientsettings.h"
+#include <utility>
+
#include <QHostAddress>
+#include <QStringList>
#ifdef HAVE_SSL
-#include <QSslSocket>
+# include <QSslSocket>
#endif
#include "client.h"
#include "quassel.h"
-ClientSettings::ClientSettings(QString g) : Settings(g, Quassel::buildInfo().clientApplicationName)
-{
-}
-
+ClientSettings::ClientSettings(QString g)
+ : Settings(g, Quassel::buildInfo().clientApplicationName)
+{}
/***********************************************************************************************/
CoreAccountSettings::CoreAccountSettings(QString subgroup)
- : ClientSettings("CoreAccounts"),
- _subgroup(std::move(subgroup))
-{
-}
-
+ : ClientSettings("CoreAccounts")
+ , _subgroup(std::move(subgroup))
+{}
-QString CoreAccountSettings::keyForNotify(const QString &key) const
+QString CoreAccountSettings::keyForNotify(const QString& key) const
{
return QString{"%1/%2/%3"}.arg(Client::currentCoreAccount().accountId().toInt()).arg(_subgroup).arg(key);
}
-
QList<AccountId> CoreAccountSettings::knownAccounts() const
{
QList<AccountId> ids;
- foreach(const QString &key, localChildGroups()) {
+ foreach (const QString& key, localChildGroups()) {
AccountId acc = key.toInt();
if (acc.isValid())
ids << acc;
return ids;
}
-
AccountId CoreAccountSettings::lastAccount() const
{
return localValue("LastAccount", 0).toInt();
}
-
void CoreAccountSettings::setLastAccount(AccountId account)
{
setLocalValue("LastAccount", account.toInt());
}
-
AccountId CoreAccountSettings::autoConnectAccount() const
{
return localValue("AutoConnectAccount", 0).toInt();
}
-
void CoreAccountSettings::setAutoConnectAccount(AccountId account)
{
setLocalValue("AutoConnectAccount", account.toInt());
}
-
bool CoreAccountSettings::autoConnectOnStartup() const
{
return localValue("AutoConnectOnStartup", false).toBool();
}
-
void CoreAccountSettings::setAutoConnectOnStartup(bool b)
{
setLocalValue("AutoConnectOnStartup", b);
}
-
bool CoreAccountSettings::autoConnectToFixedAccount() const
{
return localValue("AutoConnectToFixedAccount", false).toBool();
}
-
void CoreAccountSettings::setAutoConnectToFixedAccount(bool b)
{
setLocalValue("AutoConnectToFixedAccount", b);
}
-
-void CoreAccountSettings::storeAccountData(AccountId id, const QVariantMap &data)
+void CoreAccountSettings::storeAccountData(AccountId id, const QVariantMap& data)
{
QString base = QString::number(id.toInt());
- foreach(const QString &key, data.keys()) {
+ foreach (const QString& key, data.keys()) {
setLocalValue(base + "/" + key, data.value(key));
}
removeLocalKey(QString("%1/Connection").arg(base));
}
-
QVariantMap CoreAccountSettings::retrieveAccountData(AccountId id) const
{
QVariantMap map;
QString base = QString::number(id.toInt());
- foreach(const QString &key, localChildKeys(base)) {
+ foreach (const QString& key, localChildKeys(base)) {
map[key] = localValue(base + "/" + key);
}
return map;
}
-
-void CoreAccountSettings::setAccountValue(const QString &key, const QVariant &value)
+void CoreAccountSettings::setAccountValue(const QString& key, const QVariant& value)
{
if (!Client::currentCoreAccount().isValid())
return;
setLocalValue(QString("%1/%2/%3").arg(Client::currentCoreAccount().accountId().toInt()).arg(_subgroup).arg(key), value);
}
-
-QVariant CoreAccountSettings::accountValue(const QString &key, const QVariant &def) const
+QVariant CoreAccountSettings::accountValue(const QString& key, const QVariant& def) const
{
if (!Client::currentCoreAccount().isValid())
return QVariant();
return localValue(QString("%1/%2/%3").arg(Client::currentCoreAccount().accountId().toInt()).arg(_subgroup).arg(key), def);
}
-
-void CoreAccountSettings::setJumpKeyMap(const QHash<int, BufferId> &keyMap)
+void CoreAccountSettings::setJumpKeyMap(const QHash<int, BufferId>& keyMap)
{
QVariantMap variants;
QHash<int, BufferId>::const_iterator mapIter = keyMap.constBegin();
setAccountValue("JumpKeyMap", variants);
}
-
QHash<int, BufferId> CoreAccountSettings::jumpKeyMap() const
{
QHash<int, BufferId> keyMap;
return keyMap;
}
-
-void CoreAccountSettings::setBufferViewOverlay(const QSet<int> &viewIds)
+void CoreAccountSettings::setBufferViewOverlay(const QSet<int>& viewIds)
{
QVariantList variants;
- foreach(int viewId, viewIds) {
+ foreach (int viewId, viewIds) {
variants << qVariantFromValue(viewId);
}
setAccountValue("BufferViewOverlay", variants);
}
-
QSet<int> CoreAccountSettings::bufferViewOverlay() const
{
QSet<int> viewIds;
return viewIds;
}
-
void CoreAccountSettings::removeAccount(AccountId id)
{
removeLocalKey(QString("%1").arg(id.toInt()));
}
-
void CoreAccountSettings::clearAccounts()
{
- foreach(const QString &key, localChildGroups())
- removeLocalKey(key);
+ foreach (const QString& key, localChildGroups())
+ removeLocalKey(key);
}
-
/***********************************************************************************************/
// CoreConnectionSettings:
setLocalValue("NetworkDetectionMode", mode);
}
-
CoreConnectionSettings::NetworkDetectionMode CoreConnectionSettings::networkDetectionMode() const
{
auto mode = localValue("NetworkDetectionMode", UseQNetworkConfigurationManager).toInt();
if (mode == 0)
- mode = UseQNetworkConfigurationManager; // UseSolid is gone, map that to the new default
+ mode = UseQNetworkConfigurationManager; // UseSolid is gone, map that to the new default
return static_cast<NetworkDetectionMode>(mode);
}
-
void CoreConnectionSettings::setAutoReconnect(bool autoReconnect)
{
setLocalValue("AutoReconnect", autoReconnect);
}
-
bool CoreConnectionSettings::autoReconnect() const
{
return localValue("AutoReconnect", true).toBool();
}
-
void CoreConnectionSettings::setPingTimeoutInterval(int interval)
{
setLocalValue("PingTimeoutInterval", interval);
}
-
int CoreConnectionSettings::pingTimeoutInterval() const
{
return localValue("PingTimeoutInterval", 60).toInt();
}
-
void CoreConnectionSettings::setReconnectInterval(int interval)
{
setLocalValue("ReconnectInterval", interval);
}
-
int CoreConnectionSettings::reconnectInterval() const
{
return localValue("ReconnectInterval", 60).toInt();
}
-
/***********************************************************************************************/
// NotificationSettings:
NotificationSettings::NotificationSettings()
: ClientSettings("Notification")
-{
-}
-
+{}
-void NotificationSettings::setValue(const QString &key, const QVariant &data)
+void NotificationSettings::setValue(const QString& key, const QVariant& data)
{
setLocalValue(key, data);
}
-
-QVariant NotificationSettings::value(const QString &key, const QVariant &def) const
+QVariant NotificationSettings::value(const QString& key, const QVariant& def) const
{
return localValue(key, def);
}
-
-void NotificationSettings::remove(const QString &key)
+void NotificationSettings::remove(const QString& key)
{
removeLocalKey(key);
}
-
-void NotificationSettings::setHighlightList(const QVariantList &highlightList)
+void NotificationSettings::setHighlightList(const QVariantList& highlightList)
{
setLocalValue("Highlights/CustomList", highlightList);
}
-
QVariantList NotificationSettings::highlightList() const
{
return localValue("Highlights/CustomList").toList();
}
-
void NotificationSettings::setHighlightNick(NotificationSettings::HighlightNickType highlightNickType)
{
setLocalValue("Highlights/HighlightNick", highlightNickType);
}
-
NotificationSettings::HighlightNickType NotificationSettings::highlightNick() const
{
- return (NotificationSettings::HighlightNickType)localValue("Highlights/HighlightNick",
- CurrentNick).toInt();
+ return (NotificationSettings::HighlightNickType)localValue("Highlights/HighlightNick", CurrentNick).toInt();
}
-
void NotificationSettings::setNicksCaseSensitive(bool cs)
{
setLocalValue("Highlights/NicksCaseSensitive", cs);
}
-
bool NotificationSettings::nicksCaseSensitive() const
{
return localValue("Highlights/NicksCaseSensitive", false).toBool();
}
-
// ========================================
// TabCompletionSettings
// ========================================
TabCompletionSettings::TabCompletionSettings()
: ClientSettings("TabCompletion")
-{
-}
-
+{}
-void TabCompletionSettings::setCompletionSuffix(const QString &suffix)
+void TabCompletionSettings::setCompletionSuffix(const QString& suffix)
{
setLocalValue("CompletionSuffix", suffix);
}
-
QString TabCompletionSettings::completionSuffix() const
{
return localValue("CompletionSuffix", ": ").toString();
}
-
void TabCompletionSettings::setAddSpaceMidSentence(bool space)
{
setLocalValue("AddSpaceMidSentence", space);
}
-
bool TabCompletionSettings::addSpaceMidSentence() const
{
return localValue("AddSpaceMidSentence", false).toBool();
}
-
void TabCompletionSettings::setSortMode(SortMode mode)
{
setLocalValue("SortMode", mode);
}
-
TabCompletionSettings::SortMode TabCompletionSettings::sortMode() const
{
return static_cast<SortMode>(localValue("SortMode"), LastActivity);
}
-
void TabCompletionSettings::setCaseSensitivity(Qt::CaseSensitivity cs)
{
setLocalValue("CaseSensitivity", cs);
}
-
Qt::CaseSensitivity TabCompletionSettings::caseSensitivity() const
{
return (Qt::CaseSensitivity)localValue("CaseSensitivity", Qt::CaseInsensitive).toInt();
}
-
void TabCompletionSettings::setUseLastSpokenTo(bool use)
{
setLocalValue("UseLastSpokenTo", use);
}
-
bool TabCompletionSettings::useLastSpokenTo() const
{
return localValue("UseLastSpokenTo", false).toBool();
}
-
// ========================================
// ItemViewSettings
// ========================================
-ItemViewSettings::ItemViewSettings(const QString &group) : ClientSettings(group)
-{
-}
-
+ItemViewSettings::ItemViewSettings(const QString& group)
+ : ClientSettings(group)
+{}
bool ItemViewSettings::displayTopicInTooltip() const
{
return localValue("DisplayTopicInTooltip", false).toBool();
}
-
bool ItemViewSettings::mouseWheelChangesBuffer() const
{
return localValue("MouseWheelChangesBuffer", false).toBool();
#include "client-export.h"
#include "settings.h"
-
#include "types.h"
class QHostAddress;
class CLIENT_EXPORT ClientSettings : public Settings
{
-
protected:
ClientSettings(QString group = "General");
};
-
// ========================================
// CoreAccountSettings
// ========================================
void clearAccounts();
- void storeAccountData(AccountId id, const QVariantMap &data);
+ void storeAccountData(AccountId id, const QVariantMap& data);
QVariantMap retrieveAccountData(AccountId) const;
void removeAccount(AccountId);
- void setJumpKeyMap(const QHash<int, BufferId> &keyMap);
+ void setJumpKeyMap(const QHash<int, BufferId>& keyMap);
QHash<int, BufferId> jumpKeyMap() const;
- void setBufferViewOverlay(const QSet<int> &viewIds);
+ void setBufferViewOverlay(const QSet<int>& viewIds);
QSet<int> bufferViewOverlay() const;
- void setAccountValue(const QString &key, const QVariant &data);
- QVariant accountValue(const QString &key, const QVariant &def = QVariant()) const;
+ void setAccountValue(const QString& key, const QVariant& data);
+ QVariant accountValue(const QString& key, const QVariant& def = QVariant()) const;
protected:
- QString keyForNotify(const QString &key) const override;
+ QString keyForNotify(const QString& key) const override;
private:
QString _subgroup;
};
-
// ========================================
// NotificationSettings
// ========================================
class CLIENT_EXPORT NotificationSettings : public ClientSettings
{
public:
- enum HighlightNickType {
+ enum HighlightNickType
+ {
NoNick = 0x00,
CurrentNick = 0x01,
AllNicks = 0x02
NotificationSettings();
- void setValue(const QString &key, const QVariant &data);
- QVariant value(const QString &key, const QVariant &def = {}) const;
- void remove(const QString &key);
+ void setValue(const QString& key, const QVariant& data);
+ QVariant value(const QString& key, const QVariant& def = {}) const;
+ void remove(const QString& key);
- void setHighlightList(const QVariantList &highlightList);
+ void setHighlightList(const QVariantList& highlightList);
QVariantList highlightList() const;
void setHighlightNick(HighlightNickType);
bool nicksCaseSensitive() const;
};
-
// ========================================
// CoreConnectionSettings
// ========================================
class CLIENT_EXPORT CoreConnectionSettings : public ClientSettings
{
public:
- enum NetworkDetectionMode {
- UseQNetworkConfigurationManager = 1, // UseSolid is gone
+ enum NetworkDetectionMode
+ {
+ UseQNetworkConfigurationManager = 1, // UseSolid is gone
UsePingTimeout,
NoActiveDetection
};
int reconnectInterval() const;
};
-
// ========================================
// TabCompletionSettings
// ========================================
class CLIENT_EXPORT TabCompletionSettings : public ClientSettings
{
public:
- enum SortMode {
+ enum SortMode
+ {
Alphabetical,
LastActivity
};
TabCompletionSettings();
- void setCompletionSuffix(const QString &);
+ void setCompletionSuffix(const QString&);
QString completionSuffix() const;
void setAddSpaceMidSentence(bool);
bool useLastSpokenTo() const;
};
-
// ========================================
// ItemViewSettings
// ========================================
class CLIENT_EXPORT ItemViewSettings : public ClientSettings
{
public:
- ItemViewSettings(const QString &group = "ItemViews");
+ ItemViewSettings(const QString& group = "ItemViews");
bool displayTopicInTooltip() const;
bool mouseWheelChangesBuffer() const;
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
-#include <QFile>
-
#include "clienttransfer.h"
-ClientTransfer::ClientTransfer(const QUuid &uuid, QObject *parent)
- : Transfer(uuid, parent),
- _file(nullptr)
+#include <QFile>
+
+ClientTransfer::ClientTransfer(const QUuid& uuid, QObject* parent)
+ : Transfer(uuid, parent)
+ , _file(nullptr)
{
connect(this, &Transfer::statusChanged, this, &ClientTransfer::onStatusChanged);
}
-
quint64 ClientTransfer::transferred() const
{
if (status() == Status::Completed)
return _file ? _file->size() : 0;
}
-
void ClientTransfer::cleanUp()
{
if (_file) {
}
}
-
QString ClientTransfer::savePath() const
{
return _savePath;
}
-
-void ClientTransfer::accept(const QString &savePath) const
+void ClientTransfer::accept(const QString& savePath) const
{
_savePath = savePath;
PeerPtr ptr = nullptr;
emit accepted();
}
-
void ClientTransfer::reject() const
{
PeerPtr ptr = nullptr;
emit rejected();
}
-
-void ClientTransfer::dataReceived(PeerPtr, const QByteArray &data)
+void ClientTransfer::dataReceived(PeerPtr, const QByteArray& data)
{
// TODO: proper error handling (relay to core)
if (!_file) {
_file = new QFile(_savePath, this);
- if (!_file->open(QFile::WriteOnly|QFile::Truncate)) {
+ if (!_file->open(QFile::WriteOnly | QFile::Truncate)) {
qWarning() << Q_FUNC_INFO << "Could not open file:" << _file->errorString();
return;
}
emit transferredChanged(transferred());
}
-
void ClientTransfer::onStatusChanged(Transfer::Status status)
{
- switch(status) {
- case Status::Completed:
- if (_file)
- _file->close();
- break;
- case Status::Failed:
- if (_file)
- _file->remove();
- break;
- default:
- ;
+ switch (status) {
+ case Status::Completed:
+ if (_file)
+ _file->close();
+ break;
+ case Status::Failed:
+ if (_file)
+ _file->remove();
+ break;
+ default:
+ ;
}
}
Q_OBJECT
public:
- ClientTransfer(const QUuid &uuid, QObject *parent = nullptr);
+ ClientTransfer(const QUuid& uuid, QObject* parent = nullptr);
QString savePath() const;
public slots:
// called on the client side
- void accept(const QString &savePath) const override;
+ void accept(const QString& savePath) const override;
void reject() const override;
private slots:
- void dataReceived(PeerPtr peer, const QByteArray &data) override;
+ void dataReceived(PeerPtr peer, const QByteArray& data) override;
void onStatusChanged(Transfer::Status status);
private:
mutable QString _savePath;
- QFile *_file;
+ QFile* _file;
};
#include "client.h"
#include "clienttransfer.h"
-void ClientTransferManager::setTransferIds(const QList<QUuid> &transferIds)
+void ClientTransferManager::setTransferIds(const QList<QUuid>& transferIds)
{
- for(auto &&id : transferIds) {
+ for (auto&& id : transferIds) {
onCoreTransferAdded(id);
}
}
-
-void ClientTransferManager::onCoreTransferAdded(const QUuid &uuid)
+void ClientTransferManager::onCoreTransferAdded(const QUuid& uuid)
{
if (uuid.isNull()) {
qWarning() << Q_FUNC_INFO << "Invalid transfer uuid" << uuid.toString();
}
auto transfer = new ClientTransfer(uuid, this);
- connect(transfer, &SyncableObject::initDone, this, &ClientTransferManager::onTransferInitDone); // we only want to add initialized transfers
+ connect(transfer, &SyncableObject::initDone, this, &ClientTransferManager::onTransferInitDone); // we only want to add initialized transfers
Client::signalProxy()->synchronize(transfer);
}
-
void ClientTransferManager::onTransferInitDone()
{
- auto *transfer = qobject_cast<Transfer *>(sender());
+ auto* transfer = qobject_cast<Transfer*>(sender());
Q_ASSERT(transfer);
addTransfer(transfer);
}
using TransferManager::TransferManager;
private slots:
- void setTransferIds(const QList<QUuid> &transferIds) override;
- void onCoreTransferAdded(const QUuid &uuid) override;
+ void setTransferIds(const QList<QUuid>& transferIds) override;
+ void onCoreTransferAdded(const QUuid& uuid) override;
void onTransferInitDone();
};
#include "clientuserinputhandler.h"
+#include <QDateTime>
+
#include "bufferinfo.h"
#include "buffermodel.h"
#include "client.h"
#include "network.h"
#include "types.h"
-#include <QDateTime>
-
-ClientUserInputHandler::ClientUserInputHandler(QObject *parent)
+ClientUserInputHandler::ClientUserInputHandler(QObject* parent)
: BasicHandler(parent)
{
TabCompletionSettings s;
completionSuffixChanged(s.completionSuffix());
}
-
-void ClientUserInputHandler::completionSuffixChanged(const QVariant &v)
+void ClientUserInputHandler::completionSuffixChanged(const QVariant& v)
{
QString suffix = v.toString();
QString letter = "A-Za-z";
_nickRx = QRegExp(QString("^([%1%2][%1%2\\d-]*)%3").arg(letter, special, suffix).trimmed());
}
-
// this would be the place for a client-side hook
-void ClientUserInputHandler::handleUserInput(const BufferInfo &bufferInfo, const QString &msg)
+void ClientUserInputHandler::handleUserInput(const BufferInfo& bufferInfo, const QString& msg)
{
if (msg.isEmpty())
return;
if (!msg.startsWith('/')) {
if (_nickRx.indexIn(msg) == 0) {
- const Network *net = Client::network(bufferInfo.networkId());
- IrcUser *user = net ? net->ircUser(_nickRx.cap(1)) : nullptr;
+ const Network* net = Client::network(bufferInfo.networkId());
+ IrcUser* user = net ? net->ircUser(_nickRx.cap(1)) : nullptr;
if (user)
user->setLastSpokenTo(bufferInfo.bufferId(), QDateTime::currentDateTime().toUTC());
}
}
}
-
-void ClientUserInputHandler::defaultHandler(const QString &cmd, const BufferInfo &bufferInfo, const QString &text)
+void ClientUserInputHandler::defaultHandler(const QString& cmd, const BufferInfo& bufferInfo, const QString& text)
{
QString command = QString("/%1 %2").arg(cmd, text);
emit sendInput(bufferInfo, command);
}
-
-void ClientUserInputHandler::handleExec(const BufferInfo &bufferInfo, const QString &execString)
+void ClientUserInputHandler::handleExec(const BufferInfo& bufferInfo, const QString& execString)
{
- auto *exec = new ExecWrapper(this); // gets suicidal when it's done
+ auto* exec = new ExecWrapper(this); // gets suicidal when it's done
exec->start(bufferInfo, execString);
}
-
-void ClientUserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QString &text)
+void ClientUserInputHandler::handleJoin(const BufferInfo& bufferInfo, const QString& text)
{
if (text.isEmpty()) {
Client::messageModel()->insertErrorMessage(bufferInfo, tr("/JOIN expects a channel"));
defaultHandler("JOIN", bufferInfo, text);
}
-
-void ClientUserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &text)
+void ClientUserInputHandler::handleQuery(const BufferInfo& bufferInfo, const QString& text)
{
if (text.isEmpty()) {
Client::messageModel()->insertErrorMessage(bufferInfo, tr("/QUERY expects at least a nick"));
defaultHandler("QUERY", bufferInfo, text);
}
-
-void ClientUserInputHandler::handleIgnore(const BufferInfo &bufferInfo, const QString &text)
+void ClientUserInputHandler::handleIgnore(const BufferInfo& bufferInfo, const QString& text)
{
if (text.isEmpty()) {
emit Client::instance()->displayIgnoreList("");
// If rule contains no ! or @, we assume it is just a nickname, and turn it into an ignore rule for that nick
QString rule = (text.contains('!') || text.contains('@')) ? text : text + "!*@*";
- Client::ignoreListManager()->requestAddIgnoreListItem(
- IgnoreListManager::IgnoreType::SenderIgnore,
- rule,
- false,
- // Use a dynamic ignore rule, for reversibility
- IgnoreListManager::StrictnessType::SoftStrictness,
- // Use current network as scope
- IgnoreListManager::ScopeType::NetworkScope,
- Client::network(bufferInfo.networkId())->networkName(),
- true
- );
+ Client::ignoreListManager()->requestAddIgnoreListItem(IgnoreListManager::IgnoreType::SenderIgnore,
+ rule,
+ false,
+ // Use a dynamic ignore rule, for reversibility
+ IgnoreListManager::StrictnessType::SoftStrictness,
+ // Use current network as scope
+ IgnoreListManager::ScopeType::NetworkScope,
+ Client::network(bufferInfo.networkId())->networkName(),
+ true);
}
-void ClientUserInputHandler::handleList(const BufferInfo &bufferInfo, const QString &text)
+void ClientUserInputHandler::handleList(const BufferInfo& bufferInfo, const QString& text)
{
// Pass along any potential search parameters, list channels immediately
Client::instance()->displayChannelList(bufferInfo.networkId(), text, true);
}
-
-void ClientUserInputHandler::switchBuffer(const NetworkId &networkId, const QString &bufferName)
+void ClientUserInputHandler::switchBuffer(const NetworkId& networkId, const QString& bufferName)
{
BufferId newBufId = Client::networkModel()->bufferId(networkId, bufferName);
if (!newBufId.isValid()) {
else {
Client::bufferModel()->switchToBuffer(newBufId);
// unhide the buffer
- ClientBufferViewManager *clientBufferViewManager = Client::bufferViewManager();
- QList<ClientBufferViewConfig *> bufferViewConfigList = clientBufferViewManager->clientBufferViewConfigs();
- foreach(ClientBufferViewConfig *bufferViewConfig, bufferViewConfigList) {
+ ClientBufferViewManager* clientBufferViewManager = Client::bufferViewManager();
+ QList<ClientBufferViewConfig*> bufferViewConfigList = clientBufferViewManager->clientBufferViewConfigs();
+ foreach (ClientBufferViewConfig* bufferViewConfig, bufferViewConfigList) {
if (bufferViewConfig->temporarilyRemovedBuffers().contains(newBufId)) {
bufferViewConfig->requestAddBuffer(newBufId, bufferViewConfig->bufferList().length());
- //if (bufferViewConfig->sortAlphabetically()) {
+ // if (bufferViewConfig->sortAlphabetically()) {
// TODO we need to trigger a sort here, but can't reach the model required
// to get a bufferviewfilter, as the bufferviewmanager only managers configs
- //BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
+ // BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
//}
}
}
Q_OBJECT
public:
- ClientUserInputHandler(QObject *parent = nullptr);
+ ClientUserInputHandler(QObject* parent = nullptr);
public slots:
- void handleUserInput(const BufferInfo &bufferInfo, const QString &msg);
+ void handleUserInput(const BufferInfo& bufferInfo, const QString& msg);
signals:
- void sendInput(const BufferInfo &, const QString &);
+ void sendInput(const BufferInfo&, const QString&);
private slots:
- void completionSuffixChanged(const QVariant &);
+ void completionSuffixChanged(const QVariant&);
- void handleExec(const BufferInfo &bufferInfo, const QString &execString);
- void handleJoin(const BufferInfo &bufferInfo, const QString &text);
- void handleQuery(const BufferInfo &bufferInfo, const QString &text);
- void handleIgnore(const BufferInfo &bufferInfo, const QString &text);
- void handleList(const BufferInfo &bufferInfo, const QString &text);
- void defaultHandler(const QString &cmd, const BufferInfo &bufferInfo, const QString &text);
+ void handleExec(const BufferInfo& bufferInfo, const QString& execString);
+ void handleJoin(const BufferInfo& bufferInfo, const QString& text);
+ void handleQuery(const BufferInfo& bufferInfo, const QString& text);
+ void handleIgnore(const BufferInfo& bufferInfo, const QString& text);
+ void handleList(const BufferInfo& bufferInfo, const QString& text);
+ void defaultHandler(const QString& cmd, const BufferInfo& bufferInfo, const QString& text);
private:
QRegExp _nickRx;
//! Helper method for switching to new/existing buffers
/** Immediately switches to the given buffer or schedules a switch for whenever
- * the buffer is created
- */
- void switchBuffer(const NetworkId &networkId, const QString &bufferName);
+ * the buffer is created
+ */
+ void switchBuffer(const NetworkId& networkId, const QString& bufferName);
};
-
#endif
_proxyPort = 8080;
}
-
void CoreAccount::setAccountId(AccountId id)
{
_accountId = id;
}
-
-void CoreAccount::setAccountName(const QString &name)
+void CoreAccount::setAccountName(const QString& name)
{
_accountName = name;
}
-
-void CoreAccount::setUuid(const QUuid &uuid)
+void CoreAccount::setUuid(const QUuid& uuid)
{
_uuid = uuid;
}
-
void CoreAccount::setInternal(bool internal)
{
_internal = internal;
}
-
-void CoreAccount::setUser(const QString &user)
+void CoreAccount::setUser(const QString& user)
{
_user = user;
}
-
-void CoreAccount::setPassword(const QString &password)
+void CoreAccount::setPassword(const QString& password)
{
_password = password;
}
-
void CoreAccount::setStorePassword(bool store)
{
_storePassword = store;
}
-
-void CoreAccount::setHostName(const QString &hostname)
+void CoreAccount::setHostName(const QString& hostname)
{
_hostName = hostname;
}
-
void CoreAccount::setPort(uint port)
{
_port = port;
}
-
void CoreAccount::setUseSsl(bool useSsl)
{
_useSsl = useSsl;
}
-
void CoreAccount::setProxyType(QNetworkProxy::ProxyType type)
{
_proxyType = type;
}
-
-void CoreAccount::setProxyUser(const QString &proxyUser)
+void CoreAccount::setProxyUser(const QString& proxyUser)
{
_proxyUser = proxyUser;
}
-
-void CoreAccount::setProxyPassword(const QString &proxyPassword)
+void CoreAccount::setProxyPassword(const QString& proxyPassword)
{
_proxyPassword = proxyPassword;
}
-
-void CoreAccount::setProxyHostName(const QString &proxyHostName)
+void CoreAccount::setProxyHostName(const QString& proxyHostName)
{
_proxyHostName = proxyHostName;
}
-
void CoreAccount::setProxyPort(uint proxyPort)
{
_proxyPort = proxyPort;
}
-
QVariantMap CoreAccount::toVariantMap(bool forcePassword) const
{
QVariantMap v;
- v["AccountId"] = accountId().toInt(); // can't use AccountId because then comparison fails
+ v["AccountId"] = accountId().toInt(); // can't use AccountId because then comparison fails
v["AccountName"] = accountName();
v["Uuid"] = uuid().toString();
v["Internal"] = isInternal();
return v;
}
-
-void CoreAccount::fromVariantMap(const QVariantMap &v)
+void CoreAccount::fromVariantMap(const QVariantMap& v)
{
setAccountId((AccountId)v.value("AccountId").toInt());
setAccountName(v.value("AccountName").toString());
_storePassword = !password().isEmpty();
}
-
-bool CoreAccount::operator==(const CoreAccount &other) const
+bool CoreAccount::operator==(const CoreAccount& other) const
{
return toVariantMap(true) == other.toVariantMap(true);
}
-
-bool CoreAccount::operator!=(const CoreAccount &other) const
+bool CoreAccount::operator!=(const CoreAccount& other) const
{
return !(*this == other);
}
-
-QDebug operator<<(QDebug dbg, const CoreAccount &acc)
+QDebug operator<<(QDebug dbg, const CoreAccount& acc)
{
dbg.nospace() << qPrintable(QString("CoreAccount(AccountId:")) << acc.accountId()
- << qPrintable(QString(", AccountName:")) << acc.accountName()
- << qPrintable(QString(", Uuid:")) << acc.uuid()
- << qPrintable(QString(", Internal:")) << acc.isInternal()
- << qPrintable(QString(", User:")) << acc.user()
- << qPrintable(QString(", Password:")) << acc.password()
- << qPrintable(QString(", StorePassword:")) << acc.storePassword()
- << qPrintable(QString(", HostName:")) << acc.hostName()
- << qPrintable(QString(", Port:")) << acc.port()
- << qPrintable(QString(", UseSSL:")) << acc.useSsl()
- << qPrintable(QString(", ProxyType:")) << acc.proxyType()
- << qPrintable(QString(", ProxyUser:")) << acc.proxyUser()
- << qPrintable(QString(", ProxyPassword:")) << acc.proxyPassword()
- << qPrintable(QString(", ProxyHostName:")) << acc.proxyHostName()
- << qPrintable(QString(", ProxyPort:")) << acc.proxyPort();
+ << qPrintable(QString(", AccountName:")) << acc.accountName()
+ << qPrintable(QString(", Uuid:")) << acc.uuid()
+ << qPrintable(QString(", Internal:")) << acc.isInternal()
+ << qPrintable(QString(", User:")) << acc.user()
+ << qPrintable(QString(", Password:")) << acc.password()
+ << qPrintable(QString(", StorePassword:")) << acc.storePassword()
+ << qPrintable(QString(", HostName:")) << acc.hostName()
+ << qPrintable(QString(", Port:")) << acc.port()
+ << qPrintable(QString(", UseSSL:")) << acc.useSsl()
+ << qPrintable(QString(", ProxyType:")) << acc.proxyType()
+ << qPrintable(QString(", ProxyUser:")) << acc.proxyUser()
+ << qPrintable(QString(", ProxyPassword:")) << acc.proxyPassword()
+ << qPrintable(QString(", ProxyHostName:")) << acc.proxyHostName()
+ << qPrintable(QString(", ProxyPort:")) << acc.proxyPort();
return dbg.space();
}
inline uint proxyPort() const { return _proxyPort; }
void setAccountId(AccountId id);
- void setAccountName(const QString &accountName);
- void setUuid(const QUuid &uuid);
+ void setAccountName(const QString& accountName);
+ void setUuid(const QUuid& uuid);
void setInternal(bool);
- void setUser(const QString &user);
+ void setUser(const QString& user);
void setStorePassword(bool);
- void setHostName(const QString &hostname);
+ void setHostName(const QString& hostname);
void setPort(uint port);
void setUseSsl(bool);
void setProxyType(QNetworkProxy::ProxyType);
- void setProxyUser(const QString &);
- void setProxyHostName(const QString &);
+ void setProxyUser(const QString&);
+ void setProxyHostName(const QString&);
void setProxyPort(uint);
/* These might be overridden for KWallet/QtKeychain support */
virtual inline QString password() const { return _password; }
- virtual void setPassword(const QString &password);
+ virtual void setPassword(const QString& password);
virtual inline QString proxyPassword() const { return _proxyPassword; }
- virtual void setProxyPassword(const QString &);
+ virtual void setProxyPassword(const QString&);
virtual QVariantMap toVariantMap(bool forcePassword = false) const;
- virtual void fromVariantMap(const QVariantMap &);
+ virtual void fromVariantMap(const QVariantMap&);
- bool operator==(const CoreAccount &other) const;
- bool operator!=(const CoreAccount &other) const;
+ bool operator==(const CoreAccount& other) const;
+ bool operator!=(const CoreAccount& other) const;
private:
AccountId _accountId;
uint _proxyPort;
};
-QDebug operator<<(QDebug dbg, const CoreAccount &msg);
+QDebug operator<<(QDebug dbg, const CoreAccount& msg);
#include "clientsettings.h"
#include "quassel.h"
-CoreAccountModel::CoreAccountModel(QObject *parent)
- : QAbstractListModel(parent),
- _internalAccount(0)
-{
-}
-
+CoreAccountModel::CoreAccountModel(QObject* parent)
+ : QAbstractListModel(parent)
+ , _internalAccount(0)
+{}
-CoreAccountModel::CoreAccountModel(const CoreAccountModel *other, QObject *parent)
- : QAbstractListModel(parent),
- _internalAccount(0)
+CoreAccountModel::CoreAccountModel(const CoreAccountModel* other, QObject* parent)
+ : QAbstractListModel(parent)
+ , _internalAccount(0)
{
update(other);
}
-
-void CoreAccountModel::update(const CoreAccountModel *other)
+void CoreAccountModel::update(const CoreAccountModel* other)
{
clear();
if (other->_accounts.count() > 0) {
- beginInsertRows(QModelIndex(), 0, other->_accounts.count() -1);
+ beginInsertRows(QModelIndex(), 0, other->_accounts.count() - 1);
_accounts = other->_accounts;
endInsertRows();
}
_removedAccounts = other->_removedAccounts;
}
-
void CoreAccountModel::load()
{
clear();
CoreAccountSettings s;
- foreach(AccountId accId, s.knownAccounts()) {
+ foreach (AccountId accId, s.knownAccounts()) {
QVariantMap map = s.retrieveAccountData(accId);
CoreAccount acc;
- acc.fromVariantMap(map); // TODO Hook into kwallet/password saving stuff
+ acc.fromVariantMap(map); // TODO Hook into kwallet/password saving stuff
insertAccount(acc);
}
if (Quassel::runMode() == Quassel::Monolithic && !internalAccount().isValid()) {
}
}
-
void CoreAccountModel::save()
{
CoreAccountSettings s;
- foreach(AccountId id, _removedAccounts) {
+ foreach (AccountId id, _removedAccounts) {
s.removeAccount(id);
}
_removedAccounts.clear();
- foreach(const CoreAccount &acc, accounts()) {
- QVariantMap map = acc.toVariantMap(false); // TODO Hook into kwallet/password saving stuff
+ foreach (const CoreAccount& acc, accounts()) {
+ QVariantMap map = acc.toVariantMap(false); // TODO Hook into kwallet/password saving stuff
s.storeAccountData(acc.accountId(), map);
}
}
-
void CoreAccountModel::clear()
{
beginResetModel();
endResetModel();
}
-
-QVariant CoreAccountModel::data(const QModelIndex &index, int role) const
+QVariant CoreAccountModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid() || index.row() >= rowCount() || index.column() >= 1)
return QVariant();
- const CoreAccount &acc = accounts().at(index.row());
+ const CoreAccount& acc = accounts().at(index.row());
switch (role) {
case Qt::DisplayRole:
}
}
-
CoreAccount CoreAccountModel::account(AccountId id) const
{
int idx = findAccountIdx(id);
return CoreAccount();
}
-
-CoreAccount CoreAccountModel::account(const QModelIndex &idx) const
+CoreAccount CoreAccountModel::account(const QModelIndex& idx) const
{
if (idx.isValid() && idx.row() < _accounts.count())
return _accounts.value(idx.row());
return CoreAccount();
}
-
QList<CoreAccount> CoreAccountModel::accounts() const
{
return _accounts;
}
-
QList<AccountId> CoreAccountModel::accountIds() const
{
QList<AccountId> list;
- foreach(const CoreAccount &acc, accounts())
- list << acc.accountId();
+ foreach (const CoreAccount& acc, accounts())
+ list << acc.accountId();
return list;
}
-
-bool CoreAccountModel::operator==(const CoreAccountModel &other) const
+bool CoreAccountModel::operator==(const CoreAccountModel& other) const
{
return _accounts == other._accounts;
}
-
-bool CoreAccountModel::operator!=(const CoreAccountModel &other) const
+bool CoreAccountModel::operator!=(const CoreAccountModel& other) const
{
return !(*this == other);
}
-
// TODO with Qt 4.6, use QAbstractItemModel move semantics to properly do this
-AccountId CoreAccountModel::createOrUpdateAccount(const CoreAccount &newAcc)
+AccountId CoreAccountModel::createOrUpdateAccount(const CoreAccount& newAcc)
{
CoreAccount acc = newAcc;
if (!acc.accountId().isValid()) {
// find free Id
AccountId newId = 0;
- const QList<AccountId> &ids = accountIds();
+ const QList<AccountId>& ids = accountIds();
for (int i = 1;; i++) {
if (!_removedAccounts.contains(i) && !ids.contains(i)) {
newId = i;
return acc.accountId();
}
-
-void CoreAccountModel::insertAccount(const CoreAccount &acc)
+void CoreAccountModel::insertAccount(const CoreAccount& acc)
{
if (acc.isInternal()) {
if (internalAccount().isValid()) {
// check for Quuid
int idx = 0;
- while (idx<_accounts.count() && acc.accountName()> _accounts.at(idx).accountName() && !acc.isInternal())
+ while (idx < _accounts.count() && acc.accountName() > _accounts.at(idx).accountName() && !acc.isInternal())
++idx;
beginInsertRows(QModelIndex(), idx, idx);
endInsertRows();
}
-
CoreAccount CoreAccountModel::takeAccount(AccountId accId)
{
int idx = findAccountIdx(accId);
return acc;
}
-
void CoreAccountModel::removeAccount(AccountId accId)
{
takeAccount(accId);
_removedAccounts.insert(accId);
}
-
QModelIndex CoreAccountModel::accountIndex(AccountId accId) const
{
for (int i = 0; i < _accounts.count(); i++) {
return {};
}
-
int CoreAccountModel::findAccountIdx(AccountId id) const
{
QModelIndex idx = accountIndex(id);
Q_OBJECT
public:
- enum {
+ enum
+ {
AccountIdRole = Qt::UserRole,
UuidRole
};
- CoreAccountModel(QObject *parent = nullptr);
- CoreAccountModel(const CoreAccountModel *other, QObject *parent = nullptr);
+ CoreAccountModel(QObject* parent = nullptr);
+ CoreAccountModel(const CoreAccountModel* other, QObject* parent = nullptr);
- inline int rowCount(const QModelIndex &parent = QModelIndex()) const override;
- QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
+ inline int rowCount(const QModelIndex& parent = QModelIndex()) const override;
+ QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
- CoreAccount account(const QModelIndex &) const;
+ CoreAccount account(const QModelIndex&) const;
CoreAccount account(AccountId) const;
QList<CoreAccount> accounts() const;
QList<AccountId> accountIds() const;
inline AccountId internalAccount() const;
- AccountId createOrUpdateAccount(const CoreAccount &newAccountData);
+ AccountId createOrUpdateAccount(const CoreAccount& newAccountData);
CoreAccount takeAccount(AccountId);
void removeAccount(AccountId);
- void update(const CoreAccountModel *other);
+ void update(const CoreAccountModel* other);
- bool operator==(const CoreAccountModel &other) const;
- bool operator!=(const CoreAccountModel &other) const;
+ bool operator==(const CoreAccountModel& other) const;
+ bool operator!=(const CoreAccountModel& other) const;
public slots:
void save();
void clear();
protected:
- void insertAccount(const CoreAccount &);
+ void insertAccount(const CoreAccount&);
int findAccountIdx(AccountId) const;
private:
AccountId _internalAccount;
};
-
// Inlines
-int CoreAccountModel::rowCount(const QModelIndex &) const
+int CoreAccountModel::rowCount(const QModelIndex&) const
{
return _accounts.count();
}
-
AccountId CoreAccountModel::internalAccount() const
{
return _internalAccount;
#include "protocols/legacy/legacypeer.h"
-CoreConnection::CoreConnection(QObject *parent)
- : QObject(parent),
- _authHandler(nullptr)
+CoreConnection::CoreConnection(QObject* parent)
+ : QObject(parent)
+ , _authHandler(nullptr)
{
qRegisterMetaType<ConnectionState>("CoreConnection::ConnectionState");
}
-
void CoreConnection::init()
{
Client::signalProxy()->setHeartBeatInterval(30);
networkDetectionModeChanged(s.networkDetectionMode());
}
-
-CoreAccountModel *CoreConnection::accountModel() const
+CoreAccountModel* CoreConnection::accountModel() const
{
return Client::coreAccountModel();
}
-
-void CoreConnection::setProgressText(const QString &text)
+void CoreConnection::setProgressText(const QString& text)
{
if (_progressText != text) {
_progressText = text;
}
}
-
void CoreConnection::setProgressValue(int value)
{
if (_progressValue != value) {
}
}
-
void CoreConnection::setProgressMinimum(int minimum)
{
if (_progressMinimum != minimum) {
}
}
-
void CoreConnection::setProgressMaximum(int maximum)
{
if (_progressMaximum != maximum) {
}
}
-
void CoreConnection::updateProgress(int value, int max)
{
if (max != _progressMaximum) {
setProgressValue(value);
}
-
void CoreConnection::reconnectTimeout()
{
if (!_peer) {
if (_wantReconnect && s.autoReconnect()) {
// If using QNetworkConfigurationManager, we don't want to reconnect if we're offline
if (s.networkDetectionMode() == CoreConnectionSettings::UseQNetworkConfigurationManager) {
- if (!_qNetworkConfigurationManager->isOnline()) {
+ if (!_qNetworkConfigurationManager->isOnline()) {
return;
- }
+ }
}
reconnectToCore();
}
}
}
-
-void CoreConnection::networkDetectionModeChanged(const QVariant &vmode)
+void CoreConnection::networkDetectionModeChanged(const QVariant& vmode)
{
CoreConnectionSettings s;
auto mode = (CoreConnectionSettings::NetworkDetectionMode)vmode.toInt();
}
}
-
-void CoreConnection::pingTimeoutIntervalChanged(const QVariant &interval)
+void CoreConnection::pingTimeoutIntervalChanged(const QVariant& interval)
{
CoreConnectionSettings s;
if (s.networkDetectionMode() == CoreConnectionSettings::UsePingTimeout)
Client::signalProxy()->setMaxHeartBeatCount(interval.toInt() / 30); // interval is 30 seconds
}
-
-void CoreConnection::reconnectIntervalChanged(const QVariant &interval)
+void CoreConnection::reconnectIntervalChanged(const QVariant& interval)
{
_reconnectTimer.setInterval(interval.toInt() * 1000);
}
-
void CoreConnection::onlineStateChanged(bool isOnline)
{
CoreConnectionSettings s;
if (s.networkDetectionMode() != CoreConnectionSettings::UseQNetworkConfigurationManager)
return;
- if(isOnline) {
+ if (isOnline) {
// qDebug() << "QNetworkConfigurationManager reports Online";
if (state() == Disconnected) {
if (_wantReconnect && s.autoReconnect()) {
reconnectToCore();
}
}
- } else {
+ }
+ else {
// qDebug() << "QNetworkConfigurationManager reports Offline";
if (state() != Disconnected && !isLocalConnection())
disconnectFromCore(tr("Network is down"), true);
}
}
-
QPointer<Peer> CoreConnection::peer() const
{
if (_peer) {
return _authHandler ? _authHandler->peer() : nullptr;
}
-
bool CoreConnection::isEncrypted() const
{
return _peer && _peer->isSecure();
}
-
bool CoreConnection::isLocalConnection() const
{
if (!isConnected())
return false;
}
-
void CoreConnection::onConnectionReady()
{
setState(Connected);
}
-
void CoreConnection::setState(ConnectionState state)
{
if (state != _state) {
}
}
-
-void CoreConnection::coreSocketError(QAbstractSocket::SocketError error, const QString &errorString)
+void CoreConnection::coreSocketError(QAbstractSocket::SocketError error, const QString& errorString)
{
Q_UNUSED(error)
disconnectFromCore(errorString, true);
}
-
void CoreConnection::coreSocketDisconnected()
{
setState(Disconnected);
resetConnection(_wantReconnect);
}
-
void CoreConnection::disconnectFromCore()
{
- disconnectFromCore(QString(), false); // requested disconnect, so don't try to reconnect
+ disconnectFromCore(QString(), false); // requested disconnect, so don't try to reconnect
}
-
-void CoreConnection::disconnectFromCore(const QString &errorString, bool wantReconnect)
+void CoreConnection::disconnectFromCore(const QString& errorString, bool wantReconnect)
{
if (wantReconnect)
_reconnectTimer.start();
else
_reconnectTimer.stop();
- _wantReconnect = wantReconnect; // store if disconnect was requested
+ _wantReconnect = wantReconnect; // store if disconnect was requested
_wasReconnect = false;
if (_authHandler)
_authHandler->close();
- else if(_peer)
+ else if (_peer)
_peer->close();
if (errorString.isEmpty())
emit connectionError(errorString);
}
-
void CoreConnection::resetConnection(bool wantReconnect)
{
if (_resetting)
_netsToSync.clear();
_numNetsToSync = 0;
- setProgressMaximum(-1); // disable
+ setProgressMaximum(-1); // disable
setState(Disconnected);
emit lagUpdated(-1);
_resetting = false;
}
-
void CoreConnection::reconnectToCore()
{
if (currentAccount().isValid()) {
}
}
-
bool CoreConnection::connectToCore(AccountId accId)
{
if (isConnected())
return true;
}
-
void CoreConnection::connectToCurrentAccount()
{
if (_authHandler) {
return;
}
- auto *peer = new InternalPeer();
+ auto* peer = new InternalPeer();
_peer = peer;
- Client::instance()->signalProxy()->addPeer(peer); // sigproxy will take ownership
+ Client::instance()->signalProxy()->addPeer(peer); // sigproxy will take ownership
emit connectionMsg(tr("Initializing..."));
emit connectToInternalCore(peer);
setState(Connected);
connect(_authHandler, &ClientAuthHandler::connectionReady, this, &CoreConnection::onConnectionReady);
connect(_authHandler, &ClientAuthHandler::socketError, this, &CoreConnection::coreSocketError);
connect(_authHandler, &ClientAuthHandler::transferProgress, this, &CoreConnection::updateProgress);
- connect(_authHandler, &ClientAuthHandler::requestDisconnect, this, selectOverload<const QString&, bool>(&CoreConnection::disconnectFromCore));
+ connect(_authHandler,
+ &ClientAuthHandler::requestDisconnect,
+ this,
+ selectOverload<const QString&, bool>(&CoreConnection::disconnectFromCore));
connect(_authHandler, &ClientAuthHandler::errorMessage, this, &CoreConnection::connectionError);
connect(_authHandler, &ClientAuthHandler::errorPopup, this, &CoreConnection::connectionErrorPopup, Qt::QueuedConnection);
_authHandler->connectToCore();
}
-
-void CoreConnection::setupCore(const Protocol::SetupData &setupData)
+void CoreConnection::setupCore(const Protocol::SetupData& setupData)
{
_authHandler->setupCore(setupData);
}
-
-void CoreConnection::loginToCore(const QString &user, const QString &password, bool remember)
+void CoreConnection::loginToCore(const QString& user, const QString& password, bool remember)
{
_authHandler->login(user, password, remember);
}
-
-void CoreConnection::onLoginSuccessful(const CoreAccount &account)
+void CoreConnection::onLoginSuccessful(const CoreAccount& account)
{
updateProgress(0, 0);
emit connectionMsg(tr("Synchronizing to %1...").arg(account.accountName()));
}
-
-void CoreConnection::onHandshakeComplete(RemotePeer *peer, const Protocol::SessionState &sessionState)
+void CoreConnection::onHandshakeComplete(RemotePeer* peer, const Protocol::SessionState& sessionState)
{
updateProgress(100, 100);
syncToCore(sessionState);
}
-
-void CoreConnection::internalSessionStateReceived(const Protocol::SessionState &sessionState)
+void CoreConnection::internalSessionStateReceived(const Protocol::SessionState& sessionState)
{
updateProgress(100, 100);
setState(Synchronizing);
syncToCore(sessionState);
}
-
-void CoreConnection::syncToCore(const Protocol::SessionState &sessionState)
+void CoreConnection::syncToCore(const Protocol::SessionState& sessionState)
{
setProgressText(tr("Receiving network states"));
updateProgress(0, 100);
// create identities
- foreach(const QVariant &vid, sessionState.identities) {
+ foreach (const QVariant& vid, sessionState.identities) {
Client::instance()->coreIdentityCreated(vid.value<Identity>());
}
// create buffers
// FIXME: get rid of this crap -- why?
- NetworkModel *networkModel = Client::networkModel();
+ NetworkModel* networkModel = Client::networkModel();
Q_ASSERT(networkModel);
- foreach(const QVariant &vinfo, sessionState.bufferInfos)
+ foreach (const QVariant& vinfo, sessionState.bufferInfos)
networkModel->bufferUpdated(vinfo.value<BufferInfo>()); // create BufferItems
// prepare sync progress thingys...
updateProgress(0, _numNetsToSync);
// create network objects
- foreach(const QVariant &networkid, sessionState.networkIds) {
+ foreach (const QVariant& networkid, sessionState.networkIds) {
NetworkId netid = networkid.value<NetworkId>();
if (Client::network(netid))
continue;
- auto *net = new Network(netid, Client::instance());
+ auto* net = new Network(netid, Client::instance());
_netsToSync.insert(net);
connect(net, &SyncableObject::initDone, this, &CoreConnection::networkInitDone);
connect(net, &QObject::destroyed, this, &CoreConnection::networkInitDone);
checkSyncState();
}
-
// this is also called for destroyed networks!
void CoreConnection::networkInitDone()
{
- QObject *net = sender();
+ QObject* net = sender();
Q_ASSERT(net);
disconnect(net, nullptr, this, nullptr);
_netsToSync.remove(net);
checkSyncState();
}
-
void CoreConnection::checkSyncState()
{
if (_netsToSync.isEmpty() && state() >= Synchronizing) {
#include <QTimer>
#ifdef HAVE_SSL
-# include <QSslSocket>
+# include <QSslSocket>
#else
-# include <QTcpSocket>
+# include <QTcpSocket>
#endif
#include "coreaccount.h"
Q_OBJECT
public:
- enum ConnectionState {
+ enum ConnectionState
+ {
Disconnected,
Connecting,
Connected,
Synchronized
};
- CoreConnection(QObject *parent = nullptr);
+ CoreConnection(QObject* parent = nullptr);
void init();
bool connectToCore(AccountId = 0);
void reconnectToCore();
void disconnectFromCore();
- void internalSessionStateReceived(const Protocol::SessionState &sessionState);
+ void internalSessionStateReceived(const Protocol::SessionState& sessionState);
- void setupCore(const Protocol::SetupData &setupData);
+ void setupCore(const Protocol::SetupData& setupData);
signals:
void stateChanged(CoreConnection::ConnectionState);
void synchronized();
void lagUpdated(int msecs);
- void connectionError(const QString &errorMsg);
- void connectionErrorPopup(const QString &errorMsg);
- void connectionMsg(const QString &msg);
+ void connectionError(const QString& errorMsg);
+ void connectionErrorPopup(const QString& errorMsg);
+ void connectionMsg(const QString& msg);
void disconnected();
void progressRangeChanged(int minimum, int maximum);
void progressValueChanged(int value);
- void progressTextChanged(const QString &);
+ void progressTextChanged(const QString&);
- void startCoreSetup(const QVariantList &backendInfo, const QVariantList &authenticatorInfo);
+ void startCoreSetup(const QVariantList& backendInfo, const QVariantList& authenticatorInfo);
void coreSetupSuccess();
- void coreSetupFailed(const QString &error);
+ void coreSetupFailed(const QString& error);
void connectToInternalCore(QPointer<InternalPeer> connection);
// These signals MUST be handled synchronously!
- void userAuthenticationRequired(CoreAccount *, bool *valid, const QString &errorMessage = QString());
- void handleNoSslInClient(bool *accepted);
- void handleNoSslInCore(bool *accepted);
+ void userAuthenticationRequired(CoreAccount*, bool* valid, const QString& errorMessage = QString());
+ void handleNoSslInClient(bool* accepted);
+ void handleNoSslInCore(bool* accepted);
#ifdef HAVE_SSL
- void handleSslErrors(const QSslSocket *socket, bool *accepted, bool *permanently);
+ void handleSslErrors(const QSslSocket* socket, bool* accepted, bool* permanently);
#endif
private slots:
void connectToCurrentAccount();
- void disconnectFromCore(const QString &errorString, bool wantReconnect = true);
+ void disconnectFromCore(const QString& errorString, bool wantReconnect = true);
- void coreSocketError(QAbstractSocket::SocketError error, const QString &errorString);
+ void coreSocketError(QAbstractSocket::SocketError error, const QString& errorString);
void coreSocketDisconnected();
// for sync progress
void networkInitDone();
void checkSyncState();
- void loginToCore(const QString &user, const QString &password, bool remember); // for config wizard
- void syncToCore(const Protocol::SessionState &sessionState);
+ void loginToCore(const QString& user, const QString& password, bool remember); // for config wizard
+ void syncToCore(const Protocol::SessionState& sessionState);
void resetConnection(bool wantReconnect = false);
void onConnectionReady();
- void onLoginSuccessful(const CoreAccount &account);
- void onHandshakeComplete(RemotePeer *peer, const Protocol::SessionState &sessionState);
+ void onLoginSuccessful(const CoreAccount& account);
+ void onHandshakeComplete(RemotePeer* peer, const Protocol::SessionState& sessionState);
void updateProgress(int value, int maximum);
- void setProgressText(const QString &text);
+ void setProgressText(const QString& text);
void setProgressValue(int value);
void setProgressMinimum(int minimum);
void setProgressMaximum(int maximum);
void setState(ConnectionState state);
- void networkDetectionModeChanged(const QVariant &mode);
- void pingTimeoutIntervalChanged(const QVariant &interval);
- void reconnectIntervalChanged(const QVariant &interval);
+ void networkDetectionModeChanged(const QVariant& mode);
+ void pingTimeoutIntervalChanged(const QVariant& interval);
+ void reconnectIntervalChanged(const QVariant& interval);
void reconnectTimeout();
void onlineStateChanged(bool isOnline);
bool _wantReconnect{false};
bool _wasReconnect{false};
- QSet<QObject *> _netsToSync;
+ QSet<QObject*> _netsToSync;
int _numNetsToSync;
int _progressMinimum{0}, _progressMaximum{-1}, _progressValue{-1};
QString _progressText;
bool _resetting{false};
CoreAccount _account;
- CoreAccountModel *accountModel() const;
+ CoreAccountModel* accountModel() const;
QPointer<QNetworkConfigurationManager> _qNetworkConfigurationManager;
friend class CoreConfigWizard;
};
-
Q_DECLARE_METATYPE(CoreConnection::ConnectionState)
// Inlines
-inline int CoreConnection::progressMinimum() const { return _progressMinimum; }
-inline int CoreConnection::progressMaximum() const { return _progressMaximum; }
-inline int CoreConnection::progressValue() const { return _progressValue; }
-inline QString CoreConnection::progressText() const { return _progressText; }
-
-inline CoreConnection::ConnectionState CoreConnection::state() const { return _state; }
-inline bool CoreConnection::isConnected() const { return state() >= Connected; }
-inline CoreAccount CoreConnection::currentAccount() const { return _account; }
+inline int CoreConnection::progressMinimum() const
+{
+ return _progressMinimum;
+}
+inline int CoreConnection::progressMaximum() const
+{
+ return _progressMaximum;
+}
+inline int CoreConnection::progressValue() const
+{
+ return _progressValue;
+}
+inline QString CoreConnection::progressText() const
+{
+ return _progressText;
+}
+
+inline CoreConnection::ConnectionState CoreConnection::state() const
+{
+ return _state;
+}
+inline bool CoreConnection::isConnected() const
+{
+ return state() >= Connected;
+}
+inline CoreAccount CoreConnection::currentAccount() const
+{
+ return _account;
+}
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "execwrapper.h"
+
#include <QFile>
#include <QTextCodec>
-#include "execwrapper.h"
-
#include "client.h"
#include "messagemodel.h"
#include "quassel.h"
#include "util.h"
-ExecWrapper::ExecWrapper(QObject *parent) : QObject(parent)
+ExecWrapper::ExecWrapper(QObject* parent)
+ : QObject(parent)
{
connect(&_process, &QProcess::readyReadStandardOutput, this, &ExecWrapper::processReadStdout);
connect(&_process, &QProcess::readyReadStandardError, this, &ExecWrapper::processReadStderr);
connect(this, &ExecWrapper::error, this, &ExecWrapper::postStderr);
}
-
-void ExecWrapper::start(const BufferInfo &info, const QString &command)
+void ExecWrapper::start(const BufferInfo& info, const QString& command)
{
_bufferInfo = info;
QString params;
emit error(tr(R"(Name "%1" is invalid: ../ or ..\ are not allowed!)").arg(_scriptName));
else {
- foreach(QString scriptDir, Quassel::scriptDirPaths()) {
+ foreach (QString scriptDir, Quassel::scriptDirPaths()) {
QString fileName = scriptDir + _scriptName;
if (!QFile::exists(fileName))
continue;
emit error(tr("Could not find script \"%1\"").arg(_scriptName));
}
- deleteLater(); // self-destruct
+ deleteLater(); // self-destruct
}
-
-void ExecWrapper::postStdout(const QString &msg)
+void ExecWrapper::postStdout(const QString& msg)
{
if (_bufferInfo.isValid())
Client::userInput(_bufferInfo, msg);
}
-
-void ExecWrapper::postStderr(const QString &msg)
+void ExecWrapper::postStderr(const QString& msg)
{
if (_bufferInfo.isValid())
Client::messageModel()->insertErrorMessage(_bufferInfo, msg);
}
-
void ExecWrapper::processFinished(int exitCode, QProcess::ExitStatus status)
{
if (status == QProcess::CrashExit) {
// empty buffers
if (!_stdoutBuffer.isEmpty())
- foreach(QString msg, _stdoutBuffer.split('\n'))
- emit output(msg);
+ foreach (QString msg, _stdoutBuffer.split('\n'))
+ emit output(msg);
if (!_stderrBuffer.isEmpty())
- foreach(QString msg, _stderrBuffer.split('\n'))
- emit error(msg);
+ foreach (QString msg, _stderrBuffer.split('\n'))
+ emit error(msg);
deleteLater();
}
-
void ExecWrapper::processError(QProcess::ProcessError err)
{
if (err == QProcess::FailedToStart)
deleteLater();
}
-
void ExecWrapper::processReadStdout()
{
QString str = QTextCodec::codecForLocale()->toUnicode(_process.readAllStandardOutput());
}
}
-
void ExecWrapper::processReadStderr()
{
QString str = QTextCodec::codecForLocale()->toUnicode(_process.readAllStandardError());
Q_OBJECT
public:
- ExecWrapper(QObject *parent = nullptr);
+ ExecWrapper(QObject* parent = nullptr);
public slots:
- void start(const BufferInfo &info, const QString &command);
+ void start(const BufferInfo& info, const QString& command);
signals:
- void error(const QString &errorMsg);
- void output(const QString &out);
+ void error(const QString& errorMsg);
+ void output(const QString& out);
private slots:
void processReadStdout();
void processFinished(int exitCode, QProcess::ExitStatus exitStatus);
void processError(QProcess::ProcessError);
- void postStdout(const QString &);
- void postStderr(const QString &);
+ void postStdout(const QString&);
+ void postStderr(const QString&);
private:
QProcess _process;
QString _stderrBuffer;
};
-
#endif
#include <QStringList>
-IrcListModel::IrcListModel(QObject *parent)
+IrcListModel::IrcListModel(QObject* parent)
: QAbstractItemModel(parent)
-{
-}
+{}
-
-QVariant IrcListModel::data(const QModelIndex &index, int role) const
+QVariant IrcListModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid() || index.row() >= rowCount() || index.column() >= columnCount() || role != Qt::DisplayRole)
return QVariant();
}
}
-
-Qt::ItemFlags IrcListModel::flags(const QModelIndex &index) const
+Qt::ItemFlags IrcListModel::flags(const QModelIndex& index) const
{
if (!index.isValid()) {
return Qt::ItemIsDropEnabled;
}
}
-
QVariant IrcListModel::headerData(int section, Qt::Orientation orientation, int role) const
{
QStringList header;
- header << tr("Channel")
- << tr("Users")
- << tr("Topic");
+ header << tr("Channel") << tr("Users") << tr("Topic");
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return header[section];
return QVariant();
}
-
-QModelIndex IrcListModel::index(int row, int column, const QModelIndex &parent) const
+QModelIndex IrcListModel::index(int row, int column, const QModelIndex& parent) const
{
Q_UNUSED(parent);
if (row >= rowCount() || column >= columnCount())
return createIndex(row, column);
}
-
-void IrcListModel::setChannelList(const QList<IrcListHelper::ChannelDescription> &channelList)
+void IrcListModel::setChannelList(const QList<IrcListHelper::ChannelDescription>& channelList)
{
if (rowCount() > 0) {
beginRemoveRows(QModelIndex(), 0, _channelList.count() - 1);
#include "client-export.h"
-#include "irclisthelper.h"
-
#include <QAbstractItemModel>
+#include "irclisthelper.h"
+
class CLIENT_EXPORT IrcListModel : public QAbstractItemModel
{
Q_OBJECT
public:
- IrcListModel(QObject *parent = nullptr);
+ IrcListModel(QObject* parent = nullptr);
- QVariant data(const QModelIndex &index, int role) const override;
- Qt::ItemFlags flags(const QModelIndex &index) const override;
+ QVariant data(const QModelIndex& index, int role) const override;
+ Qt::ItemFlags flags(const QModelIndex& index) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
- QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override;
+ QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override;
- inline QModelIndex parent(const QModelIndex &) const override { return {}; }
+ inline QModelIndex parent(const QModelIndex&) const override { return {}; }
- inline int rowCount(const QModelIndex &parent = QModelIndex()) const override { Q_UNUSED(parent) return _channelList.count(); }
- inline int columnCount(const QModelIndex &parent = QModelIndex()) const override { Q_UNUSED(parent) return 3; }
+ inline int rowCount(const QModelIndex& parent = QModelIndex()) const override { Q_UNUSED(parent) return _channelList.count(); }
+ inline int columnCount(const QModelIndex& parent = QModelIndex()) const override { Q_UNUSED(parent) return 3; }
public slots:
- void setChannelList(const QList<IrcListHelper::ChannelDescription> &channelList = QList<IrcListHelper::ChannelDescription>());
+ void setChannelList(const QList<IrcListHelper::ChannelDescription>& channelList = QList<IrcListHelper::ChannelDescription>());
private:
QList<IrcListHelper::ChannelDescription> _channelList;
#include <algorithm>
+#include "buffermodel.h"
#include "buffersettings.h"
#include "client.h"
-#include "buffermodel.h"
+#include "clientignorelistmanager.h"
#include "messagemodel.h"
#include "networkmodel.h"
-#include "clientignorelistmanager.h"
-MessageFilter::MessageFilter(QAbstractItemModel *source, QObject *parent)
- : QSortFilterProxyModel(parent),
- _messageTypeFilter(0)
+MessageFilter::MessageFilter(QAbstractItemModel* source, QObject* parent)
+ : QSortFilterProxyModel(parent)
+ , _messageTypeFilter(0)
{
init();
setSourceModel(source);
}
-
-MessageFilter::MessageFilter(MessageModel *source, const QList<BufferId> &buffers, QObject *parent)
- : QSortFilterProxyModel(parent),
- _validBuffers(buffers.toSet()),
- _messageTypeFilter(0)
+MessageFilter::MessageFilter(MessageModel* source, const QList<BufferId>& buffers, QObject* parent)
+ : QSortFilterProxyModel(parent)
+ , _validBuffers(buffers.toSet())
+ , _messageTypeFilter(0)
{
init();
setSourceModel(source);
}
-
void MessageFilter::init()
{
setDynamicSortFilter(true);
mySettings.notify("hasMessageTypeFilter", this, &MessageFilter::messageTypeFilterChanged);
}
-
void MessageFilter::messageTypeFilterChanged()
{
int newFilter;
}
}
-
void MessageFilter::messageRedirectionChanged()
{
BufferSettings bufferSettings;
invalidateFilter();
}
-
QString MessageFilter::idString() const
{
if (_validBuffers.isEmpty())
qSort(bufferIds);
QStringList bufferIdStrings;
- foreach(BufferId id, bufferIds)
- bufferIdStrings << QString::number(id.toInt());
+ foreach (BufferId id, bufferIds)
+ bufferIdStrings << QString::number(id.toInt());
return bufferIdStrings.join("|");
}
-
-bool MessageFilter::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
+bool MessageFilter::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const
{
Q_UNUSED(sourceParent);
QModelIndex sourceIdx = sourceModel()->index(sourceRow, 2);
// ignorelist handling
// only match if message is not flagged as server msg
if (!(flags & Message::ServerMsg) && Client::ignoreListManager()
- && Client::ignoreListManager()->match(sourceIdx.data(MessageModel::MessageRole).value<Message>(), Client::networkModel()->networkName(bufferId)))
+ && Client::ignoreListManager()->match(sourceIdx.data(MessageModel::MessageRole).value<Message>(),
+ Client::networkModel()->networkName(bufferId)))
return false;
if (flags & Message::Redirected) {
return false;
// Extract timestamp and nickname from the new quit message
- qint64 messageTimestamp = sourceModel()->data(sourceIdx, MessageModel::TimestampRole)
- .value<QDateTime>().toMSecsSinceEpoch();
- QString quiter = nickFromMask(sourceModel()->data(sourceIdx, MessageModel::MessageRole)
- .value<Message>().sender()).toLower();
+ qint64 messageTimestamp = sourceModel()->data(sourceIdx, MessageModel::TimestampRole).value<QDateTime>().toMSecsSinceEpoch();
+ QString quiter = nickFromMask(sourceModel()->data(sourceIdx, MessageModel::MessageRole).value<Message>().sender()).toLower();
// Check that nickname matches query name
if (quiter != bufferName().toLower())
// Check if a quit message was already forwarded within +/- 1000 ms
static constexpr qint64 MAX_QUIT_DELTA_MS = 1 * 1000;
// No need to check if it's the appropriate buffer, each query has a unique message filter
- if (std::binary_search(_filteredQuitMsgTime.begin(), _filteredQuitMsgTime.end(),
- messageTimestamp,
- [](qint64 a, qint64 b) { return ((a + MAX_QUIT_DELTA_MS) < b); } )) {
+ if (std::binary_search(_filteredQuitMsgTime.begin(), _filteredQuitMsgTime.end(), messageTimestamp, [](qint64 a, qint64 b) {
+ return ((a + MAX_QUIT_DELTA_MS) < b);
+ })) {
// New element is less than if at least 1000 ms older/newer
// Match found, no need to forward another quit message
return false;
}
// Mark query as having a quit message inserted
- auto *that = const_cast<MessageFilter *>(this);
+ auto* that = const_cast<MessageFilter*>(this);
that->_filteredQuitMsgTime.insert(messageTimestamp);
return true;
}
}
-
void MessageFilter::requestBacklog()
{
QSet<BufferId>::const_iterator bufferIdIter = _validBuffers.constBegin();
#include "client-export.h"
-#include <QSortFilterProxyModel>
#include <set>
+#include <QSortFilterProxyModel>
+
#include "bufferinfo.h"
#include "client.h"
#include "messagemodel.h"
Q_OBJECT
protected:
- MessageFilter(QAbstractItemModel *source, QObject *parent = nullptr);
+ MessageFilter(QAbstractItemModel* source, QObject* parent = nullptr);
public:
- MessageFilter(MessageModel *, const QList<BufferId> &buffers = QList<BufferId>(), QObject *parent = nullptr);
+ MessageFilter(MessageModel*, const QList<BufferId>& buffers = QList<BufferId>(), QObject* parent = nullptr);
virtual QString idString() const;
bool isSingleBufferFilter() const { return _validBuffers.count() == 1; }
BufferId singleBufferId() const { return *(_validBuffers.constBegin()); }
- bool containsBuffer(const BufferId &id) const { return _validBuffers.contains(id); }
+ bool containsBuffer(const BufferId& id) const { return _validBuffers.contains(id); }
QSet<BufferId> containedBuffers() const { return _validBuffers; }
- bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override;
+ bool filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const override;
public slots:
void messageTypeFilterChanged();
void init();
QSet<BufferId> _validBuffers;
- std::set<qint64> _filteredQuitMsgTime; ///< Timestamps (ms) of already forwarded quit messages
+ std::set<qint64> _filteredQuitMsgTime; ///< Timestamps (ms) of already forwarded quit messages
int _messageTypeFilter;
int _userNoticesTarget;
#include <QEvent>
#include "backlogsettings.h"
-#include "clientbacklogmanager.h"
#include "client.h"
+#include "clientbacklogmanager.h"
#include "message.h"
#include "networkmodel.h"
class ProcessBufferEvent : public QEvent
{
public:
- inline ProcessBufferEvent() : QEvent(QEvent::User) {}
+ inline ProcessBufferEvent()
+ : QEvent(QEvent::User)
+ {}
};
-
-MessageModel::MessageModel(QObject *parent)
+MessageModel::MessageModel(QObject* parent)
: QAbstractItemModel(parent)
{
QDateTime now = QDateTime::currentDateTime();
now.setTimeSpec(Qt::UTC);
_nextDayChange.setTimeSpec(Qt::UTC);
- _nextDayChange.setMSecsSinceEpoch(
- ((now.toMSecsSinceEpoch() / DAY_IN_MSECS) + 1) * DAY_IN_MSECS);
+ _nextDayChange.setMSecsSinceEpoch(((now.toMSecsSinceEpoch() / DAY_IN_MSECS) + 1) * DAY_IN_MSECS);
_nextDayChange.setTimeSpec(Qt::LocalTime);
_dayChangeTimer.setInterval(QDateTime::currentDateTime().secsTo(_nextDayChange) * 1000);
_dayChangeTimer.start();
connect(&_dayChangeTimer, &QTimer::timeout, this, &MessageModel::changeOfDay);
}
-
-QVariant MessageModel::data(const QModelIndex &index, int role) const
+QVariant MessageModel::data(const QModelIndex& index, int role) const
{
- int row = index.row(); int column = index.column();
+ int row = index.row();
+ int column = index.column();
if (row < 0 || row >= messageCount() || column < 0)
return QVariant();
// return _messageList[row]->data(index.column(), role);
}
-
-bool MessageModel::setData(const QModelIndex &index, const QVariant &value, int role)
+bool MessageModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
int row = index.row();
if (row < 0 || row >= messageCount())
return false;
}
-
-bool MessageModel::insertMessage(const Message &msg, bool fakeMsg)
+bool MessageModel::insertMessage(const Message& msg, bool fakeMsg)
{
MsgId id = msg.msgId();
int idx = indexForId(id);
- if (!fakeMsg && idx < messageCount()) { // check for duplicate
+ if (!fakeMsg && idx < messageCount()) { // check for duplicate
if (messageItemAt(idx)->msgId() == id)
return false;
}
return true;
}
-
-void MessageModel::insertMessages(const QList<Message> &msglist)
+void MessageModel::insertMessages(const QList<Message>& msglist)
{
if (msglist.isEmpty())
return;
}
}
-
-void MessageModel::insertMessageGroup(const QList<Message> &msglist)
+void MessageModel::insertMessageGroup(const QList<Message>& msglist)
{
- Q_ASSERT(!msglist.isEmpty()); // the msglist can be assumed to be non empty
-// int last = msglist.count() - 1;
-// Q_ASSERT(0 == last || msglist.at(0).msgId() != msglist.at(last).msgId() || msglist.at(last).type() == Message::DayChange);
+ Q_ASSERT(!msglist.isEmpty()); // the msglist can be assumed to be non empty
+ // int last = msglist.count() - 1;
+ // Q_ASSERT(0 == last || msglist.at(0).msgId() != msglist.at(last).msgId() || msglist.at(last).type() == Message::DayChange);
int start = indexForId(msglist.first().msgId());
int end = start + msglist.count() - 1;
Message dayChangeMsg;
// check if the preceeding msg is a daychange message and if so if
// we have to drop or relocate it at the end of this chunk
int prevIdx = start - 1;
- if (messageItemAt(prevIdx)->msgType() == Message::DayChange
- && messageItemAt(prevIdx)->timestamp() > msglist.at(0).timestamp()) {
+ if (messageItemAt(prevIdx)->msgType() == Message::DayChange && messageItemAt(prevIdx)->timestamp() > msglist.at(0).timestamp()) {
beginRemoveRows(QModelIndex(), prevIdx, prevIdx);
Message oldDayChangeMsg = takeMessageAt(prevIdx);
if (msglist.last().timestamp() < oldDayChangeMsg.timestamp()) {
insertMessage__(start + msglist.count(), dayChangeMsg);
endInsertRows();
- Q_ASSERT(start == end || messageItemAt(start)->msgId() != messageItemAt(end)->msgId() || messageItemAt(end)->msgType() == Message::DayChange);
+ Q_ASSERT(start == end || messageItemAt(start)->msgId() != messageItemAt(end)->msgId()
+ || messageItemAt(end)->msgType() == Message::DayChange);
Q_ASSERT(start == 0 || messageItemAt(start - 1)->msgId() < messageItemAt(start)->msgId());
Q_ASSERT(end + 1 == messageCount() || messageItemAt(end)->msgId() < messageItemAt(end + 1)->msgId());
}
-
-int MessageModel::insertMessagesGracefully(const QList<Message> &msglist)
+int MessageModel::insertMessagesGracefully(const QList<Message>& msglist)
{
/* short description:
* 1) first we check where the message with the highest msgId from msglist would be inserted
QList<Message> grouplist;
MsgId minId;
MsgId dupeId;
- int processedMsgs = 1; // we know the list isn't empty, so we at least process one message
+ int processedMsgs = 1; // we know the list isn't empty, so we at least process one message
int idx;
bool fastForward = false;
QList<Message>::const_iterator iter;
if (inOrder) {
iter = msglist.constEnd();
- --iter; // this op is safe as we've allready passed an empty check
+ --iter; // this op is safe as we've allready passed an empty check
}
else {
iter = msglist.constBegin();
break;
processedMsgs++;
- if (grouplist.isEmpty()) { // as long as we don't have a starting point, we have to update the dupeId
+ if (grouplist.isEmpty()) { // as long as we don't have a starting point, we have to update the dupeId
idx = indexForId((*iter).msgId());
if (idx >= 0 && !messagesIsEmpty())
dupeId = messageItemAt(idx)->msgId();
break;
processedMsgs++;
- if (grouplist.isEmpty()) { // as long as we don't have a starting point, we have to update the dupeId
+ if (grouplist.isEmpty()) { // as long as we don't have a starting point, we have to update the dupeId
idx = indexForId((*iter).msgId());
if (idx >= 0 && !messagesIsEmpty())
dupeId = messageItemAt(idx)->msgId();
return processedMsgs;
}
-
-void MessageModel::customEvent(QEvent *event)
+void MessageModel::customEvent(QEvent* event)
{
if (event->type() != QEvent::User)
return;
QCoreApplication::postEvent(this, new ProcessBufferEvent());
}
-
void MessageModel::clear()
{
_messagesWaiting.clear();
}
}
-
// returns index of msg with given Id or of the next message after that (i.e., the index where we'd insert this msg)
int MessageModel::indexForId(MsgId id)
{
return messageCount();
// binary search
- int start = 0; int end = messageCount() - 1;
+ int start = 0;
+ int end = messageCount() - 1;
while (true) {
if (end - start == 1)
return end;
int pivot = (end + start) / 2;
- if (id <= messageItemAt(pivot)->msgId()) end = pivot;
- else